Go 1.18 中的三个小功能

2022年2月20日 187点热度 0人点赞 0条评论

本文作者:Carl M. Johnson

每个人都很兴奋,经过十年左右[1]的开发人员要求泛型之后,Go 编程语言将在 2022 年第一季度的 Go 1.18 中获得泛型类型和函数[2]。毫无疑问,泛型将导致大量实验,有些是好的[3],有些是坏的[4],有些挺奇怪[5]。Go 1.18 还准备通过将模糊[6]测试作为标准测试包的一部分来提高软件可靠性。但是今天,我想看看 Go 1.18 中的一些细微变化,否则它们可能会迷失泛型这个主要功能的兴奋中。

1、二进制中包含的版本控制信息

使用 go:generate[7]go:embed[8] 两篇文章中,其中一个激励示例是能够将有关用于创建二进制文件的 Git 提交哈希(commit hash)的信息嵌入其中。在 Go1.18 中,这成为日常go命令的自动组成部分。

runtime/debug.BuildInfo[9] 通过返回 runtime/debug.ReadBuildInfo()[10] 更新,包括一个新的字段 Settings []debug.BuildSettingSettings[11] 反过来是描述二进制文件的键值对。提交哈希是 key 的值 vcs.revision,而 vcs.time 做了所期望的。甚至vcs.modified可以告诉你构建是 “dirty” 还是 “clean”。

因为从 slice 中读取出来debug.BuildSetting有点复杂,所以我编写了一个名为 versioninfo[12] 的小包,它在启动时读取调试信息,设置versioninfo.Revision, versioninfo.LastCommitversioninfo.DirtyBuild,但可以随意编写自己的帮助程序库[13]

2、新的 http.MaxBytesHandler 中间件

关于 http.MaxBytesHandler[14] 没有什么好说的。似乎除了吹嘘该功能是我写的[15]。其实我并没有设计它。这只是一个在 Go 问题跟踪器中请求和批准的五行函数,我认为它足够简单,可以在其他任务之间编写和提交。

这是文档:

MaxBytesHandler returns a Handler that runs h with its ResponseWriter and Request.Body wrapped by a MaxBytesReader.

这样做的情况是,如果你将服务器直接暴露在 Internet 上,可能需要限制要处理的请求的大小,以避免拒绝服务攻击。这已经可以在带有 http.MaxBytesReader[16] 的处理程序中完成,但是通过在中间件级别强制执行限制,现在你可以确保它不会被意外遗忘在 Web 服务器的某个被忽视的角落。

3、不合理但有效的 strings.Cut 功能

strings.Cut[17] 类似于 Python 的 str.partition[18],它在找到分隔符子字符串的第一个位置将字符串切成两段。

为什么不增加 LastCut?Russ Cox 的解释是,LastIndex 的调用次数明显少于 Index,因此暂不提供 LastCut。

详情见 Russ Cox 在 issue 中所写的内容:https://github.com/golang/go/issues/46336。

原文链接:https://blog.carlmjohnson.net/post/2021/golang-118-minor-features/

参考资料

[1]

十年左右: https://blog.carlmjohnson.net/post/google-go-the-good-the-bad-and-the-meh/

[2]

泛型类型和函数: https://go.dev/blog/why-generics

[3]

好的: https://github.com/carlmjohnson/deque/

[4]

坏的: https://github.com/carlmjohnson/new/

[5]

挺奇怪: https://github.com/carlmjohnson/truthy/

[6]

将模糊: https://go.dev/blog/fuzz-beta

[7]

使用 go:generate: https://blog.carlmjohnson.net/post/2016-11-27-how-to-use-go-generate/

[8]

go:embed: https://blog.carlmjohnson.net/post/2021/how-to-use-go-embed/

[9]

runtime/debug.BuildInfo: https://pkg.go.dev/runtime/debug@master#BuildInfo

[10]

runtime/debug.ReadBuildInfo(): https://pkg.go.dev/runtime/debug@master#ReadBuildInfo

[11]

Settings: https://pkg.go.dev/runtime/debug@master#BuildSetting

[12]

versioninfo: https://github.com/carlmjohnson/versioninfo/

[13]

随意编写自己的帮助程序库: https://blog.carlmjohnson.net/post/2020/avoid-dependencies/

[14]

http.MaxBytesHandler: https://pkg.go.dev/net/http@master#MaxBytesHandler

[15]

我写的: https://golang.org/cl/346569

[16]

http.MaxBytesReader: https://pkg.go.dev/net/http#MaxBytesReader

[17]

strings.Cut: https://pkg.go.dev/strings@master#Cut

[18]

str.partition: https://docs.python.org/3/library/stdtypes.html#str.partition


欢迎关注Go招聘公众号,获取Go专题大厂内推面经简历股文等相关资料可回复和点击导航查阅。

图片

73960Go 1.18 中的三个小功能

这个人很懒,什么都没留下

文章评论