登录
首页 >  Golang >  Go问答

使用Gin验证输入并排除特定子字符串

来源:stackoverflow

时间:2024-02-27 08:51:24 113浏览 收藏

在Golang实战开发的过程中,我们经常会遇到一些这样那样的问题,然后要卡好半天,等问题解决了才发现原来一些细节知识点还是没有掌握好。今天golang学习网就整理分享《使用Gin验证输入并排除特定子字符串》,聊聊,希望可以帮助到正在努力赚钱的你。

问题内容

我想确保输入不包含子字符串“organization”、“forbidden”并且不等于“foo”和“bar”。

// cmd/httpd/handler/item_post.go

package handler

import (
  "net/http"
  "dummy-project/itemdata"

  "github.com/gin-gonic/gin"
)

func itempost() gin.handlerfunc {
  return func(c *gin.context) {
    requestbody := itemdata.item{}
    if err := c.shouldbindjson(&requestbody); err != nil {
        c.json(http.statusbadrequest, gin.h{"message": err.error()})
        return
    }
    // insert item object to db
    c.json(http.statuscreated, requestbody)
  }
}

下面是我用于 post 请求和插入数据库记录的结构: // itemdata/item_data.go 打包项目数据

// Item struct used for POST request and inserting new item
type Item struct {
   ID           string `bson:"_id" json:"id"`
   Name string `bson:"name" json:"name" binding:"required,excludesrune=organizationforbidden,ne=foo,ne=bar"`
}

当我插入这些值时: foo -> 验证失败排除符文

bar -> 验证失败在 ne

组织 ->validation 在排除符文时失败

orgfor -> 验证在排除符文时失败

禁止 -> 验证在排除符文时失败

bar -> 成功

我想要什么: foo -> 失败

bar -> 失败

组织->失败

orgfor -> 成功,因为组织和禁词不完整

禁止 -> 失败

bar -> 失败

如何使用 go gin 和 go validator 实现此目的?谢谢


解决方案


看起来您正在尝试排除整个字符串,因此 exincludes 验证比 exincludesrune 更合适。 go 中的“符文”是一个 unicode 代码点,您可能更习惯于将其称为“字符”,因此您编写的验证可能会失败任何包含字母 o 的字符串。

试试这个:

name string `bson:"name" json:"name" binding:"required,excludes=organization,excludes=forbidden,ne=foo,ne=bar"`

编辑:如评论中所述,这不符合您禁止被阻止字符串的大写版本的要求。据我所知,您需要使用自定义验证器来执行此操作:

func caseinsensitiveexcludes(fl validator.fieldlevel) bool {
    lowervalue := strings.tolower(fl.field().string())
   
    if strings.contains(lowervalue, fl.param()) {
        return false
    }

    return true
}

validate.registervalidation("iexcludes", caseinsensitiveexcludes)

然后尝试这个字段定义:

Name string `bson:"name" json:"name" binding:"required,iexcludes=organization,iexcludes=forbidden,ne=foo,ne=bar"`

理论要掌握,实操不能落!以上关于《使用Gin验证输入并排除特定子字符串》的详细介绍,大家都掌握了吧!如果想要继续提升自己的能力,那么就来关注golang学习网公众号吧!

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