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