Hero Image
善用 Go Fuzzing,幫助你寫出更完整的單元測試

善用 Go Fuzzing,幫助你寫出更完整的單元測試 func Pow(base uint, exponent uint) uint { if exponent == 0 { return 1 } return base * Pow(base, exponent-1) } func FuzzPow(f *testing.F) { f.Fuzz(func(t *testing.T, x, y uint) { assert := assert.New(t) assert.Equal(Pow(x, 0), uint(1)) assert.Equal(Pow(x, 1), x) assert.Equal(Pow(x, 2), x*x) if x > 0 && y > 0 { assert.Equal(Pow(x, y)/x, Pow(x, y-1)) } }) } go test -fuzz=Fuzz -fuzztime 20s 在做 Fuzzing Test 的時候如果跑一跑 FAIL 了,Go 會幫忙把那組 input 記在 testcase/ 裡面 看了之後會發現在 x=6、y=30 時 assert 會失敗,也就是說 pow(6, 30)/6 不會等於 pow(6, 29)。但這也太奇怪了吧?仔細實驗之後才發現是因為在計算 pow(6, 30) 的時候會發生 overflow。 因為 Go 定義的 max.MaxUint 大約是 18 * 10¹⁸,但 6²⁹ 大概是 7 * 10¹⁸。如果把 6²⁹ 再乘上 6,就會發生 overflow 得到 8 * 10¹⁸,很像繞了操場兩圈結果在跟原本差不多的位置。 var ErrOverflow = fmt.Errorf("overflow") func Pow(base uint, exponent uint) (uint, error) { if exponent == 0 { return 1 } prevResult, err := Pow(base, exponent-1) if math.MaxUint/base < prevResult { return 0, ErrOverflow } return base * prevResult, nil } func FuzzPow(f *testing.F) { f.Fuzz(func(t *testing.T, x, y uint) { assert := assert.New(t) if result, err := Pow(x, 1); err != ErrOverflow { assert.Equal(result, x) } if result, err := Pow(x, y); x > 0 && y > 0 && err != ErrOverflow { resultDivX, _ := Pow(x, y-1) assert.Equal(result/x, resultDivX) } }) }

Hero Image
Go string format

Go string format The verb at the end defines the type and the interpretation of its corresponding argument. d - decimal integer o - octal integer O - octal integer with 0o prefix b - binary integer x - hexadecimal integer lowercase X - hexadecimal integer uppercase f - decimal floating point, lowercase F - decimal floating point, uppercase e - scientific notation (mantissa/exponent), lowercase E - scientific notation (mantissa/exponent), uppercase g - the shortest representation of %e or %f G - the shortest representation of %E or %F c - a character represented by the corresponding Unicode code point q - a quoted character U - Unicode escape sequence t - the word true or false s - a string v - default format #v - Go-syntax representation of the value T - a Go-syntax representation of the type of the value p - pointer address % - a double %% prints a single % Go string format indexing package main import ( "fmt" ) func main() { n1 := 2 n2 := 3 n3 := 4 res := fmt.Sprintf("There are %d oranges %d apples %d plums", n1, n2, n3) fmt.Println(res) // There are 2 oranges 3 apples 4 plums res2 := fmt.Sprintf("There are %[2]d oranges %d apples %[1]d plums", n1, n2, n3) fmt.Println(res2) // There are 3 oranges 4 apples 2 plums } Go string format precision package main import ( "fmt" ) func main() { fmt.Printf("%0.f\n", 16.540) // 17 fmt.Printf("%0.2f\n", 16.540) // 16.54 fmt.Printf("%0.3f\n", 16.540) // 16.540 fmt.Printf("%0.5f\n", 16.540) // 16.54000 } Go string format flags package main import ( "fmt" ) func main() { fmt.Printf("%+d\n", 1691) // +1691 fmt.Printf("%#x\n", 1691) // 0x69b fmt.Printf("%#X\n", 1691) // 0X69B fmt.Printf("%#b\n", 1691) // 0b11010011011 fmt.Printf("%10d\n", 1691) // 1691 fmt.Printf("%-10d\n", 1691) // 1691 fmt.Printf("%010d\n", 1691) // 0000001691 } Go string format width package main import ( "fmt" ) func main() { w := "falcon" n := 122 h := 455.67 fmt.Printf("%s\n", w) // falcon fmt.Printf("%10s\n", w) // falcon fmt.Printf("%d\n", n). // 122 fmt.Printf("%7d\n", n) // 122 fmt.Printf("%07d\n", n) // 0000122 fmt.Printf("%10f\n", h) // 455.670000 fmt.Printf("%11f\n", h) // 455.670000 fmt.Printf("%12f\n", h) // 455.670000 }

