Skip to content

Instantly share code, notes, and snippets.

@marz619
Last active April 26, 2017 17:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save marz619/47db9131b9e5ff8148ba42d4af563445 to your computer and use it in GitHub Desktop.
Save marz619/47db9131b9e5ff8148ba42d4af563445 to your computer and use it in GitHub Desktop.
simple JSON utility funcs
package json
import (
"bytes"
"encoding/json"
"io"
)
// WriteJSON tries to encode `data` in to the provided io.Writer
//
// i.e. the equivalent of:
//
// b, err := json.Marshal(src)
// if err != nil {
// return err
// }
// _, err = w.Write(b)
// return err
//
func WriteJSON(w io.Writer, src interface{}) error {
return json.NewEncoder(w).Encode(src)
}
// ReadJSON tries to decode JSON into `dst` from the io.Reader.
// This method will call Close() on the provided reader if it
// conforms with a closer interface.
//
// i.e. the equivalent of:
//
// buf := bytes.Buffer{}
// _, err := io.Copy(&buf, r)
// if err != nil {
// return err
// }
// err = json.Unmarshal(buf.Bytes(), dst)
// return err
//
func ReadJSON(r io.Reader, dst interface{}) error {
// defer close
defer _close(r)
// decode
return json.NewDecoder(r).Decode(dst)
}
// ReadJSONBytes reads into dst from a byte slice
func ReadJSONBytes(b []byte, dst interface{}) error {
return ReadJSON(bytes.NewReader(b), dst)
}
// ReadJSONCopy reads into dst and returns a copy of the original reader
func ReadJSONCopy(r io.Reader, dst interface{}) (io.Reader, error) {
cpy := bytes.Buffer{}
return &cpy, ReadJSON(io.TeeReader(r, &cpy), dst)
}
// closer interface implements the Close method.
// We define our own to circumvent type issues across
// package boundaries
type closer interface {
Close() error
}
// close is a helper function used to close some interface
// if it implements the closer interface
func _close(v interface{}) error {
if c, ok := v.(closer); ok {
return c.Close()
}
return nil
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment