mirror of
https://github.com/yusing/godoxy.git
synced 2026-01-11 22:30:47 +01: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) {
|
||||
if ep.accessLogger != nil {
|
||||
rec := accesslog.NewResponseRecorder(w)
|
||||
rec := accesslog.GetResponseRecorder(w)
|
||||
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)
|
||||
|
||||
@@ -5,6 +5,7 @@ import (
|
||||
"fmt"
|
||||
"net"
|
||||
"net/http"
|
||||
"sync"
|
||||
)
|
||||
|
||||
type ResponseRecorder struct {
|
||||
@@ -13,14 +14,30 @@ type ResponseRecorder struct {
|
||||
resp http.Response
|
||||
}
|
||||
|
||||
func NewResponseRecorder(w http.ResponseWriter) *ResponseRecorder {
|
||||
return &ResponseRecorder{
|
||||
w: w,
|
||||
resp: http.Response{
|
||||
StatusCode: http.StatusOK,
|
||||
Header: w.Header(),
|
||||
},
|
||||
var recorderPool = sync.Pool{
|
||||
New: func() any {
|
||||
return &ResponseRecorder{}
|
||||
},
|
||||
}
|
||||
|
||||
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 {
|
||||
|
||||
Reference in New Issue
Block a user