Skip to content
Myr

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

8 files+258 added−18 removed

modified:docs/doc.md+7 added-1 removed
1391 unmodified lines
1392```13931394### HTML rendering13951396Using LoadHTMLGlob() or LoadHTMLFiles()1396Using LoadHTMLGlob() or LoadHTMLFiles() or LoadHTMLFS()13971398```go1399//go:embed templates/*1400var templates embed.FS14011402func 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 lines
modified:ginS/gins.go+5 added
30 unmodified lines
31func LoadHTMLFiles(files ...string) {32 engine().LoadHTMLFiles(files...)33}3435// LoadHTMLFS is a wrapper for Engine.LoadHTMLFS.36func LoadHTMLFS(fs http.FileSystem, patterns ...string) {37 engine().LoadHTMLFS(fs, patterns...)38}3940// SetHTMLTemplate is a wrapper for Engine.SetHTMLTemplate.41func SetHTMLTemplate(templ *template.Template) {42 engine().SetHTMLTemplate(templ)43}
122 unmodified lines
added:internal/fs/fs_test.go+49 added
1package fs23import (4 "errors"5 "net/http"6 "os"7 "testing"89 "github.com/stretchr/testify/assert"10 "github.com/stretchr/testify/require"11)1213type mockFileSystem struct {14 open func(name string) (http.File, error)15}1617func (m *mockFileSystem) Open(name string) (http.File, error) {18 return m.open(name)19}2021func 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}2930 file, err := fs.Open("foo")3132 require.NoError(t, err)33 assert.Equal(t, testFile, file)34}3536func 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}4445 file, err := fs.Open("foo")4647 require.ErrorIs(t, err, testError)48 assert.Nil(t, file)49}
added:internal/fs/fs.go+22 added
1package fs23import (4 "io/fs"5 "net/http"6)78// FileSystem implements an [fs.FS].9type FileSystem struct {10 http.FileSystem11}1213// Open passes `Open` to the upstream implementation and return an [fs.File].14func (o FileSystem) Open(name string) (fs.File, error) {15 f, err := o.FileSystem.Open(name)1617 if err != nil {18 return nil, err19 }2021 return fs.File(f), nil22}
modified:render/html.go+13 added-5 removed
5 unmodified lines
67import (8 "html/template"9 "net/http"1011 "github.com/gin-gonic/gin/internal/fs"12)1314// Delims represents a set of Left and Right delimiters for HTML template rendering.15type Delims struct {
16 unmodified lines
32}3334// HTMLDebug contains template delims and pattern and function with file list.35type 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}4344// HTML contains template reference and its name with given interface object.45type HTML struct {
30 unmodified lines
76 }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}8687// Render (HTML) executes template and writes its result with custom ContentType for response.88func (r HTML) Render(w http.ResponseWriter) error {
12 unmodified lines
modified:render/render_test.go+39 added-12 removed
487 unmodified lines
488489func 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 lines
509510func 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 lines
527 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}530531func 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 })544545 err := instance.Render(w)546547 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}551552func 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 lines
modified:gin_test.go+109 added
323 unmodified lines
324 resp, _ := io.ReadAll(res.Body)325 assert.Equal(t, "Date: 2017/07/01", string(resp))326}327328var tmplFS = http.Dir("testdata/template")329330func 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()340341 res, err := http.Get(fmt.Sprintf("%s/test", ts.URL))342 if err != nil {343 t.Error(err)344 }345346 resp, _ := io.ReadAll(res.Body)347 assert.Equal(t, "<h1>Hello world</h1>", string(resp))348}349350func 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()360361 res, err := http.Get(fmt.Sprintf("%s/test", ts.URL))362 if err != nil {363 t.Error(err)364 }365366 resp, _ := io.ReadAll(res.Body)367 assert.Equal(t, "<h1>Hello world</h1>", string(resp))368}369370func 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()380381 res, err := http.Get(fmt.Sprintf("%s/test", ts.URL))382 if err != nil {383 t.Error(err)384 }385386 resp, _ := io.ReadAll(res.Body)387 assert.Equal(t, "<h1>Hello world</h1>", string(resp))388}389390func 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()400401 // 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 }412413 resp, _ := io.ReadAll(res.Body)414 assert.Equal(t, "<h1>Hello world</h1>", string(resp))415}416417func 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()427428 res, err := http.Get(fmt.Sprintf("%s/raw", ts.URL))429 if err != nil {430 t.Error(err)431 }432433 resp, _ := io.ReadAll(res.Body)434 assert.Equal(t, "Date: 2017/07/01", string(resp))435}436437func TestAddRoute(t *testing.T) {438 router := New()439 router.addRoute(http.MethodGet, "/", HandlersChain{func(_ *Context) {}})440
475 unmodified lines
modified:gin.go+14 added
14 unmodified lines
15 "strings"16 "sync"1718 "github.com/gin-gonic/gin/internal/bytesconv"19 filesystem "github.com/gin-gonic/gin/internal/fs"20 "github.com/gin-gonic/gin/render"2122 "github.com/quic-go/quic-go/http3"23 "golang.org/x/net/http2"
261 unmodified lines
285 templ := template.Must(template.New("").Delims(engine.delims.Left, engine.delims.Right).Funcs(engine.FuncMap).ParseFiles(files...))286 engine.SetHTMLTemplate(templ)287}288289// LoadHTMLFS loads an http.FileSystem and a slice of patterns290// and associates the result with HTML renderer.291func (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 }296297 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}301302// SetHTMLTemplate associate a template with HTML renderer.303func (engine *Engine) SetHTMLTemplate(templ *template.Template) {304 if len(engine.trees) > 0 {305 debugPrintWARNINGSetHTMLTemplate()
484 unmodified lines