amuz.es/src/infra/goutils@v0.1.3/net/json/json.go (about) 1 package json 2 3 import ( 4 "net/http" 5 json "github.com/json-iterator/go" 6 "bytes" 7 "io" 8 "errors" 9 ) 10 11 var ( 12 jsonContentType = []string{"application/json; charset=utf-8"} 13 JSONConfig = json.ConfigFastest 14 errorJsonEncoderEmpty = errors.New("empty json encoder") 15 ) 16 func DumpJSON(w http.ResponseWriter, code int, serializable interface{}) { 17 // Encode 18 header := w.Header() 19 if val := header["Content-Type"]; len(val) == 0 { 20 header["Content-Type"] = jsonContentType 21 } 22 w.WriteHeader(code) 23 stream := JSONConfig.BorrowStream(w) 24 if stream == nil { 25 panic(errorJsonEncoderEmpty) 26 } 27 defer JSONConfig.ReturnStream(stream) 28 stream.WriteVal(serializable) 29 stream.Flush() 30 if stream.Error != nil { 31 panic(stream.Error) 32 } 33 } 34 func DumpJSONData(serializable interface{}) ([]byte, error) { 35 buf := bytes.Buffer{} 36 stream := JSONConfig.BorrowStream(&buf) 37 if stream == nil { 38 panic(errors.New("empty json encoder")) 39 } 40 defer JSONConfig.ReturnStream(stream) 41 stream.WriteVal(serializable) 42 stream.Flush() 43 return buf.Bytes(), stream.Error 44 } 45 func LoadJSON(data []byte, deserializable interface{}) (err error) { 46 iterator := JSONConfig.BorrowIterator(data) 47 if iterator == nil { 48 err = errors.New("empty json data") 49 return 50 } 51 defer JSONConfig.ReturnIterator(iterator) 52 iterator.ReadVal(deserializable) 53 return iterator.Error 54 } 55 func LoadJSONReader(r io.Reader, deserializable interface{}) (err error) { 56 decoder := JSONConfig.NewDecoder(r) 57 return decoder.Decode(deserializable) 58 }