Closed
Description
Seeing a crash with custom map encoders with jsoniter. The same works fine with std json.
Attaching the code.
package main
import (
"encoding/json"
"fmt"
"unsafe"
jsoniter "github.com/json-iterator/go"
)
func jsoniterMarshal(input Status) {
bb, err := jsoniter.Marshal(&input)
if err != nil {
fmt.Printf("JSONITER Error %v \n", err)
return
}
fmt.Printf("JSONITER Res %s \n", bb)
}
func jsonMarshal(input Status) {
bb, err := json.Marshal(&input)
if err != nil {
fmt.Printf("JSON Error %v \n", err)
return
}
fmt.Printf("JSON Res %s \n", bb)
}
type ErrMap map[string]error
type Status struct {
Total int `json:"total"`
ErrMaps ErrMap `json:"errMaps,omitempty"`
}
func (iem ErrMap) MarshalJSON() ([]byte, error) {
tmp := make(map[string]string, len(iem))
for k, v := range iem {
tmp[k] = v.Error()
}
return json.Marshal(tmp)
}
func encodeMap(ptr unsafe.Pointer, stream *jsoniter.Stream) {
iem := *((*ErrMap)(ptr))
//log.Printf("\nval-> %+v", iem)
if iem != nil {
tmp := make(map[string]string, len(iem))
for k, v := range iem {
tmp[k] = v.Error()
}
stream.WriteVal(tmp)
}
}
func main() {
jsoniter.RegisterTypeEncoderFunc("main.ErrMap", encodeMap, nil)
eMap := make(ErrMap, 2)
eMap["first"] = fmt.Errorf("First Error")
eMap["second"] = fmt.Errorf("Second Error")
s := Status{Total: 100,
ErrMaps: eMap}
jsonMarshal(s)
jsoniterMarshal(s)
}
Metadata
Metadata
Assignees
Labels
No labels