You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 

181 lines
4.0 KiB

  1. package testutil
  2. import (
  3. "bytes"
  4. "fmt"
  5. "io/ioutil"
  6. "net"
  7. "net/http"
  8. "net/url"
  9. "os"
  10. "time"
  11. )
  12. type HTTPServer struct {
  13. URL string
  14. Timeout time.Duration
  15. started bool
  16. request chan *http.Request
  17. response chan ResponseFunc
  18. }
  19. type Response struct {
  20. Status int
  21. Headers map[string]string
  22. Body string
  23. }
  24. var DefaultClient = &http.Client{
  25. Transport: &http.Transport{
  26. Proxy: http.ProxyFromEnvironment,
  27. },
  28. }
  29. func NewHTTPServer() *HTTPServer {
  30. return &HTTPServer{URL: "http://localhost:4444", Timeout: 5 * time.Second}
  31. }
  32. type ResponseFunc func(path string) Response
  33. func (s *HTTPServer) Start() {
  34. if s.started {
  35. return
  36. }
  37. s.started = true
  38. s.request = make(chan *http.Request, 1024)
  39. s.response = make(chan ResponseFunc, 1024)
  40. u, err := url.Parse(s.URL)
  41. if err != nil {
  42. panic(err)
  43. }
  44. l, err := net.Listen("tcp", u.Host)
  45. if err != nil {
  46. panic(err)
  47. }
  48. go http.Serve(l, s)
  49. s.Response(203, nil, "")
  50. for {
  51. // Wait for it to be up.
  52. resp, err := http.Get(s.URL)
  53. if err == nil && resp.StatusCode == 203 {
  54. break
  55. }
  56. time.Sleep(1e8)
  57. }
  58. s.WaitRequest() // Consume dummy request.
  59. }
  60. // Flush discards all pending requests and responses.
  61. func (s *HTTPServer) Flush() {
  62. for {
  63. select {
  64. case <-s.request:
  65. case <-s.response:
  66. default:
  67. return
  68. }
  69. }
  70. }
  71. func body(req *http.Request) string {
  72. data, err := ioutil.ReadAll(req.Body)
  73. if err != nil {
  74. panic(err)
  75. }
  76. return string(data)
  77. }
  78. func (s *HTTPServer) ServeHTTP(w http.ResponseWriter, req *http.Request) {
  79. req.ParseMultipartForm(1e6)
  80. data, err := ioutil.ReadAll(req.Body)
  81. if err != nil {
  82. panic(err)
  83. }
  84. req.Body = ioutil.NopCloser(bytes.NewBuffer(data))
  85. s.request <- req
  86. var resp Response
  87. select {
  88. case respFunc := <-s.response:
  89. resp = respFunc(req.URL.Path)
  90. case <-time.After(s.Timeout):
  91. const msg = "ERROR: Timeout waiting for test to prepare a response\n"
  92. fmt.Fprintf(os.Stderr, msg)
  93. resp = Response{500, nil, msg}
  94. }
  95. if resp.Headers != nil {
  96. h := w.Header()
  97. for k, v := range resp.Headers {
  98. h.Set(k, v)
  99. }
  100. }
  101. if resp.Status != 0 {
  102. w.WriteHeader(resp.Status)
  103. }
  104. w.Write([]byte(resp.Body))
  105. }
  106. // WaitRequests returns the next n requests made to the http server from
  107. // the queue. If not enough requests were previously made, it waits until
  108. // the timeout value for them to be made.
  109. func (s *HTTPServer) WaitRequests(n int) []*http.Request {
  110. reqs := make([]*http.Request, 0, n)
  111. for i := 0; i < n; i++ {
  112. select {
  113. case req := <-s.request:
  114. reqs = append(reqs, req)
  115. case <-time.After(s.Timeout):
  116. panic("Timeout waiting for request")
  117. }
  118. }
  119. return reqs
  120. }
  121. // WaitRequest returns the next request made to the http server from
  122. // the queue. If no requests were previously made, it waits until the
  123. // timeout value for one to be made.
  124. func (s *HTTPServer) WaitRequest() *http.Request {
  125. return s.WaitRequests(1)[0]
  126. }
  127. // ResponseFunc prepares the test server to respond the following n
  128. // requests using f to build each response.
  129. func (s *HTTPServer) ResponseFunc(n int, f ResponseFunc) {
  130. for i := 0; i < n; i++ {
  131. s.response <- f
  132. }
  133. }
  134. // ResponseMap maps request paths to responses.
  135. type ResponseMap map[string]Response
  136. // ResponseMap prepares the test server to respond the following n
  137. // requests using the m to obtain the responses.
  138. func (s *HTTPServer) ResponseMap(n int, m ResponseMap) {
  139. f := func(path string) Response {
  140. for rpath, resp := range m {
  141. if rpath == path {
  142. return resp
  143. }
  144. }
  145. body := "Path not found in response map: " + path
  146. return Response{Status: 500, Body: body}
  147. }
  148. s.ResponseFunc(n, f)
  149. }
  150. // Responses prepares the test server to respond the following n requests
  151. // using the provided response parameters.
  152. func (s *HTTPServer) Responses(n int, status int, headers map[string]string, body string) {
  153. f := func(path string) Response {
  154. return Response{status, headers, body}
  155. }
  156. s.ResponseFunc(n, f)
  157. }
  158. // Response prepares the test server to respond the following request
  159. // using the provided response parameters.
  160. func (s *HTTPServer) Response(status int, headers map[string]string, body string) {
  161. s.Responses(1, status, headers, body)
  162. }