trpc.group/trpc-go/trpc-go@v1.0.3/http/serialization_form_data.go (about) 1 // 2 // 3 // Tencent is pleased to support the open source community by making tRPC available. 4 // 5 // Copyright (C) 2023 THL A29 Limited, a Tencent company. 6 // All rights reserved. 7 // 8 // If you have downloaded a copy of the tRPC source code from Tencent, 9 // please note that tRPC source code is licensed under the Apache 2.0 License, 10 // A copy of the Apache 2.0 License is included in this file. 11 // 12 // 13 14 package http 15 16 import ( 17 "errors" 18 "net/url" 19 20 "trpc.group/trpc-go/trpc-go/codec" 21 ) 22 23 var ( 24 // tagJSON uses same tag with json. 25 tagJSON = "json" 26 // FormDataMarshalType the serialization method of the response data, 27 // default is json serialization. 28 FormDataMarshalType = codec.SerializationTypeJSON 29 ) 30 31 func init() { 32 codec.RegisterSerializer( 33 codec.SerializationTypeFormData, 34 NewFormDataSerialization(tagJSON), 35 ) 36 } 37 38 // getFormDataContentType returns content type for form data. 39 func getFormDataContentType() string { 40 return serializationTypeContentType[FormDataMarshalType] 41 } 42 43 // NewFormDataSerialization initializes from serialized object. 44 func NewFormDataSerialization(tag string) codec.Serializer { 45 return &FormDataSerialization{ 46 tagName: tag, 47 } 48 } 49 50 // FormDataSerialization packages kv structure of http request. 51 type FormDataSerialization struct { 52 tagName string 53 } 54 55 // Unmarshal unpacks kv structure. 56 func (j *FormDataSerialization) Unmarshal(in []byte, body interface{}) error { 57 values, err := url.ParseQuery(string(in)) 58 if err != nil { 59 return err 60 } 61 return unmarshalValues(j.tagName, values, body) 62 } 63 64 // Marshal serializes. 65 func (j *FormDataSerialization) Marshal(body interface{}) ([]byte, error) { 66 serializer := codec.GetSerializer(FormDataMarshalType) 67 if serializer == nil { 68 return nil, errors.New("empty json serializer") 69 } 70 return serializer.Marshal(body) 71 }