github.com/go-board/x-go@v0.1.2-0.20220610024734-db1323f6cb15/xnet/xhttp/xrequest/options.go (about) 1 package xrequest 2 3 import ( 4 "io/ioutil" 5 "net/http" 6 "net/url" 7 ) 8 9 // RequestOption modify *http.Request in a convenient way. 10 type RequestOption func(req *http.Request) 11 12 // AddHeader append key/value pair to header. 13 // Deprecated: use WithAddHeader replaced. 14 func AddHeader(key string, value string) RequestOption { 15 return func(req *http.Request) { 16 req.Header.Add(key, value) 17 } 18 } 19 20 // AddHeaderMap append extra header data to existing header. 21 func AddHeaderMap(h http.Header) RequestOption { 22 return func(req *http.Request) { 23 for k, v := range h { 24 for _, vv := range v { 25 req.Header.Add(k, vv) 26 } 27 } 28 } 29 } 30 31 // WithHeader replace or set existing header with key/value pair. 32 // Deprecated: use WithSetHeader replaced. 33 func WithHeader(key string, value string) RequestOption { 34 return func(req *http.Request) { 35 req.Header.Set(key, value) 36 } 37 } 38 39 // WithAddHeader append header value to key. 40 func WithAddHeader(key string, value string) RequestOption { 41 return func(req *http.Request) { 42 req.Header.Add(key, value) 43 } 44 } 45 46 // WithSetHeader upsert header value to key. 47 func WithSetHeader(key string, value string) RequestOption { 48 return func(req *http.Request) { 49 req.Header.Set(key, value) 50 } 51 } 52 53 // WithHeaderMap replace or set existing header. 54 func WithHeaderMap(h http.Header) RequestOption { 55 return func(req *http.Request) { 56 req.Header = h 57 } 58 } 59 60 // WithForm replace or set existing form. 61 func WithForm(f url.Values) RequestOption { 62 return func(req *http.Request) { 63 req.Form = f 64 } 65 } 66 67 // WithContentType set `Content-Type` header. 68 func WithContentType(contentType string) RequestOption { 69 return WithSetHeader("Content-Type", contentType) 70 } 71 72 // AddCookie append cookie to request. 73 func AddCookie(cookie *http.Cookie) RequestOption { 74 return func(req *http.Request) { 75 req.AddCookie(cookie) 76 } 77 } 78 79 func WithRequestBody(body RequestBody) RequestOption { 80 return func(req *http.Request) { 81 req.Body = ioutil.NopCloser(body) 82 } 83 } 84 85 // WithAddQuery add query param to url. 86 func WithAddQuery(key, value string) RequestOption { 87 return func(req *http.Request) { 88 q := req.URL.Query() 89 q.Add(key, value) 90 req.URL.RawQuery = q.Encode() 91 } 92 } 93 94 // WithSetQuery set query param to url. 95 func WithSetQuery(key, value string) RequestOption { 96 return func(req *http.Request) { 97 q := req.URL.Query() 98 q.Set(key, value) 99 req.URL.RawQuery = q.Encode() 100 } 101 }