package middlewares import ( "bytes" "encoding/json" "fmt" "github.com/gin-gonic/gin" "hospital-admin-api/consts" "io" "net/http" ) // RequestParamsMiddleware 获取请求参数中间件 func RequestParamsMiddleware() gin.HandlerFunc { return func(c *gin.Context) { contentType := c.Request.Header.Get("Content-Type") params := make(map[string]string) // 判断请求参数类型 switch contentType { case "application/json": // 解析 application/json 请求体 bodyBytes, err := io.ReadAll(c.Request.Body) if err != nil { c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to read request body"}) c.Abort() return } // 创建新的请求对象,并设置请求体数据 c.Request.Body = io.NopCloser(bytes.NewBuffer(bodyBytes)) var jsonParams map[string]interface{} err = json.Unmarshal(bodyBytes, &jsonParams) if err != nil { c.JSON(http.StatusBadRequest, gin.H{ "message": "Invalid JSON data", "code": consts.HttpError, "data": "", }) c.Abort() return } for key, value := range jsonParams { params[key] = fmt.Sprintf("%v", value) } // 存储参数到上下文 c.Set("params", params) case "multipart/form-data", "application/form-data", "application/x-www-form-urlencoded": // 解析 Form 表单参数 err := c.Request.ParseForm() if err != nil { c.JSON(http.StatusBadRequest, gin.H{ "message": "Invalid form data", "code": consts.HttpError, "data": "", }) c.Abort() return } for key, values := range c.Request.Form { if len(values) > 0 { params[key] = fmt.Sprintf("%v", values[0]) } } // 存储参数到上下文 c.Set("params", params) default: // 解析 URL 参数 queryParams := c.Request.URL.Query() for key, values := range queryParams { if len(values) > 0 { params[key] = fmt.Sprintf("%v", values[0]) } } // 存储参数到上下文 c.Set("params", params) } // 继续处理请求 c.Next() } }