github.com/jfrazelle/docker@v1.1.2-0.20210712172922-bf78e25fe508/testutil/request/ops.go (about) 1 package request 2 3 import ( 4 "bytes" 5 "encoding/json" 6 "io" 7 "io/ioutil" 8 "net/http" 9 "strings" 10 ) 11 12 // Options defines request options, like request modifiers and which host to target 13 type Options struct { 14 host string 15 requestModifiers []func(*http.Request) error 16 } 17 18 // Host creates a modifier that sets the specified host as the request URL host 19 func Host(host string) func(*Options) { 20 return func(o *Options) { 21 o.host = host 22 } 23 } 24 25 // With adds a request modifier to the options 26 func With(f func(*http.Request) error) func(*Options) { 27 return func(o *Options) { 28 o.requestModifiers = append(o.requestModifiers, f) 29 } 30 } 31 32 // Method creates a modifier that sets the specified string as the request method 33 func Method(method string) func(*Options) { 34 return With(func(req *http.Request) error { 35 req.Method = method 36 return nil 37 }) 38 } 39 40 // RawString sets the specified string as body for the request 41 func RawString(content string) func(*Options) { 42 return RawContent(ioutil.NopCloser(strings.NewReader(content))) 43 } 44 45 // RawContent sets the specified reader as body for the request 46 func RawContent(reader io.ReadCloser) func(*Options) { 47 return With(func(req *http.Request) error { 48 req.Body = reader 49 return nil 50 }) 51 } 52 53 // ContentType sets the specified Content-Type request header 54 func ContentType(contentType string) func(*Options) { 55 return With(func(req *http.Request) error { 56 req.Header.Set("Content-Type", contentType) 57 return nil 58 }) 59 } 60 61 // JSON sets the Content-Type request header to json 62 func JSON(o *Options) { 63 ContentType("application/json")(o) 64 } 65 66 // JSONBody creates a modifier that encodes the specified data to a JSON string and set it as request body. It also sets 67 // the Content-Type header of the request. 68 func JSONBody(data interface{}) func(*Options) { 69 return With(func(req *http.Request) error { 70 jsonData := bytes.NewBuffer(nil) 71 if err := json.NewEncoder(jsonData).Encode(data); err != nil { 72 return err 73 } 74 req.Body = ioutil.NopCloser(jsonData) 75 req.Header.Set("Content-Type", "application/json") 76 return nil 77 }) 78 }