Go 1.21

最後更新


Go 1.21 發布於 2023-08-08,目前最新修補版為 go1.21.13,已停止支援,請升級到 go1.27.4。

版本介紹


Go 1.21 讓日常程式碼一口氣變簡潔:新增內建函式 min、max、clear,標準庫加入泛型的 slices、maps、cmp 套件,以及官方結構化日誌套件 log/slog。工具鏈也開始「自動管理 Go 版本」:go.mod 的 go 行變成嚴格的最低需求,本機版本太舊時可自動下載對應工具鏈。升級時要注意:panic(nil) 現在會變成 *runtime.PanicNilError;套件初始化順序有了明確定義,依賴隱含順序的程式可能改變行為;PGO 正式可用並在 main 套件有 default.pgo 時自動啟用。

語言變更


  • 新增內建函式 min、max,可傳入任意多個同型別的可排序值;clear 清空映射或把切片元素歸零。
  • 型別推斷更強:把泛型函式當引數傳入、指派給變數時,多數情況可以省略型別參數。
  • panic(nil) 改為觸發 *runtime.PanicNilError,保證 recover() 在 panic 中不會回傳 nil。
  • 套件初始化順序改為「依匯入路徑排序,逐一初始化相依已完成的套件」,規則明確。
  • 以預覽方式提供「每次迭代一個新迴圈變數」的實驗(GOEXPERIMENT=loopvar),於 Go 1.22 正式生效。

工具


  • go.mod 的 go 1.21.0 代表最低需求,舊版工具鏈會明確拒絕;新增 toolchain 行指定建議的工具鏈。
  • 本機 Go 版本不足時,go 指令可依 GOTOOLCHAIN 設定自動下載並切換到需要的版本。
  • 版本號改為 1.21.0 這種三段式;第一個正式版不再是 1.21。
  • -pgo 預設為 auto,main 套件目錄有 default.pgo 就會自動使用,詳見 PGO。
  • 新增實驗性的 WASI 移植(GOOS=wasip1),可編譯成在 WebAssembly 執行環境執行的程式。

執行時與效能


  • PGO 正式可用,多數程式啟用後提升 2–7%,還能把常見的介面方法呼叫去虛擬化(devirtualize)。
  • GC 內部調校後,部分應用的尾端延遲(tail latency)最多降低 40%。
  • 在 C 建立的執行緒上反覆從 C 呼叫 Go,每次的額外開銷從約 1–3 微秒降到 100–200 奈秒。
  • 堆疊很深時,panic 訊息改為印出最內層 50 層與最外層 50 層,方便追查遞迴的起點。

標準庫重點


  • 新增 log/slog:結構化日誌,輸出 key=value 或 JSON,詳見 slog。
  • 新增 slices、maps:排序、搜尋、比較、複製等泛型工具函式,詳見 slices、maps。
  • 新增 cmp:提供 Ordered 約束與 Compare、Less 函式,詳見 cmp。
  • sync 新增 OnceFunc、OnceValue、OnceValues,把「只執行一次」包成函式。
  • context 新增 WithoutCancel、WithDeadlineCause、WithTimeoutCause、AfterFunc。
  • 新增 testing/slogtest,用來驗證自訂的 slog.Handler。

min、max 與 clear


min、max 不必再自己寫比較函式,也能比較字串(依字典順序)。clear 作用在映射時刪除所有鍵;作用在切片時把每個元素設為零值,長度不變。
範例:
  1. package main
  2. import "fmt"
  3. func main() {
  4. fmt.Println(min(3, 1, 2), max(2.5, 1.0))
  5. fmt.Println(min("banana", "apple"))
  6. m := map[string]int{"a": 1, "b": 2}
  7. clear(m)
  8. fmt.Println(len(m))
  9. s := []int{1, 2, 3}
  10. clear(s)
  11. fmt.Println(s, len(s))
  12. }

輸出:
  1. 1 2.5
  2. apple
  3. 0
  4. [0 0 0] 3

slices、maps 與 cmp


