pool.go 1.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  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. if !ctx.manualRelease {
  25. ctx.EndRequest()
  26. c.pool.Put(ctx)
  27. }
  28. }
  29. // ReleaseLight will just release the object back to the pool, but the
  30. // clean method is caller's responsibility now, currently this is only used
  31. // on `SPABuilder` and `websocket.Handler`.
  32. //
  33. // ReleaseLight does a force-put, it does NOT respect the context.DisablePoolRelease.
  34. func (c *Pool) ReleaseLight(ctx *Context) {
  35. c.pool.Put(ctx)
  36. }