No puede seleccionar más de 25 temas Los temas deben comenzar con una letra o número, pueden incluir guiones ('-') y pueden tener hasta 35 caracteres de largo.
 
 
 

67 líneas
1.7 KiB

  1. package martiantest
  2. import (
  3. "net/http"
  4. "github.com/google/martian/proxyutil"
  5. )
  6. // Transport is an http.RoundTripper for testing.
  7. type Transport struct {
  8. rtfunc func(*http.Request) (*http.Response, error)
  9. }
  10. // NewTransport builds a new transport that will respond with a 200 OK
  11. // response.
  12. func NewTransport() *Transport {
  13. tr := &Transport{}
  14. tr.Respond(200)
  15. return tr
  16. }
  17. // Respond sets the transport to respond with response with statusCode.
  18. func (tr *Transport) Respond(statusCode int) {
  19. tr.rtfunc = func(req *http.Request) (*http.Response, error) {
  20. // Force CONNECT requests to 200 to test CONNECT with downstream proxy.
  21. if req.Method == "CONNECT" {
  22. statusCode = 200
  23. }
  24. res := proxyutil.NewResponse(statusCode, nil, req)
  25. return res, nil
  26. }
  27. }
  28. // RespondError sets the transport to respond with an error on round trip.
  29. func (tr *Transport) RespondError(err error) {
  30. tr.rtfunc = func(*http.Request) (*http.Response, error) {
  31. return nil, err
  32. }
  33. }
  34. // CopyHeaders sets the transport to respond with a 200 OK response with
  35. // headers copied from the request to the response verbatim.
  36. func (tr *Transport) CopyHeaders(names ...string) {
  37. tr.rtfunc = func(req *http.Request) (*http.Response, error) {
  38. res := proxyutil.NewResponse(200, nil, req)
  39. for _, n := range names {
  40. res.Header.Set(n, req.Header.Get(n))
  41. }
  42. return res, nil
  43. }
  44. }
  45. // Func sets the transport to use the rtfunc.
  46. func (tr *Transport) Func(rtfunc func(*http.Request) (*http.Response, error)) {
  47. tr.rtfunc = rtfunc
  48. }
  49. // RoundTrip runs the stored round trip func and returns the response.
  50. func (tr *Transport) RoundTrip(req *http.Request) (*http.Response, error) {
  51. return tr.rtfunc(req)
  52. }