Skip to content

Commit

Permalink
update README tab
Browse files Browse the repository at this point in the history
improve StaticFile and StaticFileFS code, use staticFileHandler
  • Loading branch information
thinkgos committed Aug 22, 2021
1 parent 243adec commit 2a24581
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 12 deletions.
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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")
Expand Down
19 changes: 8 additions & 11 deletions routergroup.go
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand Down

0 comments on commit 2a24581

Please sign in to comment.