slices.Sort 排序、slices.Contains 檢查是否包含、slices.Compact 去掉相鄰重複值。slices.SortFunc 搭配 cmp.Compare 可自訂排序規則:回傳負數代表 a 排前面。maps.Clone 複製映射,修改複本不影響原本的映射。
範例:
  1. package main
  2. import (
  3. "cmp"
  4. "fmt"
  5. "maps"
  6. "slices"
  7. )
  8. type User struct {
  9. Name string
  10. Age int
  11. }
  12. func main() {
  13. nums := []int{5, 2, 8, 2}
  14. slices.Sort(nums)
  15. fmt.Println(nums, slices.Contains(nums, 8), slices.Index(nums, 5))
  16. fmt.Println(slices.Compact(nums))
  17. users := []User{{"Bob", 30}, {"Amy", 25}, {"Cid", 30}}
  18. slices.SortFunc(users, func(a, b User) int {
  19. if c := cmp.Compare(a.Age, b.Age); c != 0 {
  20. return c
  21. }
  22. return cmp.Compare(a.Name, b.Name)
  23. })
  24. fmt.Println(users)
  25. src := map[string]int{"x": 1}
  26. dst := maps.Clone(src)
  27. dst["y"] = 2
  28. fmt.Println(len(src), len(dst), maps.Equal(src, dst))
  29. }

輸出:
  1. [2 2 5 8] true 2
  2. [2 5 8]
  3. [{Amy 25} {Bob 30} {Cid 30}]
  4. 1 2 false

log/slog


slog 的每筆日誌都有等級、訊息與一組鍵值屬性,方便日後用程式搜尋與統計。NewTextHandler 輸出 key=value 格式,NewJSONHandler 輸出 JSON。範例用 ReplaceAttr 拿掉時間欄位,讓輸出固定;預設等級是 INFO,所以 Debug 那筆不會印出。
範例:
  1. package main
  2. import (
  3. "log/slog"
  4. "os"
  5. )
  6. func main() {
  7. handler := slog.NewTextHandler(os.Stdout, &slog.HandlerOptions{
  8. ReplaceAttr: func(groups []string, a slog.Attr) slog.Attr {
  9. if a.Key == slog.TimeKey && len(groups) == 0 {
  10. return slog.Attr{}
  11. }
  12. return a
  13. },
  14. })
  15. logger := slog.New(handler)
  16. logger.Info("user login", "user", "gopher", "id", 42)
  17. logger.With("service", "api").Warn("slow request", slog.Int("ms", 1200))
  18. logger.Debug("not shown")
  19. }

輸出:
  1. level=INFO msg="user login" user=gopher id=42
  2. level=WARN msg="slow request" service=api ms=1200

sync.OnceValue


讀設定、建立連線這類「第一次用到才做、之後重複使用結果」的工作,以前要宣告 sync.Once 再搭配一個變數。OnceValue 回傳一個函式,第一次呼叫時執行並記住結果,之後直接回傳,即使多個 goroutine 同時呼叫也只會執行一次。
範例:
  1. package main
  2. import (
  3. "fmt"
  4. "sync"
  5. )
  6. func main() {
  7. calls := 0
  8. loadConfig := sync.OnceValue(func() string {
  9. calls++
  10. return "config-v1"
  11. })
  12. fmt.Println(loadConfig(), loadConfig(), calls)
  13. }

輸出:
  1. config-v1 config-v1 1

本版新增的棄用 API


