forked from mirror/gin
Adds StaticFile()
This commit is contained in:
parent
66251d1741
commit
72f200ac56
|
@ -7,6 +7,7 @@ package gin
|
||||||
import (
|
import (
|
||||||
"net/http"
|
"net/http"
|
||||||
"path"
|
"path"
|
||||||
|
"strings"
|
||||||
)
|
)
|
||||||
|
|
||||||
// Used internally to configure router, a RouterGroup is associated with a prefix
|
// Used internally to configure router, a RouterGroup is associated with a prefix
|
||||||
|
@ -100,6 +101,17 @@ func (group *RouterGroup) Any(relativePath string, handlers ...HandlerFunc) {
|
||||||
group.handle("TRACE", relativePath, handlers)
|
group.handle("TRACE", relativePath, handlers)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (group *RouterGroup) StaticFile(relativePath, filepath string) {
|
||||||
|
if strings.Contains(relativePath, ":") || strings.Contains(relativePath, "*") {
|
||||||
|
panic("URL parameters can not be used when serving a static file")
|
||||||
|
}
|
||||||
|
handler := func(c *Context) {
|
||||||
|
c.File(filepath)
|
||||||
|
}
|
||||||
|
group.GET(relativePath, handler)
|
||||||
|
group.HEAD(relativePath, handler)
|
||||||
|
}
|
||||||
|
|
||||||
// Static serves files from the given file system root.
|
// Static serves files from the given file system root.
|
||||||
// Internally a http.FileServer is used, therefore http.NotFound is used instead
|
// Internally a http.FileServer is used, therefore http.NotFound is used instead
|
||||||
// of the Router's NotFound handler.
|
// of the Router's NotFound handler.
|
||||||
|
|
|
@ -87,3 +87,14 @@ func performRequestInGroup(t *testing.T, method string) {
|
||||||
assert.Equal(t, w.Code, 400)
|
assert.Equal(t, w.Code, 400)
|
||||||
assert.Equal(t, w.Body.String(), "the method was "+method+" and index 1")
|
assert.Equal(t, w.Body.String(), "the method was "+method+" and index 1")
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestRouterGroupInvalidStaticFile(t *testing.T) {
|
||||||
|
router := New()
|
||||||
|
assert.Panics(t, func() {
|
||||||
|
router.StaticFile("/path/:param", "favicon.ico")
|
||||||
|
})
|
||||||
|
|
||||||
|
assert.Panics(t, func() {
|
||||||
|
router.StaticFile("/path/*param", "favicon.ico")
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
Loading…
Reference in New Issue