github.com/johnnyeven/libtools@v0.0.0-20191126065708-61829c1adf46/courier/transport_http/transform/content_transformer.go (about)

     1  package transform
     2  
     3  import (
     4  	"encoding/json"
     5  	"encoding/xml"
     6  
     7  	"github.com/johnnyeven/libtools/courier/httpx"
     8  )
     9  
    10  func init() {
    11  	RegisterContentTransformer(&ContentTransformer{
    12  		Key:         "json",
    13  		ContentType: httpx.MIMEJSON,
    14  		Marshal:     json.Marshal,
    15  		Unmarshal:   json.Unmarshal,
    16  	})
    17  	RegisterContentTransformer(&ContentTransformer{
    18  		Key:         "xml",
    19  		ContentType: httpx.MIMEXML,
    20  		Marshal:     xml.Marshal,
    21  		Unmarshal:   xml.Unmarshal,
    22  	})
    23  }
    24  
    25  var contentTransformers = map[string]*ContentTransformer{}
    26  
    27  func RegisterContentTransformer(contentTransformer *ContentTransformer) {
    28  	contentTransformers[contentTransformer.Key] = contentTransformer
    29  	contentTransformers[contentTransformer.ContentType] = contentTransformer
    30  }
    31  
    32  func GetContentTransformer(keyOrContentType string) *ContentTransformer {
    33  	return contentTransformers[keyOrContentType]
    34  }
    35  
    36  type ContentTransformer struct {
    37  	Key         string
    38  	ContentType string
    39  	Marshal     func(v interface{}) ([]byte, error)
    40  	Unmarshal   func(data []byte, v interface{}) error
    41  }