pool.go 917 B

1234567891011121314151617181920212223242526272829303132333435363738
  1. package context
  2. import (
  3. "net/http"
  4. "sync"
  5. )
  6. // Pool is the context pool, it's used inside router and the framework by itself.
  7. type Pool struct {
  8. pool *sync.Pool
  9. }
  10. // New creates and returns a new context pool.
  11. func New(newFunc func() interface{}) *Pool {
  12. return &Pool{pool: &sync.Pool{New: newFunc}}
  13. }
  14. // Acquire returns a Context from pool.
  15. // See Release.
  16. func (c *Pool) Acquire(w http.ResponseWriter, r *http.Request) *Context {
  17. ctx := c.pool.Get().(*Context)
  18. ctx.BeginRequest(w, r)
  19. return ctx
  20. }
  21. // Release puts a Context back to its pull, this function releases its resources.
  22. // See Acquire.
  23. func (c *Pool) Release(ctx *Context) {
  24. ctx.EndRequest()
  25. c.pool.Put(ctx)
  26. }
  27. // ReleaseLight will just release the object back to the pool, but the
  28. // clean method is caller's responsibility now, currently this is only used
  29. // on `SPABuilder`.
  30. func (c *Pool) ReleaseLight(ctx *Context) {
  31. c.pool.Put(ctx)
  32. }