-
Notifications
You must be signed in to change notification settings - Fork 20
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
FIx precision loss with numeric send
Showing
2 changed files
with
15 additions
and
26 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,46 +1,35 @@ | ||
package requests | ||
|
||
import ( | ||
"bytes" | ||
"encoding/json" | ||
"fmt" | ||
) | ||
|
||
type SendRequest struct { | ||
BaseRequest `mapstructure:",squash"` | ||
Source string `json:"source" mapstructure:"source"` | ||
Destination string `json:"destination" mapstructure:"destination"` | ||
Amount string `json:"-" mapstructure:"amount"` // Exclude from automatic unmarshalling | ||
RawAmount json.RawMessage `json:"amount" mapstructure:"-"` | ||
ID *string `json:"id,omitempty" mapstructure:"id,omitempty"` | ||
Work *string `json:"work,omitempty" mapstructure:"work,omitempty"` | ||
Source string `json:"source" mapstructure:"source"` | ||
Destination string `json:"destination" mapstructure:"destination"` | ||
Amount string `json:"amount" mapstructure:"amount"` | ||
ID *string `json:"id,omitempty" mapstructure:"id,omitempty"` | ||
Work *string `json:"work,omitempty" mapstructure:"work,omitempty"` | ||
} | ||
|
||
func (r *SendRequest) UnmarshalJSON(data []byte) error { | ||
type Alias SendRequest | ||
aux := &struct { | ||
aux := struct { | ||
*Alias | ||
Amount json.Number `json:"amount"` | ||
}{ | ||
Alias: (*Alias)(r), | ||
} | ||
if err := json.Unmarshal(data, &aux); err != nil { | ||
return err | ||
} | ||
|
||
var temp interface{} | ||
if err := json.Unmarshal(r.RawAmount, &temp); err != nil { | ||
return err | ||
} | ||
decoder := json.NewDecoder(bytes.NewReader(data)) | ||
decoder.UseNumber() | ||
|
||
switch v := temp.(type) { | ||
case float64: | ||
r.Amount = fmt.Sprintf("%.0f", v) // Safely convert to string without scientific notation | ||
case int: | ||
r.Amount = fmt.Sprintf("%d", v) | ||
case string: | ||
r.Amount = v | ||
default: | ||
return fmt.Errorf("amount is of a type I don't know how to handle") | ||
if err := decoder.Decode(&aux); err != nil { | ||
return err | ||
} | ||
|
||
r.Amount = aux.Amount.String() | ||
return nil | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters