feat(fs): Implement loading HTML from http.FileSystem (#4053)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
* Implement loading HTML from http.FileSystem * Add OnlyHTMLFS test * Move OnlyHTMLFS to internal and add test
authored by sunshineplan · committed by GitHub · parent 0eb9949 · Browse files · 8 files·+258 added−18 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
8 files+258 added−18 removed
- other:+258 added−18 removed
Provenance
- Commit
71496ab- Tree
3390ec6- Author
sunshineplan <sunshineplan@users.noreply.github.com>- Committer
GitHub <noreply@github.com>- Parent
0eb9949
8 files changed+258 added−18 removed
modified:docs/doc.md+7 added-1 removed
1391 unmodified lines1392 ```1393 1394 ### HTML rendering1395 1396-Using LoadHTMLGlob() or LoadHTMLFiles()1396+Using LoadHTMLGlob() or LoadHTMLFiles() or LoadHTMLFS()1397 1398 ```go1399+//go:embed templates/*1400+var templates embed.FS1401+1402 func main() {1403 router := gin.Default()1404 router.LoadHTMLGlob("templates/*")1405 //router.LoadHTMLFiles("templates/template1.html", "templates/template2.html")1406+ //router.LoadHTMLFS(http.Dir("templates"), "template1.html", "template2.html")1407+ //or1408+ //router.LoadHTMLFS(http.FS(templates), "templates/template1.html", "templates/template2.html")1409 router.GET("/index", func(c *gin.Context) {1410 c.HTML(http.StatusOK, "index.tmpl", gin.H{1411 "title": "Main website",1412 })1033 unmodified linesmodified:ginS/gins.go+5 added
30 unmodified lines31 func LoadHTMLFiles(files ...string) {32 engine().LoadHTMLFiles(files...)33 }34 35+// LoadHTMLFS is a wrapper for Engine.LoadHTMLFS.36+func LoadHTMLFS(fs http.FileSystem, patterns ...string) {37+ engine().LoadHTMLFS(fs, patterns...)38+}39+40 // SetHTMLTemplate is a wrapper for Engine.SetHTMLTemplate.41 func SetHTMLTemplate(templ *template.Template) {42 engine().SetHTMLTemplate(templ)43 }122 unmodified linesadded:internal/fs/fs_test.go+49 added
1+package fs2+3+import (4+ "errors"5+ "net/http"6+ "os"7+ "testing"8+9+ "github.com/stretchr/testify/assert"10+ "github.com/stretchr/testify/require"11+)12+13+type mockFileSystem struct {14+ open func(name string) (http.File, error)15+}16+17+func (m *mockFileSystem) Open(name string) (http.File, error) {18+ return m.open(name)19+}20+21+func TesFileSystem_Open(t *testing.T) {22+ var testFile *os.File23+ mockFS := &mockFileSystem{24+ open: func(name string) (http.File, error) {25+ return testFile, nil26+ },27+ }28+ fs := &FileSystem{mockFS}29+30+ file, err := fs.Open("foo")31+32+ require.NoError(t, err)33+ assert.Equal(t, testFile, file)34+}35+36+func TestFileSystem_Open_err(t *testing.T) {37+ testError := errors.New("mock")38+ mockFS := &mockFileSystem{39+ open: func(_ string) (http.File, error) {40+ return nil, testError41+ },42+ }43+ fs := &FileSystem{mockFS}44+45+ file, err := fs.Open("foo")46+47+ require.ErrorIs(t, err, testError)48+ assert.Nil(t, file)49+}added:internal/fs/fs.go+22 added
1+package fs2+3+import (4+ "io/fs"5+ "net/http"6+)7+8+// FileSystem implements an [fs.FS].9+type FileSystem struct {10+ http.FileSystem11+}12+13+// Open passes `Open` to the upstream implementation and return an [fs.File].14+func (o FileSystem) Open(name string) (fs.File, error) {15+ f, err := o.FileSystem.Open(name)16+17+ if err != nil {18+ return nil, err19+ }20+21+ return fs.File(f), nil22+}modified:render/html.go+13 added-5 removed
5 unmodified lines6 7 import (8 "html/template"9 "net/http"10+11+ "github.com/gin-gonic/gin/internal/fs"12 )13 14 // Delims represents a set of Left and Right delimiters for HTML template rendering.15 type Delims struct {16 unmodified lines32 }33 34 // HTMLDebug contains template delims and pattern and function with file list.35 type HTMLDebug struct {34- Files []string35- Glob string36- Delims Delims37- FuncMap template.FuncMap36+ Files []string37+ Glob string38+ FileSystem http.FileSystem39+ Patterns []string40+ Delims Delims41+ FuncMap template.FuncMap42 }43 44 // HTML contains template reference and its name with given interface object.45 type HTML struct {30 unmodified lines76 }77 if r.Glob != "" {78 return template.Must(template.New("").Delims(r.Delims.Left, r.Delims.Right).Funcs(r.FuncMap).ParseGlob(r.Glob))79 }80+ if r.FileSystem != nil && len(r.Patterns) > 0 {81+ return template.Must(template.New("").Delims(r.Delims.Left, r.Delims.Right).Funcs(r.FuncMap).ParseFS(82+ fs.FileSystem{FileSystem: r.FileSystem}, r.Patterns...))83+ }76- panic("the HTML debug render was created without files or glob pattern")84+ panic("the HTML debug render was created without files or glob pattern or file system with patterns")85 }86 87 // Render (HTML) executes template and writes its result with custom ContentType for response.88 func (r HTML) Render(w http.ResponseWriter) error {12 unmodified linesmodified:render/render_test.go+39 added-12 removed
487 unmodified lines488 489 func TestRenderHTMLDebugFiles(t *testing.T) {490 w := httptest.NewRecorder()491 htmlRender := HTMLDebug{492- Files: []string{"../testdata/template/hello.tmpl"},493- Glob: "",494- Delims: Delims{Left: "{[{", Right: "}]}"},495- FuncMap: nil,492+ Files: []string{"../testdata/template/hello.tmpl"},493+ Glob: "",494+ FileSystem: nil,495+ Patterns: nil,496+ Delims: Delims{Left: "{[{", Right: "}]}"},497+ FuncMap: nil,498 }499 instance := htmlRender.Instance("hello.tmpl", map[string]any{500 "name": "thinkerou",501 })7 unmodified lines509 510 func TestRenderHTMLDebugGlob(t *testing.T) {511 w := httptest.NewRecorder()512 htmlRender := HTMLDebug{511- Files: nil,512- Glob: "../testdata/template/hello*",513- Delims: Delims{Left: "{[{", Right: "}]}"},514- FuncMap: nil,513+ Files: nil,514+ Glob: "../testdata/template/hello*",515+ FileSystem: nil,516+ Patterns: nil,517+ Delims: Delims{Left: "{[{", Right: "}]}"},518+ FuncMap: nil,519 }520 instance := htmlRender.Instance("hello.tmpl", map[string]any{521 "name": "thinkerou",522 })4 unmodified lines527 assert.Equal(t, "<h1>Hello thinkerou</h1>", w.Body.String())528 assert.Equal(t, "text/html; charset=utf-8", w.Header().Get("Content-Type"))529 }530 531+func TestRenderHTMLDebugFS(t *testing.T) {532+ w := httptest.NewRecorder()533+ htmlRender := HTMLDebug{534+ Files: nil,535+ Glob: "",536+ FileSystem: http.Dir("../testdata/template"),537+ Patterns: []string{"hello.tmpl"},538+ Delims: Delims{Left: "{[{", Right: "}]}"},539+ FuncMap: nil,540+ }541+ instance := htmlRender.Instance("hello.tmpl", map[string]any{542+ "name": "thinkerou",543+ })544+545+ err := instance.Render(w)546+547+ require.NoError(t, err)548+ assert.Equal(t, "<h1>Hello thinkerou</h1>", w.Body.String())549+ assert.Equal(t, "text/html; charset=utf-8", w.Header().Get("Content-Type"))550+}551+552 func TestRenderHTMLDebugPanics(t *testing.T) {553 htmlRender := HTMLDebug{529- Files: nil,530- Glob: "",531- Delims: Delims{"{{", "}}"},532- FuncMap: nil,554+ Files: nil,555+ Glob: "",556+ FileSystem: nil,557+ Patterns: nil,558+ Delims: Delims{"{{", "}}"},559+ FuncMap: nil,560 }561 assert.Panics(t, func() { htmlRender.Instance("", nil) })562 }563 58 unmodified linesmodified:gin_test.go+109 added
323 unmodified lines324 resp, _ := io.ReadAll(res.Body)325 assert.Equal(t, "Date: 2017/07/01", string(resp))326 }327 328+var tmplFS = http.Dir("testdata/template")329+330+func TestLoadHTMLFSTestMode(t *testing.T) {331+ ts := setupHTMLFiles(332+ t,333+ TestMode,334+ false,335+ func(router *Engine) {336+ router.LoadHTMLFS(tmplFS, "hello.tmpl", "raw.tmpl")337+ },338+ )339+ defer ts.Close()340+341+ res, err := http.Get(fmt.Sprintf("%s/test", ts.URL))342+ if err != nil {343+ t.Error(err)344+ }345+346+ resp, _ := io.ReadAll(res.Body)347+ assert.Equal(t, "<h1>Hello world</h1>", string(resp))348+}349+350+func TestLoadHTMLFSDebugMode(t *testing.T) {351+ ts := setupHTMLFiles(352+ t,353+ DebugMode,354+ false,355+ func(router *Engine) {356+ router.LoadHTMLFS(tmplFS, "hello.tmpl", "raw.tmpl")357+ },358+ )359+ defer ts.Close()360+361+ res, err := http.Get(fmt.Sprintf("%s/test", ts.URL))362+ if err != nil {363+ t.Error(err)364+ }365+366+ resp, _ := io.ReadAll(res.Body)367+ assert.Equal(t, "<h1>Hello world</h1>", string(resp))368+}369+370+func TestLoadHTMLFSReleaseMode(t *testing.T) {371+ ts := setupHTMLFiles(372+ t,373+ ReleaseMode,374+ false,375+ func(router *Engine) {376+ router.LoadHTMLFS(tmplFS, "hello.tmpl", "raw.tmpl")377+ },378+ )379+ defer ts.Close()380+381+ res, err := http.Get(fmt.Sprintf("%s/test", ts.URL))382+ if err != nil {383+ t.Error(err)384+ }385+386+ resp, _ := io.ReadAll(res.Body)387+ assert.Equal(t, "<h1>Hello world</h1>", string(resp))388+}389+390+func TestLoadHTMLFSUsingTLS(t *testing.T) {391+ ts := setupHTMLFiles(392+ t,393+ TestMode,394+ true,395+ func(router *Engine) {396+ router.LoadHTMLFS(tmplFS, "hello.tmpl", "raw.tmpl")397+ },398+ )399+ defer ts.Close()400+401+ // Use InsecureSkipVerify for avoiding `x509: certificate signed by unknown authority` error402+ tr := &http.Transport{403+ TLSClientConfig: &tls.Config{404+ InsecureSkipVerify: true,405+ },406+ }407+ client := &http.Client{Transport: tr}408+ res, err := client.Get(fmt.Sprintf("%s/test", ts.URL))409+ if err != nil {410+ t.Error(err)411+ }412+413+ resp, _ := io.ReadAll(res.Body)414+ assert.Equal(t, "<h1>Hello world</h1>", string(resp))415+}416+417+func TestLoadHTMLFSFuncMap(t *testing.T) {418+ ts := setupHTMLFiles(419+ t,420+ TestMode,421+ false,422+ func(router *Engine) {423+ router.LoadHTMLFS(tmplFS, "hello.tmpl", "raw.tmpl")424+ },425+ )426+ defer ts.Close()427+428+ res, err := http.Get(fmt.Sprintf("%s/raw", ts.URL))429+ if err != nil {430+ t.Error(err)431+ }432+433+ resp, _ := io.ReadAll(res.Body)434+ assert.Equal(t, "Date: 2017/07/01", string(resp))435+}436+437 func TestAddRoute(t *testing.T) {438 router := New()439 router.addRoute(http.MethodGet, "/", HandlersChain{func(_ *Context) {}})440 475 unmodified linesmodified:gin.go+14 added
14 unmodified lines15 "strings"16 "sync"17 18 "github.com/gin-gonic/gin/internal/bytesconv"19+ filesystem "github.com/gin-gonic/gin/internal/fs"20 "github.com/gin-gonic/gin/render"21 22 "github.com/quic-go/quic-go/http3"23 "golang.org/x/net/http2"261 unmodified lines285 templ := template.Must(template.New("").Delims(engine.delims.Left, engine.delims.Right).Funcs(engine.FuncMap).ParseFiles(files...))286 engine.SetHTMLTemplate(templ)287 }288 289+// LoadHTMLFS loads an http.FileSystem and a slice of patterns290+// and associates the result with HTML renderer.291+func (engine *Engine) LoadHTMLFS(fs http.FileSystem, patterns ...string) {292+ if IsDebugging() {293+ engine.HTMLRender = render.HTMLDebug{FileSystem: fs, Patterns: patterns, FuncMap: engine.FuncMap, Delims: engine.delims}294+ return295+ }296+297+ templ := template.Must(template.New("").Delims(engine.delims.Left, engine.delims.Right).Funcs(engine.FuncMap).ParseFS(298+ filesystem.FileSystem{FileSystem: fs}, patterns...))299+ engine.SetHTMLTemplate(templ)300+}301+302 // SetHTMLTemplate associate a template with HTML renderer.303 func (engine *Engine) SetHTMLTemplate(templ *template.Template) {304 if len(engine.trees) > 0 {305 debugPrintWARNINGSetHTMLTemplate()484 unmodified lines