request17.go 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. // +build go1.7 go1.8
  2. // Copyright (c) 2015-2019 Jeevanandam M (jeeva@myjeeva.com)
  3. // 2016 Andrew Grigorev (https://github.com/ei-grad)
  4. // All rights reserved.
  5. // resty source code and usage is governed by a MIT style
  6. // license that can be found in the LICENSE file.
  7. package resty
  8. import (
  9. "bytes"
  10. "context"
  11. "encoding/json"
  12. "net/http"
  13. "net/url"
  14. "time"
  15. )
  16. // Request type is used to compose and send individual request from client
  17. // go-resty is provide option override client level settings such as
  18. // Auth Token, Basic Auth credentials, Header, Query Param, Form Data, Error object
  19. // and also you can add more options for that particular request
  20. type Request struct {
  21. URL string
  22. Method string
  23. Token string
  24. QueryParam url.Values
  25. FormData url.Values
  26. Header http.Header
  27. Time time.Time
  28. Body interface{}
  29. Result interface{}
  30. Error interface{}
  31. RawRequest *http.Request
  32. SRV *SRVRecord
  33. UserInfo *User
  34. isMultiPart bool
  35. isFormData bool
  36. setContentLength bool
  37. isSaveResponse bool
  38. notParseResponse bool
  39. jsonEscapeHTML bool
  40. outputFile string
  41. fallbackContentType string
  42. ctx context.Context
  43. pathParams map[string]string
  44. client *Client
  45. bodyBuf *bytes.Buffer
  46. multipartFiles []*File
  47. multipartFields []*MultipartField
  48. }
  49. // Context method returns the Context if its already set in request
  50. // otherwise it creates new one using `context.Background()`.
  51. func (r *Request) Context() context.Context {
  52. if r.ctx == nil {
  53. return context.Background()
  54. }
  55. return r.ctx
  56. }
  57. // SetContext method sets the context.Context for current Request. It allows
  58. // to interrupt the request execution if ctx.Done() channel is closed.
  59. // See https://blog.golang.org/context article and the "context" package
  60. // documentation.
  61. func (r *Request) SetContext(ctx context.Context) *Request {
  62. r.ctx = ctx
  63. return r
  64. }
  65. func (r *Request) addContextIfAvailable() {
  66. if r.ctx != nil {
  67. r.RawRequest = r.RawRequest.WithContext(r.ctx)
  68. }
  69. }
  70. func (r *Request) isContextCancelledIfAvailable() bool {
  71. if r.ctx != nil {
  72. if r.ctx.Err() != nil {
  73. return true
  74. }
  75. }
  76. return false
  77. }
  78. // for go1.7+
  79. var noescapeJSONMarshal = func(v interface{}) ([]byte, error) {
  80. buf := acquireBuffer()
  81. defer releaseBuffer(buf)
  82. encoder := json.NewEncoder(buf)
  83. encoder.SetEscapeHTML(false)
  84. err := encoder.Encode(v)
  85. return buf.Bytes(), err
  86. }