request.go 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. package request
  2. import (
  3. "git.sxidc.com/go-tools/api_binding/http_binding/binding_context"
  4. "git.sxidc.com/go-tools/api_binding/http_binding/response"
  5. "github.com/gin-gonic/gin/binding"
  6. "net/http"
  7. )
  8. func BindingJson[O any](c *binding_context.Context, request any, sendFunc response.SendFunc[O]) bool {
  9. err := c.ShouldBindJSON(request)
  10. if err != nil {
  11. var zero O
  12. sendFunc(c, http.StatusBadRequest, zero, err)
  13. return false
  14. }
  15. return true
  16. }
  17. func BindingQuery[O any](c *binding_context.Context, query any, sendFunc response.SendFunc[O]) bool {
  18. err := c.ShouldBindQuery(query)
  19. if err != nil {
  20. var zero O
  21. sendFunc(c, http.StatusBadRequest, zero, err)
  22. return false
  23. }
  24. return true
  25. }
  26. func BindingMultipartForm[O any](c *binding_context.Context, request any, sendFunc response.SendFunc[O]) bool {
  27. err := c.ShouldBindWith(request, binding.FormMultipart)
  28. if err != nil {
  29. var zero O
  30. sendFunc(c, http.StatusBadRequest, zero, err)
  31. return false
  32. }
  33. return true
  34. }
  35. func BindingForm[T any](c *binding_context.Context, request interface{}, sendFunc response.SendFunc[T]) bool {
  36. err := c.ShouldBindWith(request, binding.Form)
  37. if err != nil {
  38. var zero T
  39. sendFunc(c, http.StatusBadRequest, zero, err)
  40. return false
  41. }
  42. return true
  43. }
  44. func BindingXML[T any](c *binding_context.Context, request interface{}, sendFunc response.SendFunc[T]) bool {
  45. err := c.ShouldBindXML(request)
  46. if err != nil {
  47. var zero T
  48. sendFunc(c, http.StatusBadRequest, zero, err)
  49. return false
  50. }
  51. return true
  52. }