response.go 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. package response
  2. import (
  3. "fmt"
  4. "github.com/gin-gonic/gin"
  5. "github.com/pkg/errors"
  6. "github.com/sirupsen/logrus"
  7. "net/http"
  8. "sghgogs.com/micro/common"
  9. "sghgogs.com/micro/common/errorcode"
  10. "strconv"
  11. )
  12. // ApiResponse 是通用的 API 响应结构体
  13. type ApiResponse struct {
  14. Code int `json:"code"`
  15. Message string `json:"message"`
  16. Data interface{} `json:"data,omitempty"`
  17. }
  18. // SuccessResponse 构建成功响应
  19. func SuccessResponse(data interface{}) *ApiResponse {
  20. return &ApiResponse{
  21. Code: http.StatusOK,
  22. Message: "Success",
  23. Data: data,
  24. }
  25. }
  26. func ErrorResponse(code int, message string) *ApiResponse {
  27. return &ApiResponse{
  28. Code: code,
  29. Message: message,
  30. }
  31. }
  32. func MicroErrorRequest(err error) (int, string) {
  33. logrus.Error(err.Error())
  34. if errCode, ok := err.(*errorcode.ErrorCode); ok {
  35. return int(errCode.Code), errCode.Detail
  36. }
  37. return 500, err.Error()
  38. }
  39. // ValidationConfig 结构体表示参数验证的配置
  40. type ValidationConfig struct {
  41. Validators map[string]func(interface{}) error
  42. Required []string
  43. }
  44. // ValidateInt 示例验证函数:验证是否为整数
  45. func ValidateInt(value interface{}) error {
  46. _, err := strconv.Atoi(value.(string))
  47. return err
  48. }
  49. // ParseQueryParameters 函数解析查询参数并根据配置动态验证
  50. func ParseQueryParameters(c *gin.Context, config ValidationConfig) (map[string]interface{}, error) {
  51. params := make(map[string]interface{})
  52. // 获取所有查询参数
  53. for key, value := range c.Request.URL.Query() {
  54. if len(value) > 0 {
  55. params[key] = value[0]
  56. } else {
  57. params[key] = ""
  58. }
  59. }
  60. // 动态验证参数
  61. for key, validator := range config.Validators {
  62. if paramValue, ok := params[key]; ok {
  63. if err := validator(paramValue); err != nil {
  64. return nil, errors.New(common.ErrorMessage[common.MissingParameter] + "[" + key + "]: " + err.Error())
  65. }
  66. }
  67. }
  68. // 验证必要参数
  69. for _, key := range config.Required {
  70. if _, ok := params[key]; !ok {
  71. fmt.Println(key)
  72. return nil, errors.New(common.ErrorMessage[common.MissingParameter] + "[" + key + "]")
  73. }
  74. }
  75. return params, nil
  76. }