github.com/IRelaxxx/servefiles/v3@v3.4.6/echo_adapter/handler_test.go (about) 1 package echo_adapter_test 2 3 import ( 4 "log" 5 "net/http" 6 "net/http/httptest" 7 "testing" 8 "time" 9 10 "github.com/IRelaxxx/servefiles/v3/echo_adapter" 11 "github.com/labstack/echo/v4" 12 . "github.com/onsi/gomega" 13 "github.com/spf13/afero" 14 ) 15 16 func ExampleHandlerFunc() { 17 // This is a webserver using the asset handler provided by 18 // github.com/IRelaxxx/servefiles/v3, which has enhanced 19 // HTTP expiry, cache control, compression etc. 20 // 'Normal' bespoke handlers are included as needed. 21 22 // where the assets are stored (replace as required) 23 localPath := "./assets" 24 25 // how long we allow user agents to cache assets 26 // (this is in addition to conditional requests, see 27 // RFC7234 https://tools.ietf.org/html/rfc7234#section-5.2.2.8) 28 maxAge := time.Hour 29 30 // define the URL pattern that will be routed to the asset handler 31 // (optional) 32 const path = "/files/*" 33 34 router := echo.New() 35 // ... add other routes / handlers / middleware as required 36 37 h := echo_adapter.NewAssetHandler(localPath). 38 WithMaxAge(maxAge). 39 WithNotFound(http.NotFoundHandler()). // supply your own 40 StripOff(1). 41 HandlerFunc(path) 42 43 router.GET(path, h) 44 router.HEAD(path, h) 45 46 log.Fatal(http.ListenAndServe(":8080", router)) 47 } 48 49 func TestHandlerFunc(t *testing.T) { 50 g := NewGomegaWithT(t) 51 52 maxAge := time.Hour 53 fs := afero.NewMemMapFs() 54 fs.MkdirAll("/foo/bar", 0755) 55 afero.WriteFile(fs, "/foo/bar/x.txt", []byte("hello"), 0644) 56 57 const assetPath = "/files/*" 58 59 h := echo_adapter.NewAssetHandlerFS(fs). 60 WithMaxAge(maxAge). 61 WithNotFound(http.NotFoundHandler()). // supply your own 62 StripOff(1) 63 64 router := echo.New() 65 // ... add other routes / handlers / middleware as required 66 h.Register(router, assetPath) 67 68 r, _ := http.NewRequest(http.MethodGet, "http://localhost/files/101/foo/bar/x.txt", nil) 69 w := httptest.NewRecorder() 70 router.ServeHTTP(w, r) 71 72 g.Expect(w.Code).To(Equal(200)) 73 g.Expect(w.Header().Get("Content-Type")).To(Equal("text/plain; charset=utf-8")) 74 g.Expect(w.Header().Get("Expires")).NotTo(Equal("")) 75 g.Expect(w.Body.Len()).To(Equal(5)) 76 77 r, _ = http.NewRequest(http.MethodHead, "http://localhost/files/101/foo/bar/x.txt", nil) 78 w = httptest.NewRecorder() 79 router.ServeHTTP(w, r) 80 81 g.Expect(w.Code).To(Equal(200)) 82 g.Expect(w.Header().Get("Content-Type")).To(Equal("text/plain; charset=utf-8")) 83 g.Expect(w.Header().Get("Expires")).NotTo(Equal("")) 84 g.Expect(w.Body.Len()).To(Equal(0)) 85 86 r, _ = http.NewRequest(http.MethodHead, "http://localhost/files/101/foo/baz.png", nil) 87 w = httptest.NewRecorder() 88 router.ServeHTTP(w, r) 89 90 g.Expect(w.Code).To(Equal(404)) 91 }