登录
首页 >  Golang >  Go问答

Gin 框架中的自定义验证

来源:stackoverflow

时间:2024-04-04 12:00:36 144浏览 收藏

“纵有疾风来,人生不言弃”,这句话送给正在学习Golang的朋友们,也希望在阅读本文《Gin 框架中的自定义验证》后,能够真的帮助到大家。我也会在后续的文章中,陆续更新Golang相关的技术文章,有好的建议欢迎大家在评论留言,非常感谢!

问题内容

我有一个用golang gin框架编写的应用程序。我想编写一个中间件来自定义所有错误消息,特别是在 bindjson 的情况下。

这是中间件:

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()})
            }
        }
    }
}

功能非常简单,它获取所有 gin 错误并根据错误类型执行某些操作!当我尝试将错误映射到验证错误时,问题出在 gin.errortypebind 的情况下:e.err.(validator.validationerrors)。 我遇到了这个错误

接口转换:错误是validator.validationerrors,而不是validator.validationerrors(来自不同包的类型)

这是导入的包的列表:

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

    "github.com/gin-gonic/gin"
    "gopkg.in/go-playground/validator.v9"
)

解决方案


看着 source code of gin,我看到了这个:

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

但是你正在使用 "gopkg.in/go-演示/validator.v9"

今天带大家了解了的相关知识,希望对你有所帮助;关于Golang的技术知识我们会一点点深入介绍,欢迎大家关注golang学习网公众号,一起学习编程~

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>