ops.go 2.0 KB

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