mux_httpserver_test.go 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. // +build go1.9
  2. package mux
  3. import (
  4. "bytes"
  5. "io/ioutil"
  6. "net/http"
  7. "net/http/httptest"
  8. "testing"
  9. )
  10. func TestSchemeMatchers(t *testing.T) {
  11. router := NewRouter()
  12. router.HandleFunc("/", func(rw http.ResponseWriter, r *http.Request) {
  13. rw.Write([]byte("hello http world"))
  14. }).Schemes("http")
  15. router.HandleFunc("/", func(rw http.ResponseWriter, r *http.Request) {
  16. rw.Write([]byte("hello https world"))
  17. }).Schemes("https")
  18. assertResponseBody := func(t *testing.T, s *httptest.Server, expectedBody string) {
  19. resp, err := s.Client().Get(s.URL)
  20. if err != nil {
  21. t.Fatalf("unexpected error getting from server: %v", err)
  22. }
  23. if resp.StatusCode != 200 {
  24. t.Fatalf("expected a status code of 200, got %v", resp.StatusCode)
  25. }
  26. body, err := ioutil.ReadAll(resp.Body)
  27. if err != nil {
  28. t.Fatalf("unexpected error reading body: %v", err)
  29. }
  30. if !bytes.Equal(body, []byte(expectedBody)) {
  31. t.Fatalf("response should be hello world, was: %q", string(body))
  32. }
  33. }
  34. t.Run("httpServer", func(t *testing.T) {
  35. s := httptest.NewServer(router)
  36. defer s.Close()
  37. assertResponseBody(t, s, "hello http world")
  38. })
  39. t.Run("httpsServer", func(t *testing.T) {
  40. s := httptest.NewTLSServer(router)
  41. defer s.Close()
  42. assertResponseBody(t, s, "hello https world")
  43. })
  44. }