- Run global middleware for all requests, including OPTIONS preflights, NotFound, and MethodNotAllowed — previously bypassed by httprouter's internal handling - Implement Hijacker, Flusher, and Pusher on the response writer for WebSocket, SSE, and HTTP/2 push support - Fix CORS: echo a single matching origin, handle AllowCredentials with wildcard, append Vary: Origin - Logger logs from a defer to capture correct status on panicked requests - Static and StaticFS accept route middleware; add Context.AddHeader; warn on NotFound handler override
83 lines
2.1 KiB
Go
83 lines
2.1 KiB
Go
package kite
|
|
|
|
import "net/http"
|
|
|
|
type Group struct {
|
|
k *Kite
|
|
prefix string
|
|
mws []Middleware
|
|
}
|
|
|
|
func (g *Group) Static(prefix, root string, mws ...Middleware) {
|
|
g.StaticFS(prefix, http.Dir(root), mws...)
|
|
}
|
|
|
|
func (g *Group) StaticFS(prefix string, fs http.FileSystem, mws ...Middleware) {
|
|
if prefix == "" || prefix[len(prefix)-1] != '/' {
|
|
prefix += "/"
|
|
}
|
|
fullPrefix := g.prefix + prefix
|
|
|
|
handler := http.StripPrefix(fullPrefix, http.FileServer(fs))
|
|
|
|
h := func(ctx *Context) error {
|
|
handler.ServeHTTP(ctx.w, ctx.r)
|
|
return nil
|
|
}
|
|
|
|
g.k.handle(http.MethodGet, fullPrefix+"*filepath", h, mws...)
|
|
g.k.handle(http.MethodHead, fullPrefix+"*filepath", h, mws...)
|
|
}
|
|
|
|
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) {
|
|
combined := make([]Middleware, 0, len(g.mws)+len(mws))
|
|
combined = append(combined, g.mws...)
|
|
combined = append(combined, mws...)
|
|
|
|
g.k.handle(method, g.prefix+path, h, combined...)
|
|
}
|