matchers.go 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232
  1. package gock
  2. import (
  3. "compress/gzip"
  4. "encoding/json"
  5. "io"
  6. "io/ioutil"
  7. "net/http"
  8. "reflect"
  9. "regexp"
  10. "strings"
  11. )
  12. // EOL represents the end of line character.
  13. const EOL = 0xa
  14. // BodyTypes stores the supported MIME body types for matching.
  15. // Currently only text-based types.
  16. var BodyTypes = []string{
  17. "text/html",
  18. "text/plain",
  19. "application/json",
  20. "application/xml",
  21. "multipart/form-data",
  22. "application/x-www-form-urlencoded",
  23. }
  24. // BodyTypeAliases stores a generic MIME type by alias.
  25. var BodyTypeAliases = map[string]string{
  26. "html": "text/html",
  27. "text": "text/plain",
  28. "json": "application/json",
  29. "xml": "application/xml",
  30. "form": "multipart/form-data",
  31. "url": "application/x-www-form-urlencoded",
  32. }
  33. // CompressionSchemes stores the supported Content-Encoding types for decompression.
  34. var CompressionSchemes = []string{
  35. "gzip",
  36. }
  37. // MatchMethod matches the HTTP method of the given request.
  38. func MatchMethod(req *http.Request, ereq *Request) (bool, error) {
  39. return ereq.Method == "" || req.Method == ereq.Method, nil
  40. }
  41. // MatchScheme matches the request URL protocol scheme.
  42. func MatchScheme(req *http.Request, ereq *Request) (bool, error) {
  43. return ereq.URLStruct.Scheme == "" || req.URL.Scheme == "" || ereq.URLStruct.Scheme == req.URL.Scheme, nil
  44. }
  45. // MatchHost matches the HTTP host header field of the given request.
  46. func MatchHost(req *http.Request, ereq *Request) (bool, error) {
  47. url := ereq.URLStruct
  48. if strings.EqualFold(url.Host, req.URL.Host) {
  49. return true, nil
  50. }
  51. return regexp.MatchString(url.Host, req.URL.Host)
  52. }
  53. // MatchPath matches the HTTP URL path of the given request.
  54. func MatchPath(req *http.Request, ereq *Request) (bool, error) {
  55. return regexp.MatchString(ereq.URLStruct.Path, req.URL.Path)
  56. }
  57. // MatchHeaders matches the headers fields of the given request.
  58. func MatchHeaders(req *http.Request, ereq *Request) (bool, error) {
  59. for key, value := range ereq.Header {
  60. var err error
  61. var match bool
  62. for _, field := range req.Header[key] {
  63. match, err = regexp.MatchString(value[0], field)
  64. if err != nil {
  65. return false, err
  66. }
  67. if match {
  68. break
  69. }
  70. }
  71. if !match {
  72. return false, nil
  73. }
  74. }
  75. return true, nil
  76. }
  77. // MatchQueryParams matches the URL query params fields of the given request.
  78. func MatchQueryParams(req *http.Request, ereq *Request) (bool, error) {
  79. for key, value := range ereq.URLStruct.Query() {
  80. var err error
  81. var match bool
  82. for _, field := range req.URL.Query()[key] {
  83. match, err = regexp.MatchString(value[0], field)
  84. if err != nil {
  85. return false, err
  86. }
  87. if match {
  88. break
  89. }
  90. }
  91. if !match {
  92. return false, nil
  93. }
  94. }
  95. return true, nil
  96. }
  97. // MatchBody tries to match the request body.
  98. // TODO: not too smart now, needs several improvements.
  99. func MatchBody(req *http.Request, ereq *Request) (bool, error) {
  100. // If match body is empty, just continue
  101. if req.Method == "HEAD" || len(ereq.BodyBuffer) == 0 {
  102. return true, nil
  103. }
  104. // Only can match certain MIME body types
  105. if !supportedType(req) {
  106. return false, nil
  107. }
  108. // Can only match certain compression schemes
  109. if !supportedCompressionScheme(req) {
  110. return false, nil
  111. }
  112. // Create a reader for the body depending on compression type
  113. bodyReader := req.Body
  114. if ereq.CompressionScheme != "" {
  115. if ereq.CompressionScheme != req.Header.Get("Content-Encoding") {
  116. return false, nil
  117. }
  118. compressedBodyReader, err := compressionReader(req.Body, ereq.CompressionScheme)
  119. if err != nil {
  120. return false, err
  121. }
  122. bodyReader = compressedBodyReader
  123. }
  124. // Read the whole request body
  125. body, err := ioutil.ReadAll(bodyReader)
  126. if err != nil {
  127. return false, err
  128. }
  129. // Restore body reader stream
  130. req.Body = createReadCloser(body)
  131. // If empty, ignore the match
  132. if len(body) == 0 && len(ereq.BodyBuffer) != 0 {
  133. return false, nil
  134. }
  135. // Match body by atomic string comparison
  136. bodyStr := castToString(body)
  137. matchStr := castToString(ereq.BodyBuffer)
  138. if bodyStr == matchStr {
  139. return true, nil
  140. }
  141. // Match request body by regexp
  142. match, _ := regexp.MatchString(matchStr, bodyStr)
  143. if match == true {
  144. return true, nil
  145. }
  146. // todo - add conditional do only perform the conversion of body bytes
  147. // representation of JSON to a map and then compare them for equality.
  148. // Check if the key + value pairs match
  149. var bodyMap map[string]interface{}
  150. var matchMap map[string]interface{}
  151. // Ensure that both byte bodies that that should be JSON can be converted to maps.
  152. umErr := json.Unmarshal(body, &bodyMap)
  153. umErr2 := json.Unmarshal(ereq.BodyBuffer, &matchMap)
  154. if umErr == nil && umErr2 == nil && reflect.DeepEqual(bodyMap, matchMap) {
  155. return true, nil
  156. }
  157. return false, nil
  158. }
  159. func supportedType(req *http.Request) bool {
  160. mime := req.Header.Get("Content-Type")
  161. if mime == "" {
  162. return true
  163. }
  164. for _, kind := range BodyTypes {
  165. if match, _ := regexp.MatchString(kind, mime); match {
  166. return true
  167. }
  168. }
  169. return false
  170. }
  171. func supportedCompressionScheme(req *http.Request) bool {
  172. encoding := req.Header.Get("Content-Encoding")
  173. if encoding == "" {
  174. return true
  175. }
  176. for _, kind := range CompressionSchemes {
  177. if match, _ := regexp.MatchString(kind, encoding); match {
  178. return true
  179. }
  180. }
  181. return false
  182. }
  183. func castToString(buf []byte) string {
  184. str := string(buf)
  185. tail := len(str) - 1
  186. if str[tail] == EOL {
  187. str = str[:tail]
  188. }
  189. return str
  190. }
  191. func compressionReader(r io.ReadCloser, scheme string) (io.ReadCloser, error) {
  192. switch scheme {
  193. case "gzip":
  194. return gzip.NewReader(r)
  195. default:
  196. return r, nil
  197. }
  198. }