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