Hero Image
golang pprof 实战

golang pprof 实战 炸弹程序 package main import ( // 略 _ "net/http/pprof" // 会自动注册 handler 到 http server,方便通过 http 接口获取程序运行采样报告 // 略 ) func main() { // 略 runtime.GOMAXPROCS(1) // 限制 CPU 使用数,避免过载 runtime.SetMutexProfileFraction(1) // 开启对锁调用的跟踪 runtime.SetBlockProfileRate(1) // 开启对阻塞操作的跟踪 go func() { // 启动一个 http server,注意 pprof 相关的 handler 已经自动注册过了 // /debug/pprof/ if err := http.ListenAndServe(":6060", nil); err != nil { log.Fatal(err) } os.Exit(0) }() // 略 } http://localhost:6060/debug/pprof/ 类型 描述 备注 allocs 内存分配情况的采样信息 可以用浏览器打开,但可读性不高 blocks 阻塞操作情况的采样信息 可以用浏览器打开,但可读性不高 cmdline 显示程序启动命令及参数 可以用浏览器打开,这里会显示 ./go-pprof-practice goroutine 当前所有协程的堆栈信息 可以用浏览器打开,但可读性不高 heap 堆上内存使用情况的采样信息 可以用浏览器打开,但可读性不高 mutex 锁争用情况的采样信息 可以用浏览器打开,但可读性不高 profile CPU 占用情况的采样信息 浏览器打开会下载文件 threadcreate 系统线程创建情况的采样信息 可以用浏览器打开,但可读性不高 trace 程序运行跟踪信息 浏览器打开会下载文件,本文不涉及,可另行参阅《深入浅出 Go trace》 排查 CPU 占用过高

Hero Image
Gin 框架绑定 JSON 参数使用 jsoniter

Gin 框架绑定 JSON 参数使用 jsoniter simple go build -tags=jsoniter ./... custom implement BindingBody interface // github.com/gin-gonic/gin@v1.6.3/binding/binding.go:36 // Binding describes the interface which needs to be implemented for binding the // data present in the request such as JSON request body, query parameters or // the form POST. type Binding interface { Name() string Bind(*http.Request, interface{}) error } // BindingBody adds BindBody method to Binding. BindBody is similar with Bind, // but it reads the body from supplied bytes instead of req.Body. type BindingBody interface { Binding BindBody([]byte, interface{}) error } package custom import ( "bytes" "fmt" "io" "net/http" jsoniter "github.com/json-iterator/go" "github.com/gin-gonic/gin/binding" ) // BindingJSON 替换Gin默认的binding,支持更丰富JSON功能 var BindingJSON = jsonBinding{} // 可以自定义jsoniter配置或者添加插件 var json = jsoniter.ConfigCompatibleWithStandardLibrary type jsonBinding struct{} func (jsonBinding) Name() string { return "json" } func (jsonBinding) Bind(req *http.Request, obj interface{}) error { if req == nil || req.Body == nil { return fmt.Errorf("invalid request") } return decodeJSON(req.Body, obj) } func (jsonBinding) BindBody(body []byte, obj interface{}) error { return decodeJSON(bytes.NewReader(body), obj) } func decodeJSON(r io.Reader, obj interface{}) error { decoder := json.NewDecoder(r) if binding.EnableDecoderUseNumber { decoder.UseNumber() } if binding.EnableDecoderDisallowUnknownFields { decoder.DisallowUnknownFields() } if err := decoder.Decode(obj); err != nil { return err } return validate(obj) } func validate(obj interface{}) error { if binding.Validator == nil { return nil } return binding.Validator.ValidateStruct(obj) } // binding.JSON 替换成自定义的 ctx.ShouldBindWith(ms, binding.JSON) ctx.ShouldBindBodyWith(ms, binding.JSON)