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 個元素「複製」成一個新陣列,之後修改陣列不影響原切片。範例:
- package main
- import "fmt"
- func main() {
- s := []byte{1, 2, 3, 4, 5}
- a := [4]byte(s)
- a[0] = 9
- fmt.Println(a, s)
- defer func() {
- fmt.Println("recovered:", recover())
- }()
- _ = [8]byte(s)
- }
輸出:
- [9 2 3 4] [1 2 3 4 5]
- 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。範例:
- package main
- import (
- "errors"
- "fmt"
- "io/fs"
- )
- func main() {
- errA := errors.New("name is empty")
- err := errors.Join(errA, fs.ErrNotExist)
- fmt.Println(err)
- fmt.Println(errors.Is(err, errA), errors.Is(err, fs.ErrNotExist))
- wrapped := fmt.Errorf("save failed: %w; %w", errA, fs.ErrPermission)
- fmt.Println(wrapped)
- fmt.Println(errors.Is(wrapped, fs.ErrPermission))
- }
輸出:
- name is empty
- file does not exist
- true true
- save failed: name is empty; permission denied
- true
context.WithCancelCause
一般的
cancel() 只會讓 ctx.Err() 變成 context canceled,看不出原因。WithCancelCause 回傳的取消函式接受一個錯誤,之後用 context.Cause 取出,方便記錄日誌或回傳給呼叫端。詳見 context 取消與逾時。範例:
- package main
- import (
- "context"
- "errors"
- "fmt"
- )
- var errQuota = errors.New("quota exceeded")
- func main() {
- ctx, cancel := context.WithCancelCause(context.Background())
- cancel(errQuota)
- <-ctx.Done()
- fmt.Println(ctx.Err())
- fmt.Println(context.Cause(ctx))
- }
輸出:
- context canceled
- quota exceeded
strings.CutPrefix 與 CutSuffix
常見的寫法是先
HasPrefix 再 TrimPrefix,要寫兩次前綴。CutPrefix 一次回傳去掉前綴後的字串與是否有該前綴;沒有時回傳原字串與 false。範例:
- package main
- import (
- "fmt"
- "strings"
- )
- func main() {
- rest, ok := strings.CutPrefix("Bearer abc123", "Bearer ")
- fmt.Println(rest, ok)
- name, ok := strings.CutSuffix("report.csv", ".json")
- fmt.Println(name, ok)
- }
輸出:
- abc123 true
- report.csv false
本版新增的棄用 API
以下 API 從 Go 1.20 起標記為棄用(Deprecated),新程式不要再使用;說明欄為官方原文。
| 套件 | 符號 | 官方說明 |
|---|---|---|
math/rand | Read | For almost all use cases, [crypto/rand.Read] is more appropriate. If a deterministic source is required, use [math/rand/v2.ChaCha8.Read]. |
math/rand | Seed | As 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.1 | 2023-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.2 | 2023-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.3 | 2023-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.4 | 2023-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.5 | 2023-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.6 | 2023-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.7 | 2023-08-01 | 是 | includes a security fix to the crypto/tls package, as well as bug fixes to the assembler and the compiler. |
go1.20.8 | 2023-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.9 | 2023-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.10 | 2023-10-10 | 是 | includes a security fix to the net/http package. |
go1.20.11 | 2023-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.12 | 2023-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.13 | 2024-01-09 | 否 | includes fixes to the runtime and the crypto/tls package. |
go1.20.14 | 2024-02-06 | 否 | includes fixes to the crypto/x509 package. |
已知漏洞
在 Go 1.20 系列修補版中修正的漏洞共 28 個;仍影響最新修補版
go1.20.14 的漏洞共 114 個。本系列已修正
| 編號 | CVE | 摘要(官方原文) | 修正於 |
|---|---|---|---|
| GO-2023-2383 | CVE-2023-45285 | Command 'go get' may unexpectedly fallback to insecure git in cmd/go | go1.20.12、go1.21.5 |
| GO-2023-2382 | CVE-2023-39326 | Denial of service via chunk extensions in net/http | go1.20.12、go1.21.5 |
| GO-2023-2375 | CVE-2023-45287 | Before Go 1.20, the RSA based key exchange methods in crypto/tls may exhibit a timing side channel | go1.20.0 |
| GO-2023-2186 | CVE-2023-45284 | Incorrect detection of reserved device names on Windows in path/filepath | go1.20.11、go1.21.4 |
| GO-2023-2185 | CVE-2023-45283 | Insecure parsing of Windows paths with a ??\ prefix in path/filepath | go1.20.11、go1.21.4、go1.20.12、go1.21.5 |
| GO-2023-2185 | CVE-2023-45283 | Insecure parsing of Windows paths with a ??\ prefix in path/filepath | go1.20.11、go1.21.4、go1.20.12、go1.21.5 |
| GO-2023-2102 | CVE-2023-39325 | HTTP/2 rapid reset can cause excessive work in net/http | go1.20.10、go1.21.3 |
| GO-2023-2095 | CVE-2023-39323 | Arbitrary code execution during build via line directives in cmd/go | go1.20.9、go1.21.2 |
| GO-2023-2043 | CVE-2023-39319 | Improper handling of special tags within script contexts in html/template | go1.20.8、go1.21.1 |
| GO-2023-2041 | CVE-2023-39318 | Improper handling of HTML-like comments in script contexts in html/template | go1.20.8、go1.21.1 |
| GO-2023-1987 | CVE-2023-29409 | Large RSA keys can cause high CPU usage in crypto/tls | go1.19.12、go1.20.7、go1.21.0-rc.4 |
| GO-2023-1878 | CVE-2023-29406 | Insufficient sanitization of Host header in net/http | go1.19.11、go1.20.6 |
| GO-2023-1842 | CVE-2023-29405 | Improper sanitization of LDFLAGS with embedded spaces in go command with cgo in cmd/go | go1.19.10、go1.20.5 |
| GO-2023-1841 | CVE-2023-29404 | Improper handling of non-optional LDFLAGS in go command with cgo in cmd/go | go1.19.10、go1.20.5 |
| GO-2023-1840 | CVE-2023-29403 | Unsafe behavior in setuid/setgid binaries in runtime | go1.19.10、go1.20.5 |
| GO-2023-1839 | CVE-2023-29402 | Code injection via go command with cgo in cmd/go | go1.19.10、go1.20.5 |
| GO-2023-1753 | CVE-2023-29400 | Improper handling of empty HTML attributes in html/template | go1.19.9、go1.20.4 |
| GO-2023-1752 | CVE-2023-24540 | Improper handling of JavaScript whitespace in html/template | go1.19.9、go1.20.4 |
| GO-2023-1751 | CVE-2023-24539 | Improper sanitization of CSS values in html/template | go1.19.9、go1.20.4 |
| GO-2023-1705 | CVE-2023-24536 | Excessive resource consumption in net/http, net/textproto and mime/multipart | go1.19.8、go1.20.3 |
| GO-2023-1704 | CVE-2023-24534 | Excessive memory allocation in net/http and net/textproto | go1.19.8、go1.20.3 |
| GO-2023-1703 | CVE-2023-24538 | Backticks not treated as string delimiters in html/template | go1.19.8、go1.20.3 |
| GO-2023-1702 | CVE-2023-24537 | Infinite loop in parsing in go/scanner | go1.19.8、go1.20.3 |
| GO-2023-1621 | CVE-2023-24532 | Incorrect calculation on P256 curves in crypto/internal/nistec | go1.19.7、go1.20.2 |
| GO-2023-1571 | CVE-2022-41723 | Denial of service via crafted HTTP/2 stream in net/http and golang.org/x/net | go1.19.6、go1.20.1 |
| GO-2023-1570 | CVE-2022-41724 | Panic on large handshake records in crypto/tls | go1.19.6、go1.20.1 |
| GO-2023-1569 | CVE-2022-41725 | Excessive resource consumption in mime/multipart | go1.19.6、go1.20.1 |
| GO-2023-1568 | CVE-2022-41722 | Path traversal on Windows in path/filepath | go1.19.6、go1.20.1 |
本版已停止支援,不會再修正這些漏洞;完整清單見 資安漏洞。