以下 API 從 Go 1.21 起標記為棄用(Deprecated),新程式不要再使用;說明欄為官方原文。
套件符號官方說明
crypto/ellipticCurve.Addthis is a low-level unsafe API.
crypto/ellipticCurve.Doublethis is a low-level unsafe API.
crypto/ellipticCurve.IsOnCurvethis is a low-level unsafe API. For ECDH, use the crypto/ecdh package. The NewPublicKey methods of NIST curves in crypto/ecdh accept the same encoding as the Unmarshal function, and perform on-curve checks.
crypto/ellipticCurve.ScalarBaseMultthis is a low-level unsafe API. For ECDH, use the crypto/ecdh package. Most uses of ScalarBaseMult can be replaced by a call to the PrivateKey.PublicKey method in crypto/ecdh.
crypto/ellipticCurve.ScalarMultthis is a low-level unsafe API. For ECDH, use the crypto/ecdh package. Most uses of ScalarMult can be replaced by a call to the ECDH methods of NIST curves in crypto/ecdh.
crypto/ellipticCurveParams.Addthe [CurveParams] methods are deprecated and are not guaranteed to provide any security property. For ECDH, use the [crypto/ecdh] package. For ECDSA, use the [crypto/ecdsa] package with a [Curve] value returned directly from [P224], [P256], [P384], or [P521].
crypto/ellipticCurveParams.Doublethe [CurveParams] methods are deprecated and are not guaranteed to provide any security property. For ECDH, use the [crypto/ecdh] package. For ECDSA, use the [crypto/ecdsa] package with a [Curve] value returned directly from [P224], [P256], [P384], or [P521].
crypto/ellipticCurveParams.IsOnCurvethe [CurveParams] methods are deprecated and are not guaranteed to provide any security property. For ECDH, use the [crypto/ecdh] package. For ECDSA, use the [crypto/ecdsa] package with a [Curve] value returned directly from [P224], [P256], [P384], or [P521].
crypto/ellipticCurveParams.ScalarBaseMultthe [CurveParams] methods are deprecated and are not guaranteed to provide any security property. For ECDH, use the [crypto/ecdh] package. For ECDSA, use the [crypto/ecdsa] package with a [Curve] value returned directly from [P224], [P256], [P384], or [P521].
crypto/ellipticCurveParams.ScalarMultthe [CurveParams] methods are deprecated and are not guaranteed to provide any security property. For ECDH, use the [crypto/ecdh] package. For ECDSA, use the [crypto/ecdsa] package with a [Curve] value returned directly from [P224], [P256], [P384], or [P521].
crypto/ellipticGenerateKeyfor ECDH, use the GenerateKey methods of the [crypto/ecdh] package; for ECDSA, use the GenerateKey function of the crypto/ecdsa package.
crypto/ellipticMarshalfor ECDH, use the crypto/ecdh package. This function returns an encoding equivalent to that of PublicKey.Bytes in crypto/ecdh.
crypto/ellipticUnmarshalfor ECDH, use the crypto/ecdh package. This function accepts an encoding equivalent to that of the NewPublicKey methods in crypto/ecdh.
crypto/rsaGenerateMultiPrimeKeyThe use of this function with a number of primes different from two is not recommended for the above security, compatibility, and performance reasons. Use [GenerateKey] instead.
crypto/rsaPrecomputedValues.CRTValuesThese values are still filled in by Precompute for backwards compatibility but are not used. Multi-prime RSA is very rare, and is implemented by this package without CRT optimizations to limit complexity.
crypto/x509RevocationList.RevokedCertificatesUse RevokedCertificateEntries instead.
reflectSliceHeaderUse unsafe.Slice or unsafe.SliceData instead.
reflectStringHeaderUse unsafe.String or unsafe.StringData instead.

修補版本


版本發布日期含安全修補內容(官方原文)
go1.21.12023-09-06是includes four security fixes to the cmd/go, crypto/tls, and html/template packages, as well as bug fixes to the compiler, the go command, the linker, the runtime, and the context, crypto/tls, encoding/gob, encoding/xml, go/types, net/http, os, and path/filepath packages.
go1.21.22023-10-05是includes one security fix to the cmd/go package, as well as bug fixes to the compiler, the go command, the linker, the runtime, and the runtime/metrics package.
go1.21.32023-10-10是includes a security fix to the net/http package.
go1.21.42023-11-07是includes security fixes to the path/filepath package, as well as bug fixes to the linker, the runtime, the compiler, and the go/types, net/http, and runtime/cgo packages.
go1.21.52023-12-05是includes security fixes to the go command, and the net/http and path/filepath packages, as well as bug fixes to the compiler, the go command, the runtime, and the crypto/rand, net, os, and syscall packages.
go1.21.62024-01-09否includes fixes to the compiler, the runtime, and the crypto/tls, maps, and runtime/pprof packages.
go1.21.72024-02-06否includes fixes to the compiler, the go command, the runtime, and the crypto/x509 package.
go1.21.82024-03-05是includes security fixes to the crypto/x509, html/template, net/http, net/http/cookiejar, and net/mail packages, as well as bug fixes to the go command and the runtime.
go1.21.92024-04-03是includes a security fix to the net/http package, as well as bug fixes to the linker, and the go/types and net/http packages.
go1.21.102024-05-07是includes security fixes to the go command, as well as bug fixes to the net/http package.
go1.21.112024-06-04是includes security fixes to the archive/zip and net/netip packages, as well as bug fixes to the compiler, the go command, the runtime, and the os package.
go1.21.122024-07-02是includes security fixes to the net/http package, as well as bug fixes to the compiler, the go command, the runtime, and the crypto/x509, net/http, net/netip, and os packages.
go1.21.132024-08-06否includes fixes to the go command, the covdata command, and the bytes package.

