Go 1.20

最後更新


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

版本介紹


Go 1.20 補強了泛型與錯誤處理,並開始引入以效能剖析資料引導最佳化(profile-guided optimization,PGO)的預覽版。對新手最實用的變化是:一個錯誤可以同時包裝多個錯誤(errors.Join、多個 %w),切片可以直接轉成陣列,context 也能記錄「為什麼被取消」。升級時要注意:Go 1.20 是最後一個支援 Windows 7/8 與 macOS 10.13/10.14 的版本;沒有 C 編譯器的機器上 cgo 預設會關閉。

語言變更


  • 切片可以直接轉成陣列,例如 [4]byte(s);切片長度不足時會 panic。
  • unsafe 新增 SliceData、String、StringData,可以在不依賴內部結構的情況下拆解與組合切片、字串。
  • 一般介面等「可比較但不一定安全」的型別,現在也能滿足 comparable 約束(比較時可能在執行期 panic)。
  • 規格明確定義結構與陣列逐一比較欄位/元素,遇到第一個不相等就停止,既有程式行為不變。

工具


  • go build、go test 等新增 -pgo 旗標,可讀取 CPU 剖析檔讓編譯器更積極地內聯熱點函式,詳見 PGO。
  • go build -cover 可以編譯帶覆蓋率統計的執行檔,量測整合測試或伺服器實際跑到的程式碼,詳見 覆蓋率。
  • 標準庫不再預先編譯放在 $GOROOT/pkg,改為需要時編譯並存進建置快取,下載包更小。
  • 新增 go build -C <dir> 先切換目錄再執行;go test -skip 可略過符合樣式的測試。
  • 系統上找不到 C 編譯器時,cgo 預設停用,標準庫改用純 Go 實作。

執行時與效能


  • GC 內部資料結構重整,記憶體負擔降低、CPU 效能最多提升約 2%。
  • 編譯速度最多快約 10%,回到與 Go 1.17 相當的水準。
  • 新增 runtime/coverage 套件,讓長時間執行、不會呼叫 os.Exit 的伺服器程式也能寫出覆蓋率資料。

標準庫重點


  • errors.Join 把多個錯誤合併成一個,fmt.Errorf 也能寫多個 %w,詳見 錯誤包裝。
  • context.WithCancelCause 取消時可以附上原因,用 context.Cause 讀回。
  • strings.CutPrefix、strings.CutSuffix(以及 bytes 的同名函式)一次完成「檢查並去掉前綴/後綴」。
  • 新增 crypto/ecdh 套件,提供橢圓曲線金鑰交換。
  • net/http 新增 ResponseController,可針對單一請求設定讀寫逾時;httputil.ReverseProxy 新增 Rewrite 鉤子。

切片轉陣列


陣列長度固定、可以當映射的鍵,有時比切片更方便。[4]byte(s) 會把切片前 4 個元素「複製」成一個新陣列,之後修改陣列不影響原切片。
範例:
  1. package main
  2. import "fmt"
  3. func main() {
  4. s := []byte{1, 2, 3, 4, 5}
  5. a := [4]byte(s)
  6. a[0] = 9
  7. fmt.Println(a, s)
  8. defer func() {
  9. fmt.Println("recovered:", recover())
  10. }()
  11. _ = [8]byte(s)
  12. }

輸出:
  1. [9 2 3 4] [1 2 3 4 5]
  2. recovered: runtime error: cannot convert slice with length 5 to array or pointer to array with length 8

注意:陣列長度大於切片長度時會在執行期 panic,範例用 recover 把這個 panic 接住並印出訊息。

包裝多個錯誤


驗證表單時可能同時發現好幾個問題,以前只能挑一個回傳。errors.Join 把多個錯誤合成一個,Error() 會以換行分隔;errors.Is 會逐一檢查裡面每個錯誤。fmt.Errorf 也接受多個 %w。
範例:
  1. package main
  2. import (
  3. "errors"
  4. "fmt"
  5. "io/fs"
  6. )
  7. func main() {
  8. errA := errors.New("name is empty")
  9. err := errors.Join(errA, fs.ErrNotExist)
  10. fmt.Println(err)
  11. fmt.Println(errors.Is(err, errA), errors.Is(err, fs.ErrNotExist))
  12. wrapped := fmt.Errorf("save failed: %w; %w", errA, fs.ErrPermission)
  13. fmt.Println(wrapped)
  14. fmt.Println(errors.Is(wrapped, fs.ErrPermission))
  15. }

輸出:
  1. name is empty
  2. file does not exist
  3. true true
  4. save failed: name is empty; permission denied
  5. true

context.WithCancelCause


一般的 cancel() 只會讓 ctx.Err() 變成 context canceled,看不出原因。WithCancelCause 回傳的取消函式接受一個錯誤,之後用 context.Cause 取出,方便記錄日誌或回傳給呼叫端。詳見 context 取消與逾時。
範例:
  1. package main
  2. import (
  3. "context"
  4. "errors"
  5. "fmt"
  6. )
  7. var errQuota = errors.New("quota exceeded")
  8. func main() {
  9. ctx, cancel := context.WithCancelCause(context.Background())
  10. cancel(errQuota)
  11. <-ctx.Done()
  12. fmt.Println(ctx.Err())
  13. fmt.Println(context.Cause(ctx))
  14. }

輸出:
  1. context canceled
  2. quota exceeded

strings.CutPrefix 與 CutSuffix


常見的寫法是先 HasPrefix 再 TrimPrefix,要寫兩次前綴。CutPrefix 一次回傳去掉前綴後的字串與是否有該前綴;沒有時回傳原字串與 false。
範例:
  1. package main
  2. import (
  3. "fmt"
  4. "strings"
  5. )
  6. func main() {
  7. rest, ok := strings.CutPrefix("Bearer abc123", "Bearer ")
  8. fmt.Println(rest, ok)
  9. name, ok := strings.CutSuffix("report.csv", ".json")
  10. fmt.Println(name, ok)
  11. }

