diff options
| author | Shulhan <ms@kilabit.info> | 2021-04-23 11:51:31 +0700 |
|---|---|---|
| committer | Shulhan <ms@kilabit.info> | 2021-04-23 11:51:31 +0700 |
| commit | aff8a206c06e39a010ab90d88f41ae78d7a127f3 (patch) | |
| tree | 1fb0634cb3cbb99643b6303042d4e67fe8333657 | |
| parent | a9f936aea6b2512e0af62ccacc50d89c194233d0 (diff) | |
| download | pakakeh.go-aff8a206c06e39a010ab90d88f41ae78d7a127f3.tar.xz | |
math/big: extend Int to support marshal/unmarshal JSON
| -rw-r--r-- | lib/math/big/int.go | 34 |
1 files changed, 34 insertions, 0 deletions
diff --git a/lib/math/big/int.go b/lib/math/big/int.go index f3f2b45f..66d5588b 100644 --- a/lib/math/big/int.go +++ b/lib/math/big/int.go @@ -7,6 +7,7 @@ package big import ( "bytes" "database/sql/driver" + "fmt" "math/big" "strings" ) @@ -33,6 +34,39 @@ func NewInt(v interface{}) (i *Int) { } // +// MarshalJSON implement the json.Marshaler interface and return the output of +// String method. +// +// If the global variable MarshalJSONAsString is true, the Int value will +// be encoded as string. +// +func (r *Int) MarshalJSON() ([]byte, error) { + var s string + if r == nil { + s = "0" + } else { + s = r.String() + } + if MarshalJSONAsString { + s = `"` + s + `"` + } + return []byte(s), nil +} + +// +// UnmarshalJSON convert the JSON byte value into Int. +// +func (r *Int) UnmarshalJSON(in []byte) (err error) { + in = bytes.Trim(in, `"`) + r.SetInt64(0) + _, ok := r.Int.SetString(string(in), 10) + if !ok { + return fmt.Errorf("Int.UnmarshalJSON: cannot convert %T(%v) to Int", in, in) + } + return nil +} + +// // Value implement the sql/driver.Valuer. // func (i *Int) Value() (driver.Value, error) { |
