douyuefei3546 2019-02-07 09:50
浏览 459
已采纳

Gin框架中的自定义验证

I have an application written with golang gin framework. I want to write a middleware to customize all error messages specially in the case of BindJSON.

Here is the middleware:

func Errors() gin.HandlerFunc {
    return func(c *gin.Context) {
        c.Next()
        // Only run if there are some errors to handle
        if len(c.Errors) > 0 {
            for _, e := range c.Errors {
                // Find out what type of error it is
                switch e.Type {
                case gin.ErrorTypePublic:
                    // Only output public errors if nothing has been written yet
                    if !c.Writer.Written() {
                        c.JSON(c.Writer.Status(), gin.H{"Error": e.Error()})
                    }
                case gin.ErrorTypeBind:
                    errs := e.Err.(validator.ValidationErrors)
                    list := make(map[int]string)

                    fmt.Println(errs)
                    for field, err := range errs {
                        list[field] = validationErrorToText(err)
                    }
                    // Make sure we maintain the preset response status
                    status := http.StatusBadRequest
                    if c.Writer.Status() != http.StatusOK {
                        status = c.Writer.Status()
                    }
                    c.JSON(status, gin.H{"Errors": list})

                default:
                    c.JSON(http.StatusBadRequest, gin.H{"Errors": c.Errors.JSON()})
                }

            }
            // If there was no public or bind error, display default 500 message
            if !c.Writer.Written() {
                c.JSON(http.StatusInternalServerError, gin.H{"Error": errorInternalError.Error()})
            }
        }
    }
}

The functionality is so simple, it gets all the gin errors and do something based on error type! the problem is in case of gin.ErrorTypeBind when i've tried to map errors to validation errors: e.Err.(validator.ValidationErrors). I've got this error

interface conversion: error is validator.ValidationErrors, not validator.ValidationErrors (types from different packages)

here is the list of imported packages:

import (
    "errors"
    "fmt"
    "net/http"

    "github.com/gin-gonic/gin"
    "gopkg.in/go-playground/validator.v9"
)
  • 写回答

1条回答 默认 最新

  • douzhengnao8265 2019-02-07 18:47
    关注

    Looking at the source code of gin I am seeing this:

    import (
        "gopkg.in/go-playground/validator.v8"
    )
    

    but you are using "gopkg.in/go-playground/validator.v9"

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器