gohttp/server/directive.go

93 lines
2.6 KiB
Go

package server
import (
"context"
"fmt"
"net/http"
"strings"
// "compress/gzip"
"module git.kingecg.top/kingecg/gohttpd/model"
"git.kingecg.top/kingecg/gologger"
"github.com/nanmu42/gzip"
)
type Directive func(args ...string) Middleware
var Add_Header Directive = func(args ...string) Middleware {
return func(w http.ResponseWriter, r *http.Request, next http.Handler) {
l := gologger.GetLogger("Directive")
p := args[1:]
params := strings.Join(p, " ")
l.Debug(fmt.Sprintf("Add-Header %s:%s", args[0], params))
w.Header().Add(args[0], args[1])
next.ServeHTTP(w, r)
}
}
var Set_Header Directive = func(args ...string) Middleware {
return func(w http.ResponseWriter, r *http.Request, next http.Handler) {
l := gologger.GetLogger("Directive")
p := args[1:]
params := strings.Join(p, " ")
l.Debug(fmt.Sprintf("Set-Header %s:%s", args[0], params))
w.Header().Set(args[0], params)
next.ServeHTTP(w, r)
}
}
var Gzip_Response Directive = func(args ...string) Middleware {
var gzipHandler http.Handler = nil
return func(w http.ResponseWriter, r *http.Request, next http.Handler) {
l := gologger.GetLogger("Directive")
l.Debug("Gzip-Response")
if gzipHandler == nil {
gzipHandler = gzip.DefaultHandler().WrapHandler(next)
}
gzipHandler.ServeHTTP(w, r)
}
}
var DRecordAccess Directive = func(args ...string) Middleware {
serverName := args[0]
return func(w http.ResponseWriter, r *http.Request, next http.Handler) {
l := gologger.GetLogger("Directive")
l.Debug("Record-Access")
model.Incr(r.URL.Host)
// put serverName to request context
ctx := r.Context()
ctx = context.WithValue(ctx, RequestCtxKey("serverName"), serverName)
r = r.WithContext(ctx)
next.ServeHTTP(w, r)
}
}
var JWTDirective Directive = func(args ...string) Middleware {
return JwtAuth
}
var BasicAuthDirective Directive = func(args ...string) Middleware {
return BasicAuth
}
var RedirectDirective Directive = func(args ...string) Middleware {
return func(w http.ResponseWriter, r *http.Request, next http.Handler) {
l := gologger.GetLogger("Directive")
l.Debug("Redirect")
if len(args) < 1 {
http.Error(w, "Redirect directive requires a URL", http.StatusBadRequest)
return
}
targetURL := args[0] + r.URL.Path
http.Redirect(w, r, targetURL, http.StatusFound)
}
}
// 在DirectiveMap中注册新指令
var DirectiveMap = map[string]Directive{
"Set-Header": Set_Header,
"Add-Header": Add_Header,
"Gzip-Response": Gzip_Response,
"Record-Access": DRecordAccess,
"Jwt-Auth": JWTDirective,
"Basic-Auth": BasicAuthDirective,
"Redirect": RedirectDirective,
}