binder.go 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. package binder
  2. import (
  3. "errors"
  4. "sync"
  5. )
  6. // Binder errors
  7. var (
  8. ErrSuitableContentNotFound = errors.New("binder: suitable content not found to parse body")
  9. ErrMapNotConvertible = errors.New("binder: map is not convertible to map[string]string or map[string][]string")
  10. ErrMapNilDestination = errors.New("binder: map destination is nil and cannot be initialized")
  11. ErrInvalidDestinationValue = errors.New("binder: invalid destination value")
  12. ErrUnmatchedBrackets = errors.New("unmatched brackets")
  13. )
  14. var errPoolTypeAssertion = errors.New("failed to type-assert to T")
  15. var HeaderBinderPool = sync.Pool{
  16. New: func() any {
  17. return &HeaderBinding{}
  18. },
  19. }
  20. var RespHeaderBinderPool = sync.Pool{
  21. New: func() any {
  22. return &RespHeaderBinding{}
  23. },
  24. }
  25. var CookieBinderPool = sync.Pool{
  26. New: func() any {
  27. return &CookieBinding{}
  28. },
  29. }
  30. var QueryBinderPool = sync.Pool{
  31. New: func() any {
  32. return &QueryBinding{}
  33. },
  34. }
  35. var FormBinderPool = sync.Pool{
  36. New: func() any {
  37. return &FormBinding{}
  38. },
  39. }
  40. var URIBinderPool = sync.Pool{
  41. New: func() any {
  42. return &URIBinding{}
  43. },
  44. }
  45. var XMLBinderPool = sync.Pool{
  46. New: func() any {
  47. return &XMLBinding{}
  48. },
  49. }
  50. var JSONBinderPool = sync.Pool{
  51. New: func() any {
  52. return &JSONBinding{}
  53. },
  54. }
  55. var CBORBinderPool = sync.Pool{
  56. New: func() any {
  57. return &CBORBinding{}
  58. },
  59. }
  60. var MsgPackBinderPool = sync.Pool{
  61. New: func() any {
  62. return &MsgPackBinding{}
  63. },
  64. }
  65. // GetFromThePool retrieves a binder from the provided sync.Pool and panics if
  66. // the stored value cannot be cast to the requested type.
  67. func GetFromThePool[T any](pool *sync.Pool) T {
  68. binder, ok := pool.Get().(T)
  69. if !ok {
  70. panic(errPoolTypeAssertion)
  71. }
  72. return binder
  73. }
  74. // PutToThePool returns the binder to the provided sync.Pool.
  75. func PutToThePool[T any](pool *sync.Pool, binder T) {
  76. pool.Put(binder)
  77. }