infra
/
goutils
Archived
1
0
Fork 0
This repository has been archived on 2022-04-06. You can view files and clone it, but cannot push or open issues or pull requests.
goutils/net/json/json.go

59 lines
1.4 KiB
Go

package json
import (
"net/http"
json "github.com/json-iterator/go"
"bytes"
"io"
"errors"
)
var (
jsonContentType = []string{"application/json; charset=utf-8"}
JSONConfig = json.ConfigFastest
errorJsonEncoderEmpty = errors.New("empty json encoder")
)
func DumpJSON(w http.ResponseWriter, code int, serializable interface{}) {
// Encode
header := w.Header()
if val := header["Content-Type"]; len(val) == 0 {
header["Content-Type"] = jsonContentType
}
w.WriteHeader(code)
stream := JSONConfig.BorrowStream(w)
if stream == nil {
panic(errorJsonEncoderEmpty)
}
defer JSONConfig.ReturnStream(stream)
stream.WriteVal(serializable)
stream.Flush()
if stream.Error != nil {
panic(stream.Error)
}
}
func DumpJSONData(serializable interface{}) ([]byte, error) {
buf := bytes.Buffer{}
stream := JSONConfig.BorrowStream(&buf)
if stream == nil {
panic(errors.New("empty json encoder"))
}
defer JSONConfig.ReturnStream(stream)
stream.WriteVal(serializable)
stream.Flush()
return buf.Bytes(), stream.Error
}
func LoadJSON(data []byte, deserializable interface{}) (err error) {
iterator := JSONConfig.BorrowIterator(data)
if iterator == nil {
err = errors.New("empty json data")
return
}
defer JSONConfig.ReturnIterator(iterator)
iterator.ReadVal(deserializable)
return iterator.Error
}
func LoadJSONReader(r io.Reader, deserializable interface{}) (err error) {
decoder := JSONConfig.NewDecoder(r)
return decoder.Decode(deserializable)
}