diff --git a/api/params_test.go b/api/params_test.go new file mode 100644 index 0000000000000000000000000000000000000000..df884878b4317cf1b984771db02285b7391b00c9 --- /dev/null +++ b/api/params_test.go @@ -0,0 +1,37 @@ +/////////////////////////////////////////////////////////////////////////////// +// Copyright © 2020 xx network SEZC // +// // +// Use of this source code is governed by a license that can be found in the // +// LICENSE file // +/////////////////////////////////////////////////////////////////////////////// + +package api + +import ( + "encoding/json" + "testing" +) + +func TestParams_MarshalUnmarshal(t *testing.T) { + p := GetDefaultParams() + data, err := json.Marshal(p) + if err != nil { + t.Fatalf("Marshal error: %+v", err) + } + + t.Logf("%s", string(data)) + + received := GetDefaultParams() + err = json.Unmarshal(data, &received) + if err != nil { + t.Fatalf("Unmarshal error: %+v", err) + } + + data2, err := json.Marshal(received) + if err != nil { + t.Fatalf("Marshal error: %+v", err) + } + + t.Logf("%s", string(data2)) + +} diff --git a/fileTransfer/params.go b/fileTransfer/params.go index 754bb88db3d45c75f3e47454f45bf4cf6170e830..8e54d5d02c9430224f526008d9138cb35e08e1ce 100644 --- a/fileTransfer/params.go +++ b/fileTransfer/params.go @@ -7,7 +7,10 @@ package fileTransfer -import "time" +import ( + "encoding/json" + "time" +) const ( defaultMaxThroughput = 150_000 // 150 kB per second @@ -26,6 +29,12 @@ type Params struct { SendTimeout time.Duration } +// paramsDisk will be the marshal-able and umarshal-able object. +type paramsDisk struct { + MaxThroughput int + SendTimeout time.Duration +} + // DefaultParams returns a Params object filled with the default values. func DefaultParams() Params { return Params{ @@ -33,3 +42,42 @@ func DefaultParams() Params { SendTimeout: defaultSendTimeout, } } + +// GetParameters returns the default network parameters, or override with given +// parameters, if set. +func GetParameters(params string) (Params, error) { + p := DefaultParams() + if len(params) > 0 { + err := json.Unmarshal([]byte(params), &p) + if err != nil { + return Params{}, err + } + } + return p, nil +} + +// MarshalJSON adheres to the json.Marshaler interface. +func (p Params) MarshalJSON() ([]byte, error) { + pDisk := paramsDisk{ + MaxThroughput: p.MaxThroughput, + SendTimeout: p.SendTimeout, + } + + return json.Marshal(&pDisk) +} + +// UnmarshalJSON adheres to the json.Unmarshaler interface. +func (p *Params) UnmarshalJSON(data []byte) error { + pDisk := paramsDisk{} + err := json.Unmarshal(data, &pDisk) + if err != nil { + return err + } + + *p = Params{ + MaxThroughput: pDisk.MaxThroughput, + SendTimeout: pDisk.SendTimeout, + } + + return nil +}