使用 Gin 框架实现验证码功能
时间:2024-02-22
浏览:485
作者:佚名
今日不肯埋头,明日何以抬头!每日一句努力自己的话哈哈~哈喽,今天我将给大家带来一篇《使用 Gin 框架实现验证码功能》,主要内容是讲解等等,感兴趣的朋友可以收藏或者有更好的建议在评论提出,我都会认真看的!大家一起进步,一起学习!
问题内容
我在验证 gin 中的数字时遇到错误,对于字符串数据类型,没有错误并且检测到错误,但是当我用字符串填写 int 类型的价格字段时,它收到错误 500,我预计错误为 400,解决方案是什么?
package web
type bookrequest struct{
title string `json:"title" binding:"required"`
description string `json:"description" binding:"required"`
price int `json:"price" binding:"required,numeric,gte=0"`
rating int `json:"rating" binding:"required,numeric"`
}
func (controller *BookControllerImpl) Create(ctx *gin.Context) {
var bookRequest web.BookRequest
err := ctx.ShouldBindJSON(&bookRequest)
if err != nil {
var error_request []string
for _, e := range err.(validator.ValidationErrors) {
errorMessage := fmt.Sprintf("Error field %s, Condition %s", e.Field(), e.ActualTag())
error_request = append(error_request, errorMessage)
}
ctx.JSON(http.StatusBadRequest, web.WebResponse{
Code: http.StatusBadRequest,
Status: "BAD REQUEST",
Data: error_request,
})
return
}
book, err := controller.BookService.Create(bookRequest)
if err != nil {
ctx.JSON(http.StatusBadRequest, web.WebResponse{
Code: http.StatusBadRequest,
Status: "BAD REQUEST",
Data: err,
})
}
ctx.JSON(http.StatusOK, web.WebResponse{
Code: 200,
Status: "Ok",
Data: book,
})
}正确答案
当我用字符串填写int类型的价格字段时
如果您的请求 (payload price) 不是标准的或者它可以是 string 或 number,您可以为您的结构使用 json.number 类型。
type bookrequest struct{
title string `json:"title" binding:"required"`
description string `json:"description" binding:"required"`
price json.number `json:"price" binding:"required,numeric,gte=0"`
rating int `json:"rating" binding:"required,numeric"`
}
这是 json.number 的简单示例:https://go.dev/play/p/7fyCFAon2PC
- 您必须检查 err 是否为
validator.validationerrors,如下所示:
...
err := ctx.shouldbindjson(&bookrequest)
if err != nil {
if vals, ok := err.(validator.validationerrors); ok {
// do for loop from vals
...
ctx.json(http.statusbadrequest, web.webresponse{
code: http.statusbadrequest,
status: "bad request",
data: error_request,
})
return
}
ctx.json(http.statusinternalservererror, web.webresponse{
code: http.statusinternalservererror,
status: "internal server error",
data: err,
})
return
}
...
========== 答案 2 ==========
您可以实施json.Unmarshaller来做到这一点
示例如下:
func (br *BookRequest) UnmarshalJSON(b []byte) error {
// TODO: remove binding tag
type helperBookRequest struct {
Title string `json:"title" binding:"required"`
Description string `json:"description" binding:"required"`
Price any `json:"price" binding:"required,numeric,gte=0"` // look at this type is any or interface{}
Rating int `json:"rating" binding:"required,numeric"`
}
var hbr helperBookRequest
err := json.Unmarshal(b, &hbr)
if err != nil {
return err
}
br.Title = hbr.Title
br.Description = hbr.Description
br.Rating = hbr.Rating
switch hbr.Price.(type) {
case float64:
br.Price = strconv.Itoa(int(hbr.Price.(float64)))
case string:
br.Price = hbr.Price.(string)
default:
return errors.New("invalid type")
}
return nil
}
演示中的简单示例:https://go.dev/play/p/tmnKW4peBgp
到这里,我们也就讲完了《使用 Gin 框架实现验证码功能》的内容了。个人认为,基础知识的学习和巩固,是为了更好的将其运用到项目中,欢迎关注golang学习网公众号,带你了解更多关于的知识点!
本文内容来源于互联网,如有侵权请联系删除。
近期热门
11.18
站内热门
最新文章
12.01
12.01
热门专题
