123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687 |
- package response
- import (
- "fmt"
- "github.com/gin-gonic/gin"
- "github.com/pkg/errors"
- "github.com/sirupsen/logrus"
- "net/http"
- "sghgogs.com/micro/common"
- "sghgogs.com/micro/common/errorcode"
- "strconv"
- )
- // ApiResponse 是通用的 API 响应结构体
- type ApiResponse struct {
- Code int `json:"code"`
- Message string `json:"message"`
- Data interface{} `json:"data,omitempty"`
- }
- // SuccessResponse 构建成功响应
- func SuccessResponse(data interface{}) *ApiResponse {
- return &ApiResponse{
- Code: http.StatusOK,
- Message: "Success",
- Data: data,
- }
- }
- func ErrorResponse(code int, message string) *ApiResponse {
- return &ApiResponse{
- Code: code,
- Message: message,
- }
- }
- func MicroErrorRequest(err error) (int, string) {
- logrus.Error(err.Error())
- if errCode, ok := err.(*errorcode.ErrorCode); ok {
- return int(errCode.Code), errCode.Detail
- }
- return 500, err.Error()
- }
- // ValidationConfig 结构体表示参数验证的配置
- type ValidationConfig struct {
- Validators map[string]func(interface{}) error
- Required []string
- }
- // ValidateInt 示例验证函数:验证是否为整数
- func ValidateInt(value interface{}) error {
- _, err := strconv.Atoi(value.(string))
- return err
- }
- // ParseQueryParameters 函数解析查询参数并根据配置动态验证
- func ParseQueryParameters(c *gin.Context, config ValidationConfig) (map[string]interface{}, error) {
- params := make(map[string]interface{})
- // 获取所有查询参数
- for key, value := range c.Request.URL.Query() {
- if len(value) > 0 {
- params[key] = value[0]
- } else {
- params[key] = ""
- }
- }
- // 动态验证参数
- for key, validator := range config.Validators {
- if paramValue, ok := params[key]; ok {
- if err := validator(paramValue); err != nil {
- return nil, errors.New(common.ErrorMessage[common.MissingParameter] + "[" + key + "]: " + err.Error())
- }
- }
- }
- // 验证必要参数
- for _, key := range config.Required {
- if _, ok := params[key]; !ok {
- fmt.Println(key)
- return nil, errors.New(common.ErrorMessage[common.MissingParameter] + "[" + key + "]")
- }
- }
- return params, nil
- }
|