package middlewares import ( "encoding/json" "github.com/gin-gonic/gin" "hospital-open-api/consts" "net/http" ) // RequestParamsMiddleware1 获取请求参数中间件 func RequestParamsMiddleware1() gin.HandlerFunc { return func(c *gin.Context) { contentType := c.GetHeader("Content-Type") // 判断请求参数类型 switch contentType { case "application/json": // 解析 JSON 参数 var params map[string]interface{} // 读取请求体数据 data, err := c.GetRawData() if err != nil { c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to read request body"}) return } // 解析 JSON 数据到 map[string]interface{} err = json.Unmarshal(data, ¶ms) if err != nil { c.JSON(http.StatusBadRequest, gin.H{ "message": "Invalid JSON data", "code": consts.HttpError, "data": "", }) c.Abort() return } // 存储参数到上下文 c.Set("params", params) case "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 } // 将参数转换为 map[string]interface{} params := make(map[string]interface{}) for key, values := range c.Request.Form { if len(values) > 0 { params[key] = values[0] } } // 存储参数到上下文 c.Set("params", params) default: // 解析 URL 参数 queryParams := c.Request.URL.Query() // 将参数转换为 map[string]interface{} params := make(map[string]interface{}) for key, values := range queryParams { if len(values) > 0 { params[key] = values[0] } } // 存储参数到上下文 c.Set("params", params) } // 继续处理请求 c.Next() } }