Debian Codegraph @

encode.go

raw symbols SCIP
1 // Package httpheader implements encoding of structs into http.Header fields.
2 //
3 // As a simple example:
4 //
5 // type Options struct {
6 // ContentType string `header:"Content-Type"`
7 // Length int
8 // }
9 //
10 // opt := Options{"application/json", 2}
11 // h, _ := httpheader.Header(opt)
12 // fmt.Printf("%#v", h)
13 // // will output:
14 // // http.Header{"Content-Type":[]string{"application/json"},"Length":[]string{"2"}}
15 //
16 // The exact mapping between Go values and http.Header is described in the
17 // documentation for the Header() function.
18 package httpheader
19
20 import (
21 "fmt"
22 "net/http"
23 "reflect"
24 "strconv"
25 "strings"
26 "time"
27 )
28
29 const tagName = "header"
30
31 // Version ...
32 const Version = "0.3.1"
33
34 var timeType = reflect.TypeOf(time.Time{})
35 var headerType = reflect.TypeOf(http.Header{})
36
37 var encoderType = reflect.TypeOf(new(Encoder)).Elem()
38
39 // Encoder is an interface implemented by any type that wishes to encode
40 // itself into Header fields in a non-standard way.
41 type Encoder interface {
42 EncodeHeader(key string, v *http.Header) error
43 }
44
45 // Header returns the http.Header encoding of v.
46 //
47 // Header expects to be passed a struct, and traverses it recursively using the
48 // following encoding rules.
49 //
50 // Each exported struct field is encoded as a Header field unless
51 //
52 // - the field's tag is "-", or
53 // - the field is empty and its tag specifies the "omitempty" option
54 //
55 // The empty values are false, 0, any nil pointer or interface value, any array
56 // slice, map, or string of length zero, and any time.Time that returns true
57 // for IsZero().
58 //
59 // The Header field name defaults to the struct field name but can be
60 // specified in the struct field's tag value. The "header" key in the struct
61 // field's tag value is the key name, followed by an optional comma and
62 // options. For example:
63 //
64 // // Field is ignored by this package.
65 // Field int `header:"-"`
66 //
67 // // Field appears as Header field "X-Name".
68 // Field int `header:"X-Name"`
69 //
70 // // Field appears as Header field "X-Name" and the field is omitted if
71 // // its value is empty
72 // Field int `header:"X-Name,omitempty"`
73 //
74 // // Field appears as Header field "Field" (the default), but the field
75 // // is skipped if empty. Note the leading comma.
76 // Field int `header:",omitempty"`
77 //
78 // For encoding individual field values, the following type-dependent rules
79 // apply:
80 //
81 // Boolean values default to encoding as the strings "true" or "false".
82 // Including the "int" option signals that the field should be encoded as the
83 // strings "1" or "0".
84 //
85 // time.Time values default to encoding as RFC1123("Mon, 02 Jan 2006 15:04:05 GMT")
86 // timestamps. Including the "unix" option signals that the field should be
87 // encoded as a Unix time (see time.Unix())
88 //
89 // Slice and Array values default to encoding as multiple Header values of the
90 // same name. example:
91 // X-Name: []string{"Tom", "Jim"}, etc.
92 //
93 // http.Header values will be used to extend the Header fields.
94 //
95 // Anonymous struct fields are usually encoded as if their inner exported
96 // fields were fields in the outer struct, subject to the standard Go
97 // visibility rules. An anonymous struct field with a name given in its Header
98 // tag is treated as having that name, rather than being anonymous.
99 //
100 // Non-nil pointer values are encoded as the value pointed to.
101 //
102 // All other values are encoded using their default string representation.
103 //
104 // Multiple fields that encode to the same Header filed name will be included
105 // as multiple Header values of the same name.
106 func Header(v interface{}) (http.Header, error) {
107 h := make(http.Header)
108 val := reflect.ValueOf(v)
109 for val.Kind() == reflect.Ptr {
110 if val.IsNil() {
111 return h, nil
112 }
113 val = val.Elem()
114 }
115
116 if v == nil {
117 return h, nil
118 }
119
120 if val.Kind() != reflect.Struct {
121 return nil, fmt.Errorf("httpheader: Header() expects struct input. Got %v", val.Kind())
122 }
123
124 err := reflectValue(h, val)
125 return h, err
126 }
127
128 // reflectValue populates the header fields from the struct fields in val.
129 // Embedded structs are followed recursively (using the rules defined in the
130 // Values function documentation) breadth-first.
131 func reflectValue(header http.Header, val reflect.Value) error {
132 var embedded []reflect.Value
133
134 typ := val.Type()
135 for i := 0; i < typ.NumField(); i++ {
136 sf := typ.Field(i)
137 if sf.PkgPath != "" && !sf.Anonymous { // unexported
138 continue
139 }
140
141 sv := val.Field(i)
142 tag := sf.Tag.Get(tagName)
143 if tag == "-" {
144 continue
145 }
146 name, opts := parseTag(tag)
147 if name == "" {
148 if sf.Anonymous && sv.Kind() == reflect.Struct {
149 // save embedded struct for later processing
150 embedded = append(embedded, sv)
151 continue
152 }
153
154 name = sf.Name
155 }
156
157 if opts.Contains("omitempty") && isEmptyValue(sv) {
158 continue
159 }
160
161 if sv.Type().Implements(encoderType) {
162 if !reflect.Indirect(sv).IsValid() {
163 sv = reflect.New(sv.Type().Elem())
164 }
165
166 m := sv.Interface().(Encoder)
167 if err := m.EncodeHeader(name, &header); err != nil {
168 return err
169 }
170 continue
171 }
172
173 if sv.Kind() == reflect.Slice || sv.Kind() == reflect.Array {
174 for i := 0; i < sv.Len(); i++ {
175 k := name
176 header.Add(k, valueString(sv.Index(i), opts))
177 }
178 continue
179 }
180
181 for sv.Kind() == reflect.Ptr {
182 if sv.IsNil() {
183 break
184 }
185 sv = sv.Elem()
186 }
187
188 if sv.Type() == timeType {
189 header.Add(name, valueString(sv, opts))
190 continue
191 }
192 if sv.Type() == headerType {
193 h := sv.Interface().(http.Header)
194 for k, vs := range h {
195 for _, v := range vs {
196 header.Add(k, v)
197 }
198 }
199 continue
200 }
201
202 if sv.Kind() == reflect.Struct {
203 if err := reflectValue(header, sv); err != nil {
204 return err
205 }
206 continue
207 }
208
209 header.Add(name, valueString(sv, opts))
210 }
211
212 for _, f := range embedded {
213 if err := reflectValue(header, f); err != nil {
214 return err
215 }
216 }
217
218 return nil
219 }
220
221 // valueString returns the string representation of a value.
222 func valueString(v reflect.Value, opts tagOptions) string {
223 for v.Kind() == reflect.Ptr {
224 if v.IsNil() {
225 return ""
226 }
227 v = v.Elem()
228 }
229
230 if v.Kind() == reflect.Bool && opts.Contains("int") {
231 if v.Bool() {
232 return "1"
233 }
234 return "0"
235 }
236
237 if v.Type() == timeType {
238 t := v.Interface().(time.Time)
239 if opts.Contains("unix") {
240 return strconv.FormatInt(t.Unix(), 10)
241 }
242 return t.Format(http.TimeFormat)
243 }
244
245 return fmt.Sprint(v.Interface())
246 }
247
248 // isEmptyValue checks if a value should be considered empty for the purposes
249 // of omitting fields with the "omitempty" option.
250 func isEmptyValue(v reflect.Value) bool {
251 switch v.Kind() {
252 case reflect.Array, reflect.Map, reflect.Slice, reflect.String:
253 return v.Len() == 0
254 case reflect.Bool:
255 return !v.Bool()
256 case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
257 return v.Int() == 0
258 case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
259 return v.Uint() == 0
260 case reflect.Float32, reflect.Float64:
261 return v.Float() == 0
262 case reflect.Interface, reflect.Ptr:
263 return v.IsNil()
264 }
265
266 if v.Type() == timeType {
267 return v.Interface().(time.Time).IsZero()
268 }
269
270 return false
271 }
272
273 // tagOptions is the string following a comma in a struct field's "header" tag, or
274 // the empty string. It does not include the leading comma.
275 type tagOptions []string
276
277 // parseTag splits a struct field's header tag into its name and comma-separated
278 // options.
279 func parseTag(tag string) (string, tagOptions) {
280 s := strings.Split(tag, ",")
281 return s[0], s[1:]
282 }
283
284 // Contains checks whether the tagOptions contains the specified option.
285 func (o tagOptions) Contains(option string) bool {
286 for _, s := range o {
287 if s == option {
288 return true
289 }
290 }
291 return false
292 }
293
294 // Encode is an alias of Header function
295 func Encode(v interface{}) (http.Header, error) {
296 return Header(v)
297 }