HashidsDecoder 中间件,自动解码路由参数中的Hashid
()
| 11 | |
| 12 | // HashidsDecoder 中间件,自动解码路由参数中的Hashid |
| 13 | func HashidsDecoder() gin.HandlerFunc { |
| 14 | return func(c *gin.Context) { |
| 15 | // 获取所有路由参数 |
| 16 | params := c.Params |
| 17 | |
| 18 | // 遍历所有参数,查找需要解码的ID参数 |
| 19 | for _, param := range params { |
| 20 | if isIDParam(param.Key) { |
| 21 | // 尝试解码Hashid |
| 22 | if decodedID, err := hashids.TryParseID(param.Value); err == nil { |
| 23 | // 将解码后的数字ID存储到上下文中,供后续处理使用 |
| 24 | c.Set("decoded_"+param.Key, decodedID) |
| 25 | // 同时保留原始值 |
| 26 | c.Set("original_"+param.Key, param.Value) |
| 27 | } else { |
| 28 | // 如果解码失败,返回错误 |
| 29 | c.JSON(http.StatusBadRequest, model.ParamError.ToNewErrorResponse("Invalid ID format: "+param.Key)) |
| 30 | c.Abort() |
| 31 | return |
| 32 | } |
| 33 | } |
| 34 | } |
| 35 | |
| 36 | c.Next() |
| 37 | } |
| 38 | } |
| 39 | |
| 40 | // isIDParam 判断参数是否为ID类型参数 |
| 41 | func isIDParam(paramName string) bool { |
nothing calls this directly
no test coverage detected