github.com/profzone/eden-framework@v1.0.10/pkg/courier/transport_http/transform/content_transformer.go (about) 1 package transform 2 3 import ( 4 "bytes" 5 "encoding/json" 6 "encoding/xml" 7 "reflect" 8 9 "github.com/profzone/eden-framework/pkg/courier/httpx" 10 ) 11 12 func init() { 13 RegisterContentTransformer(&ContentTransformer{ 14 Key: "json", 15 ContentType: httpx.MIME_JSON, 16 Marshal: json.Marshal, 17 Unmarshal: func(data []byte, v interface{}) error { 18 d := json.NewDecoder(bytes.NewBuffer(data)) 19 20 err := d.Decode(v) 21 if err != nil { 22 switch err.(type) { 23 case *json.UnmarshalTypeError: 24 return err 25 case *json.SyntaxError: 26 return err 27 default: 28 offset := reflect.ValueOf(d).Elem().Field(2 /*d*/).Field(1 /*off*/).Int() 29 return &json.UnmarshalTypeError{ 30 Offset: int64(offset), 31 Value: err.Error(), 32 } 33 } 34 return err 35 } 36 return nil 37 }, 38 }) 39 RegisterContentTransformer(&ContentTransformer{ 40 Key: "xml", 41 ContentType: httpx.MIME_XML, 42 Marshal: xml.Marshal, 43 Unmarshal: xml.Unmarshal, 44 }) 45 } 46 47 var contentTransformers = map[string]*ContentTransformer{} 48 49 func RegisterContentTransformer(contentTransformer *ContentTransformer) { 50 contentTransformers[contentTransformer.Key] = contentTransformer 51 contentTransformers[contentTransformer.ContentType] = contentTransformer 52 } 53 54 func GetContentTransformer(keyOrContentType string) *ContentTransformer { 55 return contentTransformers[keyOrContentType] 56 } 57 58 type ContentTransformer struct { 59 Key string 60 ContentType string 61 Marshal func(v interface{}) ([]byte, error) 62 Unmarshal func(data []byte, v interface{}) error 63 }