“纵有疾风来,人生不言弃”,这句话送给正在学习golang的朋友们,也希望在阅读本文《Gin 框架中的自定义验证》后,能够真的帮助到大家。我也会在后续的文章中,陆续更新Golang相关的技术文章,有
“纵有疾风来,人生不言弃”,这句话送给正在学习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的技术知识我们会一点点深入介绍,欢迎大家关注编程网公众号,一起学习编程~
--结束END--
本文标题: Gin 框架中的自定义验证
本文链接: https://www.lsjlt.com/news/596786.html(转载时请注明来源链接)
有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341
2024-04-05
2024-04-05
2024-04-05
2024-04-04
2024-04-05
2024-04-05
2024-04-05
2024-04-05
2024-04-04
回答
回答
回答
回答
回答
回答
回答
回答
回答
回答
0