github.com/vugu/vugu@v0.3.6-0.20240430171613-3f6f402e014b/devutil/mux_test.go (about)

     1  package devutil
     2  
     3  import (
     4  	"net/http"
     5  	"net/http/httptest"
     6  	"os"
     7  	"testing"
     8  )
     9  
    10  func TestMux(t *testing.T) {
    11  
    12  	tmpFile, err := os.CreateTemp("", "TestMux")
    13  	must(err)
    14  	_, _ = tmpFile.Write([]byte("<html><body>contents of temp file</body></html>"))
    15  	tmpFile.Close()
    16  	defer os.Remove(tmpFile.Name())
    17  
    18  	m := NewMux().
    19  		Exact("/blah", DefaultIndex).
    20  		Exact("/tmpfile", StaticFilePath(tmpFile.Name())).
    21  		Match(NoFileExt, StaticContent(`<html><body>NoFileExt test</body></html>`))
    22  
    23  	// exact route with StaticContent
    24  	wr := httptest.NewRecorder()
    25  	r, _ := http.NewRequest("GET", "/blah", nil)
    26  	m.ServeHTTP(wr, r)
    27  	checkStatus(t, r, wr.Result(), 200)
    28  	checkBody(t, r, wr.Result(), "<script")
    29  	checkHeader(t, r, wr.Result(), "Content-Type", "text/html; charset=utf-8")
    30  
    31  	// exact route with StaticFilePath
    32  	wr = httptest.NewRecorder()
    33  	r, _ = http.NewRequest("GET", "/tmpfile", nil)
    34  	m.ServeHTTP(wr, r)
    35  	checkStatus(t, r, wr.Result(), 200)
    36  	checkBody(t, r, wr.Result(), "contents of temp file")
    37  	checkHeader(t, r, wr.Result(), "Content-Type", "text/html; charset=utf-8")
    38  
    39  	// NoFileExt
    40  	wr = httptest.NewRecorder()
    41  	r, _ = http.NewRequest("GET", "/otherfile", nil)
    42  	m.ServeHTTP(wr, r)
    43  	checkStatus(t, r, wr.Result(), 200)
    44  	checkBody(t, r, wr.Result(), "NoFileExt test")
    45  	checkHeader(t, r, wr.Result(), "Content-Type", "text/html; charset=utf-8")
    46  
    47  	// no default, 404
    48  	wr = httptest.NewRecorder()
    49  	r, _ = http.NewRequest("GET", "/aintthere.css", nil)
    50  	m.ServeHTTP(wr, r)
    51  	checkStatus(t, r, wr.Result(), 404)
    52  	checkBody(t, r, wr.Result(), "404 page not found")
    53  
    54  	// default
    55  	m.Default(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
    56  		_, _ = w.Write([]byte("<html><body>default overridden</body></body>"))
    57  	}))
    58  	wr = httptest.NewRecorder()
    59  	r, _ = http.NewRequest("GET", "/aintthere.css", nil)
    60  	m.ServeHTTP(wr, r)
    61  	checkBody(t, r, wr.Result(), "default overridden")
    62  
    63  }