...

Source file src/github.com/gorilla/mux/mux_httpserver_test.go

Documentation: github.com/gorilla/mux

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

View as plain text