Skip to content

Commit

Permalink
Input validations for jsonutil
Browse files Browse the repository at this point in the history
  • Loading branch information
vishalnayak committed Jul 7, 2016
1 parent 80b8e1f commit 2dc811d
Showing 1 changed file with 22 additions and 5 deletions.
27 changes: 22 additions & 5 deletions helper/jsonutil/json.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import (
"reflect"
)

// Encodes/Marshals the given object into JSON
func EncodeJSON(in interface{}) ([]byte, error) {
var buf bytes.Buffer
enc := json.NewEncoder(&buf)
Expand All @@ -17,20 +18,36 @@ func EncodeJSON(in interface{}) ([]byte, error) {
return buf.Bytes(), nil
}

// Decodes/Unmarshals the given JSON into a desired object
func DecodeJSON(data []byte, out interface{}) error {
// Decoding requires a pointer type to be supplied
value := reflect.ValueOf(out)
if value.Kind() != reflect.Ptr {
return fmt.Errorf("decoding the value into an invalid type: %v", reflect.TypeOf(out))
if data == nil {
return fmt.Errorf("'data' being decoded is nil")
}
if out == nil {
return fmt.Errorf("output parameter 'out' is nil")
}

return DecodeJSONFromReader(bytes.NewReader(data), out)
}

// Decodes/Unmarshals the given io.Reader pointing to a JSON, into a desired object
func DecodeJSONFromReader(r io.Reader, out interface{}) error {
if r == nil {
return fmt.Errorf("'io.Reader' being decoded is nil")
}
if out == nil {
return fmt.Errorf("output parameter 'out' is nil")
}

// Decoding requires a pointer type to be supplied
value := reflect.ValueOf(out)
if value.Kind() != reflect.Ptr {
return fmt.Errorf("decoding the value into a non-pointer type: %v", reflect.TypeOf(out))
}

dec := json.NewDecoder(r)

// While decoding JSON values, intepret the integer values as numbers instead of floats.
// While decoding JSON values, intepret the integer values as `json.Number`s instead of `float64`.
dec.UseNumber()

// Since 'out' is an interface representing a pointer, pass it to the decoder without an '&'
Expand Down

0 comments on commit 2dc811d

Please sign in to comment.