| 1 | # go-httpheader |
| 2 | |
| 3 | go-httpheader is a Go library for encoding structs into Header fields. |
| 4 | |
| 5 | [](https://github.com/mozillazg/go-httpheader/actions) |
| 6 | [](https://coveralls.io/github/mozillazg/go-httpheader?branch=master) |
| 7 | [](https://goreportcard.com/report/github.com/mozillazg/go-httpheader) |
| 8 | [](https://godoc.org/github.com/mozillazg/go-httpheader) |
| 9 | |
| 10 | ## install |
| 11 | |
| 12 | `go get -u github.com/mozillazg/go-httpheader` |
| 13 | |
| 14 | |
| 15 | ## usage |
| 16 | |
| 17 | ```go |
| 18 | package main |
| 19 | |
| 20 | import ( |
| 21 | "fmt" |
| 22 | "net/http" |
| 23 | |
| 24 | "github.com/mozillazg/go-httpheader" |
| 25 | ) |
| 26 | |
| 27 | type Options struct { |
| 28 | hide string |
| 29 | ContentType string `header:"Content-Type"` |
| 30 | Length int |
| 31 | XArray []string `header:"X-Array"` |
| 32 | TestHide string `header:"-"` |
| 33 | IgnoreEmpty string `header:"X-Empty,omitempty"` |
| 34 | IgnoreEmptyN string `header:"X-Empty-N,omitempty"` |
| 35 | CustomHeader http.Header |
| 36 | } |
| 37 | |
| 38 | func main() { |
| 39 | opt := Options{ |
| 40 | hide: "hide", |
| 41 | ContentType: "application/json", |
| 42 | Length: 2, |
| 43 | XArray: []string{"test1", "test2"}, |
| 44 | TestHide: "hide", |
| 45 | IgnoreEmptyN: "n", |
| 46 | CustomHeader: http.Header{ |
| 47 | "X-Test-1": []string{"233"}, |
| 48 | "X-Test-2": []string{"666"}, |
| 49 | }, |
| 50 | } |
| 51 | h, _ := httpheader.Header(opt) |
| 52 | fmt.Printf("%#v", h) |
| 53 | // h: |
| 54 | // http.Header{ |
| 55 | // "X-Test-1": []string{"233"}, |
| 56 | // "X-Test-2": []string{"666"}, |
| 57 | // "Content-Type": []string{"application/json"}, |
| 58 | // "Length": []string{"2"}, |
| 59 | // "X-Array": []string{"test1", "test2"}, |
| 60 | // "X-Empty-N": []string{"n"}, |
| 61 | // } |
| 62 | |
| 63 | // decode |
| 64 | var decode Options |
| 65 | httpheader.Decode(h, &decode) |
| 66 | } |
| 67 | ``` |