Skip to content

Commit 177845d

Browse files
committed
refactor, make code more readable
1 parent 4299c3b commit 177845d

File tree

9 files changed

+269
-313
lines changed

9 files changed

+269
-313
lines changed

modules/web/handler.go

Lines changed: 201 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,201 @@
1+
// Copyright 2023 The Gitea Authors. All rights reserved.
2+
// SPDX-License-Identifier: MIT
3+
4+
package web
5+
6+
import (
7+
goctx "context"
8+
"fmt"
9+
"net/http"
10+
"reflect"
11+
"strings"
12+
13+
"code.gitea.io/gitea/modules/context"
14+
"code.gitea.io/gitea/modules/web/routing"
15+
)
16+
17+
// ResponseStatusProvider is an interface to check whether the response has been written by the handler
18+
type ResponseStatusProvider interface {
19+
Written() bool
20+
}
21+
22+
// TODO: decouple this from the context package, let the context package register these providers
23+
var argTypeProvider = map[reflect.Type]func(req *http.Request) ResponseStatusProvider{
24+
reflect.TypeOf(&context.APIContext{}): func(req *http.Request) ResponseStatusProvider { return context.GetAPIContext(req) },
25+
reflect.TypeOf(&context.Context{}): func(req *http.Request) ResponseStatusProvider { return context.GetContext(req) },
26+
reflect.TypeOf(&context.PrivateContext{}): func(req *http.Request) ResponseStatusProvider { return context.GetPrivateContext(req) },
27+
}
28+
29+
// responseWriter is a wrapper of http.ResponseWriter, to check whether the response has been written
30+
type responseWriter struct {
31+
respWriter http.ResponseWriter
32+
status int
33+
}
34+
35+
var _ ResponseStatusProvider = (*responseWriter)(nil)
36+
37+
func (r *responseWriter) Written() bool {
38+
return r.status > 0
39+
}
40+
41+
func (r *responseWriter) Header() http.Header {
42+
return r.respWriter.Header()
43+
}
44+
45+
func (r *responseWriter) Write(bytes []byte) (int, error) {
46+
if r.status == 0 {
47+
r.status = http.StatusOK
48+
}
49+
return r.respWriter.Write(bytes)
50+
}
51+
52+
func (r *responseWriter) WriteHeader(statusCode int) {
53+
r.status = statusCode
54+
r.respWriter.WriteHeader(statusCode)
55+
}
56+
57+
var (
58+
httpReqType = reflect.TypeOf((*http.Request)(nil))
59+
respWriterType = reflect.TypeOf((*http.ResponseWriter)(nil)).Elem()
60+
cancelFuncType = reflect.TypeOf((*goctx.CancelFunc)(nil)).Elem()
61+
)
62+
63+
// preCheckHandler checks whether the handler is valid, developers could get first-time feedback, all mistakes could be found at startup
64+
func preCheckHandler(fn reflect.Value, argsIn []reflect.Value) {
65+
hasStatusProvider := false
66+
for _, argIn := range argsIn {
67+
if _, hasStatusProvider = argIn.Interface().(ResponseStatusProvider); hasStatusProvider {
68+
break
69+
}
70+
}
71+
if !hasStatusProvider {
72+
panic(fmt.Sprintf("handler should have at least one ResponseStatusProvider argument, but got %s", fn.Type()))
73+
}
74+
if fn.Type().NumOut() != 0 && fn.Type().NumIn() != 1 {
75+
panic(fmt.Sprintf("handler should have no return value or only one argument, but got %s", fn.Type()))
76+
}
77+
if fn.Type().NumOut() == 1 && fn.Type().Out(0) != cancelFuncType {
78+
panic(fmt.Sprintf("handler should return a cancel function, but got %s", fn.Type()))
79+
}
80+
}
81+
82+
func prepareHandleArgsIn(resp http.ResponseWriter, req *http.Request, fn reflect.Value) []reflect.Value {
83+
isPreCheck := req == nil
84+
85+
argsIn := make([]reflect.Value, fn.Type().NumIn())
86+
for i := 0; i < fn.Type().NumIn(); i++ {
87+
argTyp := fn.Type().In(i)
88+
switch argTyp {
89+
case respWriterType:
90+
argsIn[i] = reflect.ValueOf(resp)
91+
case httpReqType:
92+
argsIn[i] = reflect.ValueOf(req)
93+
default:
94+
if argFn, ok := argTypeProvider[argTyp]; ok {
95+
if isPreCheck {
96+
argsIn[i] = reflect.ValueOf(&responseWriter{})
97+
} else {
98+
argsIn[i] = reflect.ValueOf(argFn(req))
99+
}
100+
} else {
101+
panic(fmt.Sprintf("unsupported argument type: %s", argTyp))
102+
}
103+
}
104+
}
105+
return argsIn
106+
}
107+
108+
func handleResponse(fn reflect.Value, ret []reflect.Value) goctx.CancelFunc {
109+
if len(ret) == 1 {
110+
if cancelFunc, ok := ret[0].Interface().(goctx.CancelFunc); ok {
111+
return cancelFunc
112+
}
113+
panic(fmt.Sprintf("unsupported return type: %s", ret[0].Type()))
114+
} else if len(ret) > 1 {
115+
panic(fmt.Sprintf("unsupported return values: %s", fn.Type()))
116+
}
117+
return nil
118+
}
119+
120+
func hasResponseBeenWritten(argsIn []reflect.Value) bool {
121+
written := false
122+
for _, argIn := range argsIn {
123+
if statusProvider, ok := argIn.Interface().(ResponseStatusProvider); ok {
124+
if written = statusProvider.Written(); written {
125+
break
126+
}
127+
}
128+
}
129+
return written
130+
}
131+
132+
// toHandlerProvider converts a handler to a handler provider
133+
// A handler provider is a function that takes a "next" http.Handler, it can be used as a middleware
134+
func toHandlerProvider(handler any) func(next http.Handler) http.Handler {
135+
if hp, ok := handler.(func(next http.Handler) http.Handler); ok {
136+
return hp
137+
}
138+
139+
funcInfo := routing.GetFuncInfo(handler)
140+
fn := reflect.ValueOf(handler)
141+
if fn.Type().Kind() != reflect.Func {
142+
panic(fmt.Sprintf("handler must be a function, but got %s", fn.Type()))
143+
}
144+
145+
provider := func(next http.Handler) http.Handler {
146+
return http.HandlerFunc(func(respOrig http.ResponseWriter, req *http.Request) {
147+
// wrap the response writer to check whether the response has been written
148+
resp := respOrig
149+
if _, ok := resp.(ResponseStatusProvider); !ok {
150+
resp = &responseWriter{respWriter: resp}
151+
}
152+
153+
// prepare the arguments for the handler and do pre-check
154+
argsIn := prepareHandleArgsIn(resp, req, fn)
155+
if req == nil {
156+
preCheckHandler(fn, argsIn)
157+
return // it's doing pre-check, just return
158+
}
159+
160+
routing.UpdateFuncInfo(req.Context(), funcInfo)
161+
ret := fn.Call(argsIn)
162+
163+
// handle the return value, and defer the cancel function if there is one
164+
cancelFunc := handleResponse(fn, ret)
165+
if cancelFunc != nil {
166+
defer cancelFunc()
167+
}
168+
169+
// if the response has not been written, call the next handler
170+
if next != nil && !hasResponseBeenWritten(argsIn) {
171+
next.ServeHTTP(resp, req)
172+
}
173+
})
174+
}
175+
176+
provider(nil).ServeHTTP(nil, nil) // do a pre-check to make sure all arguments and return values are supported
177+
return provider
178+
}
179+
180+
// MiddlewareWithPrefix wraps a handler function at a prefix, and make it as a middleware
181+
// TODO: this design is incorrect, the asset handler should not be a middleware
182+
func MiddlewareWithPrefix(pathPrefix string, middleware func(handler http.Handler) http.Handler, handlerFunc http.HandlerFunc) func(next http.Handler) http.Handler {
183+
funcInfo := routing.GetFuncInfo(handlerFunc)
184+
handler := http.HandlerFunc(func(resp http.ResponseWriter, req *http.Request) {
185+
routing.UpdateFuncInfo(req.Context(), funcInfo)
186+
handlerFunc(resp, req)
187+
})
188+
return func(next http.Handler) http.Handler {
189+
return http.HandlerFunc(func(resp http.ResponseWriter, req *http.Request) {
190+
if !strings.HasPrefix(req.URL.Path, pathPrefix) {
191+
next.ServeHTTP(resp, req)
192+
return
193+
}
194+
if middleware != nil {
195+
middleware(handler).ServeHTTP(resp, req)
196+
} else {
197+
handler.ServeHTTP(resp, req)
198+
}
199+
})
200+
}
201+
}

0 commit comments

Comments
 (0)