http_request.go 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. package http_requests
  2. import (
  3. "bytes"
  4. "context"
  5. "encoding/json"
  6. "io"
  7. "net/http"
  8. "strings"
  9. "time"
  10. )
  11. func buildHttpRequest(method string, url string, options ...HttpOptions) (*http.Request, error) {
  12. req, err := http.NewRequest(method, url, nil)
  13. if err != nil {
  14. return nil, err
  15. }
  16. for _, option := range options {
  17. switch option.Type {
  18. case "write_timeout":
  19. timeout := time.Second * time.Duration(option.Value.(int64))
  20. ctx, cancel := context.WithTimeout(context.Background(), timeout)
  21. time.AfterFunc(timeout, cancel) // release resources associated with context asynchronously
  22. req = req.WithContext(ctx)
  23. case "header":
  24. for k, v := range option.Value.(map[string]string) {
  25. req.Header.Set(k, v)
  26. }
  27. case "params":
  28. q := req.URL.Query()
  29. for k, v := range option.Value.(map[string]string) {
  30. q.Add(k, v)
  31. }
  32. req.URL.RawQuery = q.Encode()
  33. case "payload":
  34. q := req.URL.Query()
  35. for k, v := range option.Value.(map[string]string) {
  36. q.Add(k, v)
  37. }
  38. req.Body = io.NopCloser(strings.NewReader(q.Encode()))
  39. case "payloadText":
  40. req.Body = io.NopCloser(strings.NewReader(option.Value.(string)))
  41. req.Header.Set("Content-Type", "text/plain")
  42. case "payloadJson":
  43. jsonStr, err := json.Marshal(option.Value)
  44. if err != nil {
  45. return nil, err
  46. }
  47. req.Body = io.NopCloser(bytes.NewBuffer(jsonStr))
  48. // set application/json content type
  49. req.Header.Set("Content-Type", "application/json")
  50. case "directReferer":
  51. req.Header.Set("Referer", url)
  52. }
  53. }
  54. return req, nil
  55. }
  56. func Request(client *http.Client, url string, method string, options ...HttpOptions) (*http.Response, error) {
  57. req, err := buildHttpRequest(method, url, options...)
  58. if err != nil {
  59. return nil, err
  60. }
  61. resp, err := client.Do(req)
  62. if err != nil {
  63. return nil, err
  64. }
  65. return resp, nil
  66. }