support cors in rest server

This commit is contained in:
kevin
2020-10-21 14:10:29 +08:00
parent 1c1e4bca86
commit fe0d0687f5
8 changed files with 122 additions and 8 deletions

View File

@@ -22,8 +22,9 @@ var (
)
type patRouter struct {
trees map[string]*search.Tree
notFound http.Handler
trees map[string]*search.Tree
notFound http.Handler
notAllowed http.Handler
}
func NewRouter() httpx.Router {
@@ -63,11 +64,17 @@ func (pr *patRouter) ServeHTTP(w http.ResponseWriter, r *http.Request) {
}
}
if allow, ok := pr.methodNotAllowed(r.Method, reqPath); ok {
allow, ok := pr.methodNotAllowed(r.Method, reqPath)
if !ok {
pr.handleNotFound(w, r)
return
}
if pr.notAllowed != nil {
pr.notAllowed.ServeHTTP(w, r)
} else {
w.Header().Set(allowHeader, allow)
w.WriteHeader(http.StatusMethodNotAllowed)
} else {
pr.handleNotFound(w, r)
}
}
@@ -75,6 +82,10 @@ func (pr *patRouter) SetNotFoundHandler(handler http.Handler) {
pr.notFound = handler
}
func (pr *patRouter) SetNotAllowedHandler(handler http.Handler) {
pr.notAllowed = handler
}
func (pr *patRouter) handleNotFound(w http.ResponseWriter, r *http.Request) {
if pr.notFound != nil {
pr.notFound.ServeHTTP(w, r)