Browse Source
* Guess the scheme if r.URL.Scheme is unset It's not expected that the request's URL is fully populated when used on the server-side (it's more of a client-side field), so we shouldn't expect it to be present. In practice, it's only rarely set at all on the server, making mux's `Schemes` matcher tricky to use as it is. This commit adds a test which would have failed before demonstrating the problem, as well as a fix which I think makes `.Schemes` match what users expect. * [doc] Add more detail to Schemes and URL godocs * Add route url test for schemes * Make httpserver test use more specific scheme matchers * Update test to have different responses per routepull/526/head
4 changed files with 85 additions and 19 deletions
@ -0,0 +1,49 @@ |
|||||||
|
// +build go1.9
|
||||||
|
|
||||||
|
package mux |
||||||
|
|
||||||
|
import ( |
||||||
|
"bytes" |
||||||
|
"io/ioutil" |
||||||
|
"net/http" |
||||||
|
"net/http/httptest" |
||||||
|
"testing" |
||||||
|
) |
||||||
|
|
||||||
|
func TestSchemeMatchers(t *testing.T) { |
||||||
|
router := NewRouter() |
||||||
|
router.HandleFunc("/", func(rw http.ResponseWriter, r *http.Request) { |
||||||
|
rw.Write([]byte("hello http world")) |
||||||
|
}).Schemes("http") |
||||||
|
router.HandleFunc("/", func(rw http.ResponseWriter, r *http.Request) { |
||||||
|
rw.Write([]byte("hello https world")) |
||||||
|
}).Schemes("https") |
||||||
|
|
||||||
|
assertResponseBody := func(t *testing.T, s *httptest.Server, expectedBody string) { |
||||||
|
resp, err := s.Client().Get(s.URL) |
||||||
|
if err != nil { |
||||||
|
t.Fatalf("unexpected error getting from server: %v", err) |
||||||
|
} |
||||||
|
if resp.StatusCode != 200 { |
||||||
|
t.Fatalf("expected a status code of 200, got %v", resp.StatusCode) |
||||||
|
} |
||||||
|
body, err := ioutil.ReadAll(resp.Body) |
||||||
|
if err != nil { |
||||||
|
t.Fatalf("unexpected error reading body: %v", err) |
||||||
|
} |
||||||
|
if !bytes.Equal(body, []byte(expectedBody)) { |
||||||
|
t.Fatalf("response should be hello world, was: %q", string(body)) |
||||||
|
} |
||||||
|
} |
||||||
|
|
||||||
|
t.Run("httpServer", func(t *testing.T) { |
||||||
|
s := httptest.NewServer(router) |
||||||
|
defer s.Close() |
||||||
|
assertResponseBody(t, s, "hello http world") |
||||||
|
}) |
||||||
|
t.Run("httpsServer", func(t *testing.T) { |
||||||
|
s := httptest.NewTLSServer(router) |
||||||
|
defer s.Close() |
||||||
|
assertResponseBody(t, s, "hello https world") |
||||||
|
}) |
||||||
|
} |
||||||
Loading…
Reference in new issue