mirror of
https://github.com/yusing/godoxy.git
synced 2026-04-21 08:21:51 +02:00
refactor(http): performance improvement
- Introduced a sync.Pool for ResponseRecorder to optimize memory usage. - Updated ServeHTTP method to utilize the new GetResponseRecorder and PutResponseRecorder functions. - Adjusted NewResponseRecorder to leverage the pooling mechanism.
This commit is contained in:
@@ -97,9 +97,12 @@ func (ep *Entrypoint) FindRoute(s string) types.HTTPRoute {
|
|||||||
|
|
||||||
func (ep *Entrypoint) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
func (ep *Entrypoint) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||||
if ep.accessLogger != nil {
|
if ep.accessLogger != nil {
|
||||||
rec := accesslog.NewResponseRecorder(w)
|
rec := accesslog.GetResponseRecorder(w)
|
||||||
w = rec
|
w = rec
|
||||||
defer ep.accessLogger.Log(r, rec.Response())
|
defer func() {
|
||||||
|
ep.accessLogger.Log(r, rec.Response())
|
||||||
|
accesslog.PutResponseRecorder(rec)
|
||||||
|
}()
|
||||||
}
|
}
|
||||||
|
|
||||||
route := ep.findRouteFunc(r.Host)
|
route := ep.findRouteFunc(r.Host)
|
||||||
|
|||||||
@@ -5,6 +5,7 @@ import (
|
|||||||
"fmt"
|
"fmt"
|
||||||
"net"
|
"net"
|
||||||
"net/http"
|
"net/http"
|
||||||
|
"sync"
|
||||||
)
|
)
|
||||||
|
|
||||||
type ResponseRecorder struct {
|
type ResponseRecorder struct {
|
||||||
@@ -13,14 +14,30 @@ type ResponseRecorder struct {
|
|||||||
resp http.Response
|
resp http.Response
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewResponseRecorder(w http.ResponseWriter) *ResponseRecorder {
|
var recorderPool = sync.Pool{
|
||||||
return &ResponseRecorder{
|
New: func() any {
|
||||||
w: w,
|
return &ResponseRecorder{}
|
||||||
resp: http.Response{
|
},
|
||||||
StatusCode: http.StatusOK,
|
}
|
||||||
Header: w.Header(),
|
|
||||||
},
|
func GetResponseRecorder(w http.ResponseWriter) *ResponseRecorder {
|
||||||
|
r := recorderPool.Get().(*ResponseRecorder)
|
||||||
|
r.w = w
|
||||||
|
r.resp = http.Response{
|
||||||
|
StatusCode: http.StatusOK,
|
||||||
|
Header: w.Header(),
|
||||||
}
|
}
|
||||||
|
return r
|
||||||
|
}
|
||||||
|
|
||||||
|
func PutResponseRecorder(r *ResponseRecorder) {
|
||||||
|
r.w = nil
|
||||||
|
r.resp = http.Response{}
|
||||||
|
recorderPool.Put(r)
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewResponseRecorder(w http.ResponseWriter) *ResponseRecorder {
|
||||||
|
return GetResponseRecorder(w)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (w *ResponseRecorder) Unwrap() http.ResponseWriter {
|
func (w *ResponseRecorder) Unwrap() http.ResponseWriter {
|
||||||
|
|||||||
Reference in New Issue
Block a user