context.go 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. package api
  2. import (
  3. "bytes"
  4. "git.sxidc.com/go-framework/baize/framework/core/infrastructure/logger"
  5. "github.com/gin-gonic/gin"
  6. "io"
  7. "mime/multipart"
  8. "strings"
  9. )
  10. type Context struct {
  11. *gin.Context
  12. }
  13. // GetFileHeaderBytes 获取传递的文件名和文件内容
  14. func (c *Context) GetFileHeaderBytes(fileHeader *multipart.FileHeader) (string, []byte, error) {
  15. file, err := fileHeader.Open()
  16. if err != nil {
  17. return "", nil, err
  18. }
  19. defer func(file multipart.File) {
  20. err := file.Close()
  21. if err != nil {
  22. logger.GetInstance().Error(err)
  23. return
  24. }
  25. }(file)
  26. contentBytes, err := io.ReadAll(file)
  27. if err != nil {
  28. return "", nil, err
  29. }
  30. return fileHeader.Filename, contentBytes, nil
  31. }
  32. func (c *Context) ReadBody() ([]byte, error) {
  33. if c.Request.Body == nil {
  34. return make([]byte, 0), nil
  35. }
  36. body, err := io.ReadAll(c.Request.Body)
  37. if err != nil {
  38. return nil, err
  39. }
  40. defer func(Body io.ReadCloser) {
  41. err := Body.Close()
  42. if err != nil {
  43. logger.GetInstance().Error(err)
  44. return
  45. }
  46. }(c.Request.Body)
  47. c.Request.Body = io.NopCloser(bytes.NewBuffer(body))
  48. return body, nil
  49. }
  50. func (c *Context) GetAllQueryParams() map[string]string {
  51. queryParams := make(map[string]string, 0)
  52. for key, value := range c.Request.URL.Query() {
  53. queryParams[key] = strings.Join(value, ",")
  54. }
  55. return queryParams
  56. }
  57. func (c *Context) GetAllPathParams() map[string]string {
  58. pathParams := make(map[string]string, 0)
  59. for _, params := range c.Params {
  60. pathParams[params.Key] = params.Value
  61. }
  62. return pathParams
  63. }