Simplifying String Validation in Go: Introducing validatorgo

simplifying string validation in go: introducing validatorgo

字符串验证器和清理器的库,基于 js 库 validator.js

为什么选择验证器go?

为什么不使用流行的 go 库,如 package validator 或 govalidator?虽然这两个库都很出名,但 validatorgo 专注于独立字符串验证,并提供了受 validator.js 启发的广泛的可定制验证器集合,而这两个 go 库都没有完全实现。

以下是 validatorgo 与 go-playground/validator 和 govalidator 相比的突出之处:

1. 与 go-playground/validator 相比

直接字符串验证:go-playground/validator 主要用于使用标签验证结构字段,这非常适合处理 json 或基于结构的数据。然而,它并不是为验证单个字符串而设计的,validatorgo 可以无缝地验证单个字符串,而不需要结构标签或额外的设置。

性能:go-playground/validator 依赖反射来动态检查结构标签。反射虽然功能强大,但会带来性能开销,尤其是在验证大型或复杂数据结构时。 validatorgo 避免了反射,从而提高了性能,对于需要单字段验证的场景来说,速度更快、效率更高。

2. 与 asasskevich/govalidator 相比

定制和灵活性:govalidator 为字符串提供了一系列验证器,但是 validatorgo 通过允许单个验证器的特定选项和配置来增强灵活性。例如,可以自定义日期格式或区域设置规范,使开发人员能够更好地控制根据项目需求定制的验证规则。

项目动机

我创建了 validatorgo 作为另一个名为 ginvalidator 的 go 库的依赖项,该库验证 go web 应用程序中的 http 请求。受 express-validator(node.js 和 express 的流行验证库)的启发,validatorgo 填补了 go 生态系统中的空白,实现高效、可定制且简单的字符串验证。由于其他库要么矫枉过正,缺乏功能,要么不满足我的用例,我构建了 validatorgo 来提供实用的解决方案。

安装

使用 go get。

 go get github.com/bube054/validatorgo

登录后复制

然后将包导入到您自己的代码中。

 import (   "fmt"   "github.com/bube054/validatorgo" )

登录后复制

如果您不满意使用长 validatorgo 包名称,您可以这样做。

 import (   "fmt"   vgo "github.com/bube054/validatorgo" )

登录后复制

