pool.go 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  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. //
  8. // It's the only one real implementation inside this package because it used widely.
  9. type Pool struct {
  10. pool *sync.Pool
  11. newFunc func() Context // we need a field otherwise is not working if we change the return value
  12. }
  13. // New creates and returns a new context pool.
  14. func New(newFunc func() Context) *Pool {
  15. c := &Pool{pool: &sync.Pool{}, newFunc: newFunc}
  16. c.pool.New = func() interface{} { return c.newFunc() }
  17. return c
  18. }
  19. // Attach changes the pool's return value Context.
  20. //
  21. // The new Context should explicitly define the `Next()`
  22. // and `Do(context.Handlers)` functions.
  23. //
  24. // Example: https://github.com/kataras/iris/blob/master/_examples/routing/custom-context/method-overriding/main.go
  25. func (c *Pool) Attach(newFunc func() Context) {
  26. c.newFunc = newFunc
  27. }
  28. // Acquire returns a Context from pool.
  29. // See Release.
  30. func (c *Pool) Acquire(w http.ResponseWriter, r *http.Request) Context {
  31. ctx := c.pool.Get().(Context)
  32. ctx.BeginRequest(w, r)
  33. return ctx
  34. }
  35. // Release puts a Context back to its pull, this function releases its resources.
  36. // See Acquire.
  37. func (c *Pool) Release(ctx Context) {
  38. ctx.EndRequest()
  39. c.pool.Put(ctx)
  40. }
  41. // ReleaseLight will just release the object back to the pool, but the
  42. // clean method is caller's responsibility now, currently this is only used
  43. // on `SPABuilder`.
  44. func (c *Pool) ReleaseLight(ctx Context) {
  45. c.pool.Put(ctx)
  46. }