registry_mock.go 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. package main
  2. import (
  3. "net/http"
  4. "net/http/httptest"
  5. "regexp"
  6. "strings"
  7. "sync"
  8. "github.com/go-check/check"
  9. )
  10. type handlerFunc func(w http.ResponseWriter, r *http.Request)
  11. type testRegistry struct {
  12. server *httptest.Server
  13. hostport string
  14. handlers map[string]handlerFunc
  15. mu sync.Mutex
  16. }
  17. func (tr *testRegistry) registerHandler(path string, h handlerFunc) {
  18. tr.mu.Lock()
  19. defer tr.mu.Unlock()
  20. tr.handlers[path] = h
  21. }
  22. func newTestRegistry(c *check.C) (*testRegistry, error) {
  23. testReg := &testRegistry{handlers: make(map[string]handlerFunc)}
  24. ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  25. url := r.URL.String()
  26. var matched bool
  27. var err error
  28. for re, function := range testReg.handlers {
  29. matched, err = regexp.MatchString(re, url)
  30. if err != nil {
  31. c.Fatal("Error with handler regexp")
  32. }
  33. if matched {
  34. function(w, r)
  35. break
  36. }
  37. }
  38. if !matched {
  39. c.Fatalf("Unable to match %s with regexp", url)
  40. }
  41. }))
  42. testReg.server = ts
  43. testReg.hostport = strings.Replace(ts.URL, "http://", "", 1)
  44. return testReg, nil
  45. }