已知漏洞


在 Go 1.21 系列修補版中修正的漏洞共 24 個;仍影響最新修補版 go1.21.13 的漏洞共 103 個。

本系列已修正


編號CVE摘要(官方原文)修正於
GO-2024-2963CVE-2024-24791Denial of service due to improper 100-continue handling in net/httpgo1.21.12、go1.22.5
GO-2024-2962CVE-2023-24531Output of "go env" does not sanitize values in cmd/gogo1.21.0-0
GO-2024-2888CVE-2024-24789Mishandling of corrupt central directory record in archive/zipgo1.21.11、go1.22.4
GO-2024-2887CVE-2024-24790Unexpected behavior from Is methods for IPv4-mapped IPv6 addresses in net/netipgo1.21.11、go1.22.4
GO-2024-2825CVE-2024-24787Arbitrary code execution during build on Darwin in cmd/gogo1.21.10、go1.22.3
GO-2024-2687CVE-2023-45288HTTP/2 CONTINUATION flood in net/httpgo1.21.9、go1.22.2
GO-2024-2610CVE-2024-24785Errors returned from JSON marshaling may break template escaping in html/templatego1.21.8、go1.22.1
GO-2024-2609CVE-2024-24784Comments in display names are incorrectly handled in net/mailgo1.21.8、go1.22.1
GO-2024-2600CVE-2023-45289Incorrect forwarding of sensitive headers and cookies on HTTP redirect in net/httpgo1.21.8、go1.22.1
GO-2024-2599CVE-2023-45290Memory exhaustion in multipart form parsing in net/textproto and net/httpgo1.21.8、go1.22.1
GO-2024-2598CVE-2024-24783Verify panics on certificates with an unknown public key algorithm in crypto/x509go1.21.8、go1.22.1
GO-2023-2383CVE-2023-45285Command 'go get' may unexpectedly fallback to insecure git in cmd/gogo1.20.12、go1.21.5
GO-2023-2382CVE-2023-39326Denial of service via chunk extensions in net/httpgo1.20.12、go1.21.5
GO-2023-2186CVE-2023-45284Incorrect detection of reserved device names on Windows in path/filepathgo1.20.11、go1.21.4
GO-2023-2185CVE-2023-45283Insecure parsing of Windows paths with a ??\ prefix in path/filepathgo1.20.11、go1.21.4、go1.20.12、go1.21.5
GO-2023-2185CVE-2023-45283Insecure parsing of Windows paths with a ??\ prefix in path/filepathgo1.20.11、go1.21.4、go1.20.12、go1.21.5
GO-2023-2102CVE-2023-39325HTTP/2 rapid reset can cause excessive work in net/httpgo1.20.10、go1.21.3
GO-2023-2095CVE-2023-39323Arbitrary code execution during build via line directives in cmd/gogo1.20.9、go1.21.2
GO-2023-2045CVE-2023-39322Memory exhaustion in QUIC connection handling in crypto/tlsgo1.21.1
GO-2023-2044CVE-2023-39321Panic when processing post-handshake message on QUIC connections in crypto/tlsgo1.21.1
GO-2023-2043CVE-2023-39319Improper handling of special tags within script contexts in html/templatego1.20.8、go1.21.1
GO-2023-2042CVE-2023-39320Arbitrary code execution via go.mod toolchain directive in cmd/gogo1.21.1
GO-2023-2041CVE-2023-39318Improper handling of HTML-like comments in script contexts in html/templatego1.20.8、go1.21.1
GO-2023-1987CVE-2023-29409Large RSA keys can cause high CPU usage in crypto/tlsgo1.19.12、go1.20.7、go1.21.0-rc.4

本版已停止支援,不會再修正這些漏洞;完整清單見 資安漏洞。

資料來源