Skip to content
This repository has been archived by the owner on Dec 23, 2023. It is now read-only.

Commit

Permalink
Move contextPool out from router
Browse files Browse the repository at this point in the history
  • Loading branch information
razonyang committed Apr 5, 2020
1 parent 80a4248 commit 09c6c71
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 18 deletions.
16 changes: 16 additions & 0 deletions context.go
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,22 @@ func putBuffer(buf *bytes.Buffer) {
bufPool.Put(buf)
}

var contextPool = sync.Pool{
New: func() interface{} {
return &Context{}
},
}

func getContext() *Context {
ctx := contextPool.Get().(*Context)
ctx.reset()
return ctx
}

func putContext(ctx *Context) {
contextPool.Put(ctx)
}

// Context contains incoming request, route, params and manages outgoing response.
type Context struct {
router *Router
Expand Down
20 changes: 2 additions & 18 deletions router.go
Original file line number Diff line number Diff line change
Expand Up @@ -52,8 +52,6 @@ type Router struct {
// Named routes.
routes map[string]*Route

contextPool sync.Pool

paramsPool sync.Pool
maxParams uint16

Expand Down Expand Up @@ -132,15 +130,6 @@ func NewRouter() *Router {
HandleOPTIONS: true,
}
}
func (r *Router) getContext() *Context {
ctx := r.contextPool.Get().(*Context)
ctx.reset()
return ctx
}

func (r *Router) putContext(ctx *Context) {
r.contextPool.Put(ctx)
}

func (r *Router) getParams() *Params {
ps := r.paramsPool.Get().(*Params)
Expand Down Expand Up @@ -255,11 +244,6 @@ func (r *Router) Handle(method, path string, handle Handle, opts ...RouteOption)
return &ps
}
}
if r.contextPool.New == nil {
r.contextPool.New = func() interface{} {
return &Context{}
}
}
}

// Handler implements IRouter.Handler.
Expand Down Expand Up @@ -367,11 +351,11 @@ func (r *Router) allowed(path, reqMethod string) (allow string) {

// ServeHTTP makes the router implement the http.Handler interface.
func (r *Router) ServeHTTP(w http.ResponseWriter, req *http.Request) {
ctx := r.getContext()
ctx := getContext()
ctx.router = r
ctx.Request = req
ctx.Response = w
defer r.putContext(ctx)
defer putContext(ctx)

var err error
if r.handle != nil {
Expand Down

0 comments on commit 09c6c71

Please sign in to comment.