简单的验证器示例

 func main(){   id := "5f2a6c69e1d7a4e0077b4e6b"   validid := vgo.ismongoid(id)   fmt.println(validid) // true }

登录后复制

一些验证器

下面是 validatorgo 包提供的验证器列表,涵盖了各种字符串格式和类型,使其能够满足多种验证需求。

validator description

containschecks if a string contains a specified substring.equalsvalidates if a string is exactly equal to a comparison string.isabaroutingchecks if the string is a valid aba routing number (us bank accounts).isaftervalidates if a date string is after a specified date.isalphaensures the string contains only letters (a-za-z).isalphanumericvalidates if a string contains only letters and numbers.isasciichecks if the string contains only ascii characters.isbase32checks if the string is a valid base32 encoded value.isbase64validates if a string is in base64 encoding.isbeforeensures the date is before a specified date.isbooleanchecks if the string is either “true” or “false”.iscreditcardvalidates if the string is a valid credit card number.iscurrencychecks if the string is a valid currency format.isdatevalidates if a string is a valid date.isdecimalensures the string represents a valid decimal number.isemailchecks if the string is a valid email address format.isemptyvalidates if a string is empty.isfqdnchecks if the string is a fully qualified domain name.isfloatensures the string represents a floating-point number.ishexcolorvalidates if a string is a valid hex color (e.g., #ffffff).isipchecks if the string is a valid ip address (ipv4 or ipv6).isiso8601validates if the string is in iso8601 date format.islengthchecks if the string’s length is within a specified range.ismimetypevalidates if the string is a valid mime type.ismobilephonechecks if the string is a valid mobile phone number for specified locales.ismongoidvalidates if the string is a valid mongodb objectid.isnumericensures the string contains only numeric characters.ispostalcodechecks if the string is a valid postal code for specified locale.isrfc3339validates if the string is in rfc3339 date format.isslugchecks if the string is url-friendly (only letters, numbers, and dashes).isstrongpasswordensures the string meets common password strength requirements.isurlvalidates if the string is a url.isuuidchecks if the string is a valid uuid (versions 1-5).isuppercaseensures the string is all uppercase.isvatchecks if the string is a valid vat number for specified countries.matchesvalidates if the string matches a specified regular expression.

该表应该涵盖 validatorgo 中当前可用的大多数验证器。请务必参阅包的文档以了解每个验证器的更详细用法。

⚠ 注意当使用需要选项结构(指针或非指针)的验证器时,请始终显式地为所有结构字段提供值。与 validator.js 中缺少的字段会自动设置为默认值不同,go 使用严格类型。这意味着布尔值的缺失值默认为 false,数字类型的缺失值默认为 0,等等。如果您习惯了 javascript 版本,不指定所有字段可能会导致意外行为。

示例

  // do this (using the default options specified in the docs)  ok := validatorgo.isfqdn("example", nil)  // or this (explicitly setting all possible fields for the structs)  ok := validatorgo.isfqdn("example", &validatorgo.isfqdnopts{    requiretld: false,    allowunderscores: false,    allowtrailingdot: true,    allownumerictld: false,    ignoremaxlength: true  })  // but rarely this(not explicitly setting all possible fields)  ok := validatorgo.isfqdn("example", &validatorgo.isfqdnopts{ requiretld: false, })

登录后复制

简单的消毒剂示例

  import (   "fmt"   "github.com/bube054/validatorgo/sanitizer" ) func main(){   str := sanitizer.Whitelist("Hello123 World!", "a-zA-Z")   fmt.Println(str) // "HelloWorld" }

登录后复制

消毒剂

sanitizer description

trimremoves whitespace from both ends of the string.ltrimremoves whitespace from the left side of the string.rtrimremoves whitespace from the right side of the string.tolowerconverts the entire string to lowercase.toupperconverts the entire string to uppercase.escapeescapes html characters in the string to prevent injection attacks.unescapereverts escaped html characters back to normal characters.normalizeemailstandardizes an email address, e.g., removing dots in gmail addresses.blacklistremoves characters from the string that match specified characters or patterns.whitelistretains only characters in the string that match specified characters or patterns.replacereplaces occurrences of a substring with a specified replacement.striplowremoves control characters, optionally allowing some specified ones.trimspacetrims all types of whitespace from both ends of the string.tobooleanconverts common truthy and falsy values in strings into boolean true or false.tointconverts a numeric string into an integer, if possible.tofloatconverts a numeric string into a floating-point number, if possible.

这些清理程序通常用于通过删除或修改潜在不需要或危险的字符来确保数据一致性和安全性。

请务必参考 validatorgo 官方文档,了解每种消毒剂的具体实现和示例。

概括

validatorgo 如果您需要的话,是理想的选择:

针对各个字段进行高效、无反射的验证,而不会产生与基于结构的反射相关的性能成本。高度可定制与现代数据格式一致的验证选项,提供与 validator.js 相同的稳健性。

使用 validatorgo,您将获得专门为字符串验证而设计的工具,支持 go 中的独立和 web 应用程序要求。

维护者

bube054 – attah gbubemi david(作者)

以上就是Simplifying String Validation in Go: Introducing validatorgo的详细内容,更多请关注【创想鸟】其它相关文章!

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至253000106@qq.com举报,一经查实,本站将立刻删除。

发布者:PHP中文网,转转请注明出处:https://www.chuangxiangniao.com/p/2477244.html

(0)
上一篇 2025年3月4日 19:21:15
下一篇 2025年3月4日 19:21:35

AD推荐 黄金广告位招租... 更多推荐

相关推荐

  • GO:缺乏同步

    var a stringvar done boolfunc setup() { a = “hello, world” done = true}func doprint() { if !done { once.do(setup) } prin…

    2025年3月4日
    200
  • 在 Go Huma 中添加过滤查询参数

    据我所知,不幸的是,huma 不支持这样的数组查询过滤器:filters[]=filter1&filters[]=filter2(也不保留括号,例如filter=filter1&filter=filter2)。我遇到了这个 …

    2025年3月4日
    200
  • gRPC 流:最佳实践和性能见解

    介绍 grpc 流允许 protobuf 消息从客户端流式传输到服务器、从服务器流式传输到客户端,或者双向流式传输。 这一强大的功能可用于构建实时应用程序,例如聊天应用程序、实时监控仪表板等。 在本文中,我们将探讨如何正确使用 grpc 流…

    2025年3月4日
    200
  • PnR:具有 Go 平台抽象的配置意图驱动的容器编排

    您是否曾经希望容器编排能够比静态依赖链更灵活,但又比 kubernetes 更简单?满足 pnr(提示和响应) – 一种配置驱动的方法,利用 go 强大的平台抽象功能根据实际的就绪状态而不是简单的依赖关系来编排容器。 go 平台…

    编程技术 2025年3月4日
    200
  • Starknet 交易批量处理程序

    抽象的 本文介绍了 metacube 中使用的交易批处理程序,用于即时发送玩家赚取的 nft。它解释了批处理程序基于参与者的可扩展架构,并提供了 go 中的详细实现。 所有代码片段都可以在关联的 github 存储库中找到。 建筑学 巴彻由…

    2025年3月4日
    200
  • 每个后端开发人员都应该知道的热门库

    Go语言凭借其简洁性、性能和并发优势,已成为后端开发的热门选择。虽然Go标准库功能强大,但许多第三方库能显著提升开发效率和代码质量。 本文将介绍五个必备的Go语言库,助您高效构建API、管理数据库、完善日志记录等。 1. Gin 高性能HT…

    2025年3月4日
    200
  • 使用 OpenAI、Go 和 PostgreSQL (pgvector) 构建语义搜索引擎

    近年来,向量嵌入技术已成为自然语言处理(NLP)和语义搜索的核心。与传统的关键词搜索不同,向量数据库通过比较文本的向量表示(嵌入)来理解文本的语义含义。本示例展示如何结合OpenAI嵌入、Go语言和PostgreSQL数据库(以及pgvec…

    2025年3月4日
    200
  • 微服务中的事务:SAGA 模式概述部分

    构建强大的分布式系统是一项极具挑战性的任务,尤其是在保证多个服务数据一致性方面。在微服务架构中,传统的数据库事务往往力不从心。这时,分布式事务便成为关键解决方案。 分布式事务能够协调多个服务间的操作,并优雅地处理各种故障。而SAGA模式是实…

    2025年3月4日
    200
  • Docker 卷

    容器化应用的关键在于数据持久化。docker容器默认情况下,删除后其内部所有数据都会丢失。解决方法是使用docker卷。它们允许数据在容器生命周期中持续存在,为任何应用提供隔离和可扩展性。 为何使用Docker卷? 持久性:创建或链接卷到容…

    2025年3月4日
    200
  • 如何使用Golang,Gin和Postgresql构建CRUD应用程序

    本教程演示如何使用Go语言、Gin框架和PostgreSQL数据库构建一个简单的CRUD (创建、读取、更新、删除) 应用。最终,您将得到一个可以管理PostgreSQL数据库中数据的基本应用。 目录 简介前提条件项目结构项目设置创建数据库…

    2025年3月4日
    200

发表回复

登录后才能评论