Skip to content

Commit

Permalink
fix json float parsing
Browse files Browse the repository at this point in the history
  • Loading branch information
ibuildthecloud committed Jan 20, 2018
1 parent aa2538a commit c970c36
Show file tree
Hide file tree
Showing 3 changed files with 46 additions and 9 deletions.
10 changes: 3 additions & 7 deletions parse/read_input.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ import (
"encoding/json"
"fmt"
"io"
"io/ioutil"
"net/http"

"github.com/rancher/norman/httperror"
Expand All @@ -22,14 +21,11 @@ func ReadBody(req *http.Request) (map[string]interface{}, error) {
return nil, nil
}

content, err := ioutil.ReadAll(io.LimitReader(req.Body, reqMaxSize))
if err != nil {
return nil, httperror.NewAPIError(httperror.InvalidBodyContent,
fmt.Sprintf("Body content longer than %d bytes", reqMaxSize-1))
}
dec := json.NewDecoder(io.LimitReader(req.Body, reqMaxSize))
dec.UseNumber()

data := map[string]interface{}{}
if err := json.Unmarshal(content, &data); err != nil {
if err := dec.Decode(&data); err != nil {
return nil, httperror.NewAPIError(httperror.InvalidBodyContent,
fmt.Sprintf("Failed to parse body: %v", err))
}
Expand Down
19 changes: 17 additions & 2 deletions types/convert/convert.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package convert

import (
"bytes"
"encoding/json"
"errors"
"fmt"
Expand Down Expand Up @@ -85,6 +86,18 @@ func ToNumber(value interface{}) (int64, error) {
if ok {
return i, nil
}
f, ok := value.(float64)
if ok {
return int64(f), nil
}
if n, ok := value.(json.Number); ok {
i, err := n.Int64()
if err == nil {
return i, nil
}
f, err := n.Float64()
return int64(f), err
}
return strconv.ParseInt(ToString(value), 10, 64)
}

Expand Down Expand Up @@ -185,10 +198,12 @@ func ToObj(data interface{}, into interface{}) error {
}

func EncodeToMap(obj interface{}) (map[string]interface{}, error) {
bytes, err := json.Marshal(obj)
b, err := json.Marshal(obj)
if err != nil {
return nil, err
}
result := map[string]interface{}{}
return result, json.Unmarshal(bytes, &result)
dec := json.NewDecoder(bytes.NewBuffer(b))
dec.UseNumber()
return result, dec.Decode(&result)
}
26 changes: 26 additions & 0 deletions types/convert/convert_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
package convert

import (
"testing"
)

type data struct {
TTLMillis int `json:"ttl"`
}

func TestJSON(t *testing.T) {
d := &data{
TTLMillis: 57600000,
}

m, err := EncodeToMap(d)
if err != nil {
t.Fatal(err)
}

i, _ := ToNumber(m["ttl"])
if i != 57600000 {
t.Fatal("not", 57600000, "got", m["ttl"])
}

}

0 comments on commit c970c36

Please sign in to comment.