Go 1.18 中的三個功能,你知道幾個
大家好,我是程序員幽鬼。
每個人都很興奮,經(jīng)過十年左右[1]的開發(fā)人員要求泛型之后,Go 編程語言將在 2022 年第一季度的 Go 1.18 中獲得泛型類型和函數(shù)[2]。毫無疑問,泛型將導(dǎo)致大量實驗,有些是好的[3],有些是壞的[4],有些挺奇怪[5]。Go 1.18 還準(zhǔn)備通過將模糊[6]測試作為標(biāo)準(zhǔn)測試包的一部分來提高軟件可靠性。但是今天,我想看看 Go 1.18 中的一些細(xì)微變化,否則它們可能會迷失泛型這個主要功能的興奮中。
1、二進(jìn)制中包含的版本控制信息
在使用 go:generate[7] 和 go:embed[8] 兩篇文章中,其中一個激勵示例是能夠?qū)⒂嘘P(guān)用于創(chuàng)建二進(jìn)制文件的 Git 提交哈希(commit hash)的信息嵌入其中。在 Go1.18 中,這成為日常go命令的自動組成部分。
在 runtime/debug.BuildInfo[9] 通過返回 runtime/debug.ReadBuildInfo()[10] 更新,包括一個新的字段 Settings []debug.BuildSetting。Settings[11] 反過來是描述二進(jìn)制文件的鍵值對。提交哈希是 key 的值 vcs.revision,而 vcs.time 做了所期望的。甚至vcs.modified可以告訴你構(gòu)建是 “dirty” 還是 “clean”。
因為從 slice 中讀取出來debug.BuildSetting有點(diǎn)復(fù)雜,所以我編寫了一個名為 versioninfo[12] 的小包,它在啟動時讀取調(diào)試信息,設(shè)置versioninfo.Revision, versioninfo.LastCommit 和 versioninfo.DirtyBuild,但可以隨意編寫自己的幫助程序庫[13]。
2、新的 http.MaxBytesHandler 中間件
關(guān)于 http.MaxBytesHandler[14] 沒有什么好說的。似乎除了吹噓該功能是我寫的[15]。其實我并沒有設(shè)計它。這只是一個在 Go 問題跟蹤器中請求和批準(zhǔn)的五行函數(shù),我認(rèn)為它足夠簡單,可以在其他任務(wù)之間編寫和提交。
這是文檔:
MaxBytesHandler returns a Handler that runs h with its ResponseWriter and Request.Body wrapped by a MaxBytesReader.
這樣做的情況是,如果你將服務(wù)器直接暴露在 Internet 上,可能需要限制要處理的請求的大小,以避免拒絕服務(wù)攻擊。這已經(jīng)可以在帶有 http.MaxBytesReader[16] 的處理程序中完成,但是通過在中間件級別強(qiáng)制執(zhí)行限制,現(xiàn)在你可以確保它不會被意外遺忘在 Web 服務(wù)器的某個被忽視的角落。
3、不合理但有效的 strings.Cut 功能
strings.Cut[17] 類似于 Python 的 str.partition[18],它在找到分隔符子字符串的第一個位置將字符串切成兩段。
為什么不增加 LastCut?Russ Cox 的解釋是,LastIndex 的調(diào)用次數(shù)明顯少于 Index,因此暫不提供 LastCut。
詳情見 Russ Cox 在 issue 中所寫的內(nèi)容:https://github.com/golang/go/issues/46336。
本文作者:Carl M. Johnson
原文鏈接: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]泛型類型和函數(shù): 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
本文作者:Carl M. Johnson
本文轉(zhuǎn)載自微信公眾號「幽鬼」,可以通過以下二維碼關(guān)注。轉(zhuǎn)載本文請聯(lián)系幽鬼公眾號。