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