From 2a2458152c9a9d7b20259b9e2f337b694a1996ac Mon Sep 17 00:00:00 2001 From: thinkgo Date: Sun, 22 Aug 2021 22:31:48 +0800 Subject: [PATCH] update README `tab` improve StaticFile and StaticFileFS code, use staticFileHandler --- README.md | 2 +- routergroup.go | 19 ++++++++----------- 2 files changed, 9 insertions(+), 12 deletions(-) diff --git a/README.md b/README.md index 48c030fba5..303c6a7c10 100644 --- a/README.md +++ b/README.md @@ -1241,7 +1241,7 @@ func main() { router.Static("/assets", "./assets") router.StaticFS("/more_static", http.Dir("my_file_system")) router.StaticFile("/favicon.ico", "./resources/favicon.ico") - router.StaticFileFS("/more_favicon.ico", "more_favicon.ico", http.Dir("my_file_system")) + router.StaticFileFS("/more_favicon.ico", "more_favicon.ico", http.Dir("my_file_system")) // Listen and serve on 0.0.0.0:8080 router.Run(":8080") diff --git a/routergroup.go b/routergroup.go index df94b3209c..5f955f0443 100644 --- a/routergroup.go +++ b/routergroup.go @@ -152,27 +152,24 @@ func (group *RouterGroup) Any(relativePath string, handlers ...HandlerFunc) IRou // StaticFile registers a single route in order to serve a single file of the local filesystem. // router.StaticFile("favicon.ico", "./resources/favicon.ico") func (group *RouterGroup) StaticFile(relativePath, filepath string) IRoutes { - if strings.Contains(relativePath, ":") || strings.Contains(relativePath, "*") { - panic("URL parameters can not be used when serving a static file") - } - handler := func(c *Context) { + return group.staticFileHandler(relativePath, func(c *Context) { c.File(filepath) - } - group.GET(relativePath, handler) - group.HEAD(relativePath, handler) - return group.returnObj() + }) } // StaticFileFS works just like `StaticFile` but a custom `http.FileSystem` can be used instead.. // router.StaticFileFS("favicon.ico", "./resources/favicon.ico", Dir{".", false}) // Gin by default user: gin.Dir() func (group *RouterGroup) StaticFileFS(relativePath, filepath string, fs http.FileSystem) IRoutes { + return group.staticFileHandler(relativePath, func(c *Context) { + c.FileFromFS(filepath, fs) + }) +} + +func (group *RouterGroup) staticFileHandler(relativePath string, handler HandlerFunc) IRoutes { if strings.Contains(relativePath, ":") || strings.Contains(relativePath, "*") { panic("URL parameters can not be used when serving a static file") } - handler := func(c *Context) { - c.FileFromFS(filepath, fs) - } group.GET(relativePath, handler) group.HEAD(relativePath, handler) return group.returnObj()