- Add Static(prefix, root) to serve files from disk on Kite and Group - Add StaticFS(prefix, fs) to serve from any http.FileSystem on Kite and Group - Add SPA(root) and SPAFS(fs) for Single Page Application serving — falls back to index.html for unknown paths so client-side routing works correctly
73 lines
1.8 KiB
Go
73 lines
1.8 KiB
Go
package kite
|
|
|
|
import "net/http"
|
|
|
|
type Group struct {
|
|
k *Kite
|
|
prefix string
|
|
mws []Middleware
|
|
}
|
|
|
|
func (g *Group) Static(prefix, root string) {
|
|
g.StaticFS(prefix, http.Dir(root))
|
|
}
|
|
|
|
func (g *Group) StaticFS(prefix string, fs http.FileSystem) {
|
|
if prefix == "" || prefix[len(prefix)-1] != '/' {
|
|
prefix += "/"
|
|
}
|
|
fullPrefix := g.prefix + prefix
|
|
|
|
handler := http.StripPrefix(fullPrefix, http.FileServer(fs))
|
|
g.k.r.Handler(http.MethodGet, fullPrefix+"*filepath", handler)
|
|
g.k.r.Handler(http.MethodHead, fullPrefix+"*filepath", handler)
|
|
}
|
|
|
|
func (g *Group) Group(prefix string, mws ...Middleware) *Group {
|
|
return &Group{
|
|
k: g.k,
|
|
prefix: g.prefix + prefix,
|
|
mws: append(append([]Middleware{}, g.mws...), mws...),
|
|
}
|
|
}
|
|
|
|
func (g *Group) Use(mws ...Middleware) {
|
|
g.mws = append(g.mws, mws...)
|
|
}
|
|
|
|
func (g *Group) CONNECT(path string, h Handler, mws ...Middleware) {
|
|
g.handle(http.MethodConnect, path, h, mws...)
|
|
}
|
|
|
|
func (g *Group) DELETE(path string, h Handler, mws ...Middleware) {
|
|
g.handle(http.MethodDelete, path, h, mws...)
|
|
}
|
|
|
|
func (g *Group) GET(path string, h Handler, mws ...Middleware) {
|
|
g.handle(http.MethodGet, path, h, mws...)
|
|
}
|
|
|
|
func (g *Group) HEAD(path string, h Handler, mws ...Middleware) {
|
|
g.handle(http.MethodHead, path, h, mws...)
|
|
}
|
|
|
|
func (g *Group) OPTIONS(path string, h Handler, mws ...Middleware) {
|
|
g.handle(http.MethodOptions, path, h, mws...)
|
|
}
|
|
|
|
func (g *Group) POST(path string, h Handler, mws ...Middleware) {
|
|
g.handle(http.MethodPost, path, h, mws...)
|
|
}
|
|
|
|
func (g *Group) PUT(path string, h Handler, mws ...Middleware) {
|
|
g.handle(http.MethodPut, path, h, mws...)
|
|
}
|
|
|
|
func (g *Group) TRACE(path string, h Handler, mws ...Middleware) {
|
|
g.handle(http.MethodTrace, path, h, mws...)
|
|
}
|
|
|
|
func (g *Group) handle(method, path string, h Handler, mws ...Middleware) {
|
|
g.k.handle(method, g.prefix+path, h, append(g.mws, mws...)...)
|
|
}
|