mirror of https://github.com/gin-gonic/gin.git
New static file serving
This commit is contained in:
parent
3295c6e9c4
commit
058201713b
|
@ -2,6 +2,7 @@ package gin
|
|||
|
||||
import (
|
||||
"github.com/gin-gonic/gin/binding"
|
||||
"net/http"
|
||||
)
|
||||
|
||||
// DEPRECATED, use Bind() instead.
|
||||
|
@ -15,3 +16,18 @@ func (c *Context) EnsureBody(item interface{}) bool {
|
|||
func (c *Context) ParseBody(item interface{}) error {
|
||||
return binding.JSON.Bind(c.Req, item)
|
||||
}
|
||||
|
||||
// DEPRECATED use gin.Static() instead
|
||||
// ServeFiles serves files from the given file system root.
|
||||
// The path must end with "/*filepath", files are then served from the local
|
||||
// path /defined/root/dir/*filepath.
|
||||
// For example if root is "/etc" and *filepath is "passwd", the local file
|
||||
// "/etc/passwd" would be served.
|
||||
// Internally a http.FileServer is used, therefore http.NotFound is used instead
|
||||
// of the Router's NotFound handler.
|
||||
// To use the operating system's file system implementation,
|
||||
// use http.Dir:
|
||||
// router.ServeFiles("/src/*filepath", http.Dir("/var/www"))
|
||||
func (engine *Engine) ServeFiles(path string, root http.FileSystem) {
|
||||
engine.router.ServeFiles(path, root)
|
||||
}
|
||||
|
|
18
gin.go
18
gin.go
|
@ -304,6 +304,24 @@ func (group *RouterGroup) HEAD(path string, handlers ...HandlerFunc) {
|
|||
group.Handle("HEAD", path, handlers)
|
||||
}
|
||||
|
||||
// Static serves files from the given file system root.
|
||||
// Internally a http.FileServer is used, therefore http.NotFound is used instead
|
||||
// of the Router's NotFound handler.
|
||||
// To use the operating system's file system implementation,
|
||||
// use :
|
||||
// router.Static("/static", "/var/www")
|
||||
func (group *RouterGroup) Static(p, root string) {
|
||||
p = path.Join(p, "/*filepath")
|
||||
fileServer := http.FileServer(http.Dir(root))
|
||||
|
||||
group.GET(p, func(c *Context) {
|
||||
original := c.Req.URL.Path
|
||||
c.Req.URL.Path = c.Params.ByName("filepath")
|
||||
fileServer.ServeHTTP(c.Writer, c.Req)
|
||||
c.Req.URL.Path = original
|
||||
})
|
||||
}
|
||||
|
||||
func (group *RouterGroup) combineHandlers(handlers []HandlerFunc) []HandlerFunc {
|
||||
s := len(group.Handlers) + len(handlers)
|
||||
h := make([]HandlerFunc, 0, s)
|
||||
|
|
Loading…
Reference in New Issue