From c32167d65f2e0d4e590a27fef01e7e852113895d Mon Sep 17 00:00:00 2001 From: witchc Date: Wed, 29 Sep 2021 01:38:52 +0800 Subject: [PATCH] Add IRouter interface, test and documentation --- README.md | 26 ++++++++++++++++++++++++++ go.mod | 2 +- routergroup.go | 1 + routergroup_test.go | 5 +++++ 4 files changed, 33 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 10be5e15..350437c2 100644 --- a/README.md +++ b/README.md @@ -1248,6 +1248,32 @@ func main() { } ``` +### Serving static files from embed + +```go +// static +// ├── css +// │ └── chunk.css +// ├── favicon.ico +// ├── index.html +// +//go:embed static +var static embed.FS + +func main() { + router := gin.Default() + // /public/css/chunk.css + // /public/favicon.ico + // /public/index.html + router.StaticFSFromEmbed("/public/", "static/", static) + // /asset/chunk.css + router.StaticFSFromEmbed("/asset/", "static/css/", static) + // Listen and serve on 0.0.0.0:8080 + router.Run(":8080") +} + +``` + ### Serving data from file ```go diff --git a/go.mod b/go.mod index 80807e85..55f40ed5 100644 --- a/go.mod +++ b/go.mod @@ -1,6 +1,6 @@ module github.com/gin-gonic/gin -go 1.13 +go 1.16 require ( github.com/gin-contrib/sse v0.1.0 diff --git a/routergroup.go b/routergroup.go index 3906f528..380288fd 100644 --- a/routergroup.go +++ b/routergroup.go @@ -38,6 +38,7 @@ type IRoutes interface { OPTIONS(string, ...HandlerFunc) IRoutes HEAD(string, ...HandlerFunc) IRoutes + StaticFSFromEmbed(relativePath, root string, assets embed.FS) IRoutes StaticFile(string, string) IRoutes Static(string, string) IRoutes StaticFS(string, http.FileSystem) IRoutes diff --git a/routergroup_test.go b/routergroup_test.go index d6d8b452..e8ff4b61 100644 --- a/routergroup_test.go +++ b/routergroup_test.go @@ -5,6 +5,7 @@ package gin import ( + "embed" "net/http" "testing" @@ -162,6 +163,9 @@ func TestRouterGroupPipeline(t *testing.T) { testRoutesInterface(t, v1) } +//go:embed testdata +var embed_static embed.FS + func testRoutesInterface(t *testing.T, r IRoutes) { handler := func(c *Context) {} assert.Equal(t, r, r.Use(handler)) @@ -179,4 +183,5 @@ func testRoutesInterface(t *testing.T, r IRoutes) { assert.Equal(t, r, r.StaticFile("/file", ".")) assert.Equal(t, r, r.Static("/static", ".")) assert.Equal(t, r, r.StaticFS("/static2", Dir(".", false))) + assert.Equal(t, r, r.StaticFSFromEmbed("/static3", "testdata", embed_static)) }