輸出:
  1. abc123 true
  2. report.csv false

本版新增的棄用 API


以下 API 從 Go 1.20 起標記為棄用(Deprecated),新程式不要再使用;說明欄為官方原文。
套件符號官方說明
math/randReadFor almost all use cases, [crypto/rand.Read] is more appropriate. If a deterministic source is required, use [math/rand/v2.ChaCha8.Read].
math/randSeedAs of Go 1.20 there is no reason to call Seed with a random value. Programs that call Seed with a known value to get a specific sequence of results should use New(NewSource(seed)) to obtain a local random generator.

修補版本


版本發布日期含安全修補內容(官方原文)
go1.20.12023-02-14是includes security fixes to the crypto/tls, mime/multipart, net/http, and path/filepath packages, as well as bug fixes to the compiler, the go command, the linker, the runtime, and the time package.
go1.20.22023-03-07是includes a security fix to the crypto/elliptic package, as well as bug fixes to the compiler, the covdata command, the linker, the runtime, and the crypto/ecdh, crypto/rsa, crypto/x509, os, and syscall packages.
go1.20.32023-04-04是includes security fixes to the go/parser, html/template, mime/multipart, net/http, and net/textproto packages, as well as bug fixes to the compiler, the linker, the runtime, and the time package.
go1.20.42023-05-02是includes three security fixes to the html/template package, as well as bug fixes to the compiler, the runtime, and the crypto/subtle, crypto/tls, net/http, and syscall packages.
go1.20.52023-06-06是includes four security fixes to the cmd/go and runtime packages, as well as bug fixes to the compiler, the go command, the runtime, and the crypto/rsa, net, and os packages.
go1.20.62023-07-11是includes a security fix to the net/http package, as well as bug fixes to the compiler, cgo, the cover tool, the go command, the runtime, and the crypto/ecdsa, go/build, go/printer, net/mail, and text/template packages.
go1.20.72023-08-01是includes a security fix to the crypto/tls package, as well as bug fixes to the assembler and the compiler.
go1.20.82023-09-06是includes two security fixes to the html/template package, as well as bug fixes to the compiler, the go command, the runtime, and the crypto/tls, go/types, net/http, and path/filepath packages.
go1.20.92023-10-05是includes one security fix to the cmd/go package, as well as bug fixes to the go command and the linker.
go1.20.102023-10-10是includes a security fix to the net/http package.
go1.20.112023-11-07是includes security fixes to the path/filepath package, as well as bug fixes to the linker and the net/http package.
go1.20.122023-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 and the go command.
go1.20.132024-01-09否includes fixes to the runtime and the crypto/tls package.
go1.20.142024-02-06否includes fixes to the crypto/x509 package.

已知漏洞


在 Go 1.20 系列修補版中修正的漏洞共 28 個;仍影響最新修補版 go1.20.14 的漏洞共 114 個。

本系列已修正


編號CVE摘要(官方原文)修正於
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-2375CVE-2023-45287Before Go 1.20, the RSA based key exchange methods in crypto/tls may exhibit a timing side channelgo1.20.0
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-2043CVE-2023-39319Improper handling of special tags within script contexts in html/templatego1.20.8、go1.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
GO-2023-1878CVE-2023-29406Insufficient sanitization of Host header in net/httpgo1.19.11、go1.20.6
GO-2023-1842CVE-2023-29405Improper sanitization of LDFLAGS with embedded spaces in go command with cgo in cmd/gogo1.19.10、go1.20.5
GO-2023-1841CVE-2023-29404Improper handling of non-optional LDFLAGS in go command with cgo in cmd/gogo1.19.10、go1.20.5
GO-2023-1840CVE-2023-29403Unsafe behavior in setuid/setgid binaries in runtimego1.19.10、go1.20.5
GO-2023-1839CVE-2023-29402Code injection via go command with cgo in cmd/gogo1.19.10、go1.20.5
GO-2023-1753CVE-2023-29400Improper handling of empty HTML attributes in html/templatego1.19.9、go1.20.4
GO-2023-1752CVE-2023-24540Improper handling of JavaScript whitespace in html/templatego1.19.9、go1.20.4
GO-2023-1751CVE-2023-24539Improper sanitization of CSS values in html/templatego1.19.9、go1.20.4
GO-2023-1705CVE-2023-24536Excessive resource consumption in net/http, net/textproto and mime/multipartgo1.19.8、go1.20.3
GO-2023-1704CVE-2023-24534Excessive memory allocation in net/http and net/textprotogo1.19.8、go1.20.3
GO-2023-1703CVE-2023-24538Backticks not treated as string delimiters in html/templatego1.19.8、go1.20.3
GO-2023-1702CVE-2023-24537Infinite loop in parsing in go/scannergo1.19.8、go1.20.3
GO-2023-1621CVE-2023-24532Incorrect calculation on P256 curves in crypto/internal/nistecgo1.19.7、go1.20.2
GO-2023-1571CVE-2022-41723Denial of service via crafted HTTP/2 stream in net/http and golang.org/x/netgo1.19.6、go1.20.1
GO-2023-1570CVE-2022-41724Panic on large handshake records in crypto/tlsgo1.19.6、go1.20.1
GO-2023-1569CVE-2022-41725Excessive resource consumption in mime/multipartgo1.19.6、go1.20.1
GO-2023-1568CVE-2022-41722Path traversal on Windows in path/filepathgo1.19.6、go1.20.1

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

資料來源