What's new in Go 1.21 and 1.22
19 Fev 2024
Mauri de Souza Meneguzzo
19 Fev 2024
Mauri de Souza Meneguzzo
govulncheck cmd
go install golang.org/x/vuln/cmd/govulncheck@latest
govulncheck ./...
Vulnerability #1: GO-2023-2102
HTTP/2 rapid reset can cause excessive work in net/http
More info: https://pkg.go.dev/vuln/GO-2023-2102
Module: golang.org/x/net
Found in: golang.org/x/[email protected]
Fixed in: golang.org/x/[email protected]
Example traces found:
#1: main.go:34:16: server.main calls gin.Engine.Run, which eventually calls
http2.Server.ServeConn
6
$ go version
go version devel go1.23-af5943f90c Sat Feb 17 23:25:55 2024 +0000 darwin/arm64
$ go env -w GOTOOLCHAIN=go1.22.0
$ go version
go version go1.22.0 darwin/arm64
7
# tests or benchmarks
go test -cpuprofile=cpu.prof -bench=. .
# net/http/pprof
go tool pprof http://localhost:6060/debug/pprof/profile
# runtime/pprof
pprof.StartCPUProfile(f)
defer pprof.StopCPUProfile()
10
package main
func main() { for i := range 5 { println(i) } }
func BenchA(b *testing.B) {
for i := 0; i < b.N; i++ {
// ...
}
}
func BenchB(b *testing.B) {
for range b.N {
// ...
}
}
12
iter.Seq/iter.Seq2
package iter // import "iter"
// Seq is an iterator over sequences of individual values.
// When called as seq(yield), seq calls yield(v) for each value v
// in the sequence, stopping early if yield returns false.
type Seq[V any] func(yield func(V) bool)
// Seq2 is an iterator over sequences of pairs of values, most commonly
// key-value pairs. When called as seq(yield), seq calls yield(k, v) for each
// pair (k, v) in the sequence, stopping early if yield returns false.
type Seq2[K, V any] func(yield func(K, V) bool)
13
package main import "iter" func main() { var mySeq iter.Seq[int] mySeq = func(yield func(n int) bool) { for i := 0; i < 5; i++ { if !yield(i) { return } } } for v := range mySeq { println(v) } }
$ go install golang.org/x/tools/cmd/deadcode@latest
$ deadcode ./...
15
# implicit, simpler syntax
slog.Info("User logged in", "username", user.Name, "userid", user.ID)
# explicit, less memory allocs
slog.LogAttrs(context.Background(), slog.LevelInfo, "User logged in",
slog.String("username", user.Name), slog.Int("userid", user.ID))
# zap for comparison
zapLogger.Info("User logged in",
zap.String("username", user.Name),
zap.Int("userid", user.ID))
17
First V2 package in the stdlib
Read removed. Many people misused math/rand.Read as a secure random source instead of crypto/rand.Read
Outdated, slow algorithms in math/rand
//go:linkname Uint32 runtime.fastrand
func Uint32() uint32
//go:linkname Uint32n runtime.fastrandn
func Uint32n(n uint32) uint32
18
http.Handle("GET /posts/{id}", handlePost2)
// ...
idString := req.PathValue("id")
19
The Go home page.
My talks are written with golang.org/x/tools/present
Find this talk at talks.mauri870.com
23