1
0
Fork 0
forked from forgejo/forgejo

Refactor web route (#24080)

The old code is unnecessarily complex, and has many misuses.

Old code "wraps" a lot, wrap wrap wrap, it's difficult to understand
which kind of handler is used.

The new code uses a general approach, we do not need to write all kinds
of handlers into the "wrapper", do not need to wrap them again and
again.

New code, there are only 2 concepts:

1. HandlerProvider: `func (h any) (handlerProvider func (next)
http.Handler)`, it can be used as middleware
2. Use HandlerProvider to get the final HandlerFunc, and use it for
`r.Get()`


And we can decouple the route package from context package (see the
TODO).

# FAQ

## Is `reflect` safe?

Yes, all handlers are checked during startup, see the `preCheckHandler`
comment. If any handler is wrong, developers could know it in the first
time.

## Does `reflect` affect performance?

No. https://github.com/go-gitea/gitea/pull/24080#discussion_r1164825901

1. This reflect code only runs for each web handler call, handler is far
more slower: 10ms-50ms
2. The reflect is pretty fast (comparing to other code): 0.000265ms
3. XORM has more reflect operations already
This commit is contained in:
wxiaoguang 2023-04-21 02:49:06 +08:00 committed by GitHub
parent 70fc47a22a
commit b9a97ccd0e
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
10 changed files with 297 additions and 332 deletions

View file

@ -4,8 +4,6 @@
package web
import (
goctx "context"
"fmt"
"net/http"
"strings"
@ -17,13 +15,13 @@ import (
)
// Bind binding an obj to a handler
func Bind[T any](obj T) http.HandlerFunc {
return Wrap(func(ctx *context.Context) {
func Bind[T any](_ T) any {
return func(ctx *context.Context) {
theObj := new(T) // create a new form obj for every request but not use obj directly
binding.Bind(ctx.Req, theObj)
SetForm(ctx, theObj)
middleware.AssignForm(theObj, ctx.Data)
})
}
}
// SetForm set the form object
@ -56,21 +54,12 @@ func NewRoute() *Route {
// Use supports two middlewares
func (r *Route) Use(middlewares ...interface{}) {
if r.curGroupPrefix != "" {
// FIXME: this behavior is incorrect, should use "With" instead
r.curMiddlewares = append(r.curMiddlewares, middlewares...)
} else {
for _, middle := range middlewares {
switch t := middle.(type) {
case func(http.Handler) http.Handler:
r.R.Use(t)
case func(*context.Context):
r.R.Use(Middle(t))
case func(*context.Context) goctx.CancelFunc:
r.R.Use(MiddleCancel(t))
case func(*context.APIContext):
r.R.Use(MiddleAPI(t))
default:
panic(fmt.Sprintf("Unsupported middleware type: %#v", t))
}
// FIXME: another misuse, the "Use" with empty middlewares is called after "Mount"
for _, m := range middlewares {
r.R.Use(toHandlerProvider(m))
}
}
}
@ -99,6 +88,32 @@ func (r *Route) getPattern(pattern string) string {
return strings.TrimSuffix(newPattern, "/")
}
func (r *Route) wrapMiddlewareAndHandler(h []any) ([]func(http.Handler) http.Handler, http.HandlerFunc) {
handlerProviders := make([]func(http.Handler) http.Handler, 0, len(r.curMiddlewares)+len(h))
for _, m := range r.curMiddlewares {
handlerProviders = append(handlerProviders, toHandlerProvider(m))
}
for _, m := range h {
handlerProviders = append(handlerProviders, toHandlerProvider(m))
}
middlewares := handlerProviders[:len(handlerProviders)-1]
handlerFunc := handlerProviders[len(handlerProviders)-1](nil).ServeHTTP
return middlewares, handlerFunc
}
func (r *Route) Methods(method, pattern string, h []any) {
middlewares, handlerFunc := r.wrapMiddlewareAndHandler(h)
fullPattern := r.getPattern(pattern)
if strings.Contains(method, ",") {
methods := strings.Split(method, ",")
for _, method := range methods {
r.R.With(middlewares...).Method(strings.TrimSpace(method), fullPattern, handlerFunc)
}
} else {
r.R.With(middlewares...).Method(method, fullPattern, handlerFunc)
}
}
// Mount attaches another Route along ./pattern/*
func (r *Route) Mount(pattern string, subR *Route) {
middlewares := make([]interface{}, len(r.curMiddlewares))
@ -109,81 +124,53 @@ func (r *Route) Mount(pattern string, subR *Route) {
// Any delegate requests for all methods
func (r *Route) Any(pattern string, h ...interface{}) {
middlewares := r.getMiddlewares(h)
r.R.HandleFunc(r.getPattern(pattern), Wrap(middlewares...))
middlewares, handlerFunc := r.wrapMiddlewareAndHandler(h)
r.R.With(middlewares...).HandleFunc(r.getPattern(pattern), handlerFunc)
}
// Route delegate special methods
func (r *Route) Route(pattern, methods string, h ...interface{}) {
p := r.getPattern(pattern)
ms := strings.Split(methods, ",")
middlewares := r.getMiddlewares(h)
for _, method := range ms {
r.R.MethodFunc(strings.TrimSpace(method), p, Wrap(middlewares...))
}
// RouteMethods delegate special methods, it is an alias of "Methods", while the "pattern" is the first parameter
func (r *Route) RouteMethods(pattern, methods string, h ...interface{}) {
r.Methods(methods, pattern, h)
}
// Delete delegate delete method
func (r *Route) Delete(pattern string, h ...interface{}) {
middlewares := r.getMiddlewares(h)
r.R.Delete(r.getPattern(pattern), Wrap(middlewares...))
}
func (r *Route) getMiddlewares(h []interface{}) []interface{} {
middlewares := make([]interface{}, len(r.curMiddlewares), len(r.curMiddlewares)+len(h))
copy(middlewares, r.curMiddlewares)
middlewares = append(middlewares, h...)
return middlewares
r.Methods("DELETE", pattern, h)
}
// Get delegate get method
func (r *Route) Get(pattern string, h ...interface{}) {
middlewares := r.getMiddlewares(h)
r.R.Get(r.getPattern(pattern), Wrap(middlewares...))
}
// Options delegate options method
func (r *Route) Options(pattern string, h ...interface{}) {
middlewares := r.getMiddlewares(h)
r.R.Options(r.getPattern(pattern), Wrap(middlewares...))
r.Methods("GET", pattern, h)
}
// GetOptions delegate get and options method
func (r *Route) GetOptions(pattern string, h ...interface{}) {
middlewares := r.getMiddlewares(h)
r.R.Get(r.getPattern(pattern), Wrap(middlewares...))
r.R.Options(r.getPattern(pattern), Wrap(middlewares...))
r.Methods("GET,OPTIONS", pattern, h)
}
// PostOptions delegate post and options method
func (r *Route) PostOptions(pattern string, h ...interface{}) {
middlewares := r.getMiddlewares(h)
r.R.Post(r.getPattern(pattern), Wrap(middlewares...))
r.R.Options(r.getPattern(pattern), Wrap(middlewares...))
r.Methods("POST,OPTIONS", pattern, h)
}
// Head delegate head method
func (r *Route) Head(pattern string, h ...interface{}) {
middlewares := r.getMiddlewares(h)
r.R.Head(r.getPattern(pattern), Wrap(middlewares...))
r.Methods("HEAD", pattern, h)
}
// Post delegate post method
func (r *Route) Post(pattern string, h ...interface{}) {
middlewares := r.getMiddlewares(h)
r.R.Post(r.getPattern(pattern), Wrap(middlewares...))
r.Methods("POST", pattern, h)
}
// Put delegate put method
func (r *Route) Put(pattern string, h ...interface{}) {
middlewares := r.getMiddlewares(h)
r.R.Put(r.getPattern(pattern), Wrap(middlewares...))
r.Methods("PUT", pattern, h)
}
// Patch delegate patch method
func (r *Route) Patch(pattern string, h ...interface{}) {
middlewares := r.getMiddlewares(h)
r.R.Patch(r.getPattern(pattern), Wrap(middlewares...))
r.Methods("PATCH", pattern, h)
}
// ServeHTTP implements http.Handler
@ -191,19 +178,12 @@ func (r *Route) ServeHTTP(w http.ResponseWriter, req *http.Request) {
r.R.ServeHTTP(w, req)
}
// NotFound defines a handler to respond whenever a route could
// not be found.
// NotFound defines a handler to respond whenever a route could not be found.
func (r *Route) NotFound(h http.HandlerFunc) {
r.R.NotFound(h)
}
// MethodNotAllowed defines a handler to respond whenever a method is
// not allowed.
func (r *Route) MethodNotAllowed(h http.HandlerFunc) {
r.R.MethodNotAllowed(h)
}
// Combo deletegate requests to Combo
// Combo delegates requests to Combo
func (r *Route) Combo(pattern string, h ...interface{}) *Combo {
return &Combo{r, pattern, h}
}
@ -215,31 +195,31 @@ type Combo struct {
h []interface{}
}
// Get deletegate Get method
// Get delegates Get method
func (c *Combo) Get(h ...interface{}) *Combo {
c.r.Get(c.pattern, append(c.h, h...)...)
return c
}
// Post deletegate Post method
// Post delegates Post method
func (c *Combo) Post(h ...interface{}) *Combo {
c.r.Post(c.pattern, append(c.h, h...)...)
return c
}
// Delete deletegate Delete method
// Delete delegates Delete method
func (c *Combo) Delete(h ...interface{}) *Combo {
c.r.Delete(c.pattern, append(c.h, h...)...)
return c
}
// Put deletegate Put method
// Put delegates Put method
func (c *Combo) Put(h ...interface{}) *Combo {
c.r.Put(c.pattern, append(c.h, h...)...)
return c
}
// Patch deletegate Patch method
// Patch delegates Patch method
func (c *Combo) Patch(h ...interface{}) *Combo {
c.r.Patch(c.pattern, append(c.h, h...)...)
return c