Golang默认Http Client导致的cannot assign requested address错误

问题表现 重现代码: package main import ( "fmt" "io" "net/http" "time" ) func main() { client := &http.Client{ Timeout: time.Duration(3) * time.Second, } for i := 0; i < 100; i++ { go func() { for { req, _ := http.NewRequest(http.MethodGet, "https://baidu.com", nil) rsp, err := client.Do(req) if err != nil { fmt.Println("request failed", err) continue } rsp.Body.Close() body, err := io.ReadAll(rsp.Body) if err != nil { fmt.Println("read body failed", err) continue } fmt.Println(string(body)) } }() } select {} } 启动后,随着请求越来越多,很快就出现了"cannot assign requested address"错误,服务器出现大量TIME_WAIT连接。 ...

2025-04-29 · 2 min · 529 words · Liudon

解决Golang使用go get安装包后找不到可执行文件的问题

背景 编译流水线代码 go get google.golang.org/protobuf/cmd/protoc-gen-go@latest protoc -I=./zzz --proto_path=./xx --go_out=./abc --go_opt=paths=xx.proto ... go build -o xxx 在go升级到1.20.1版本后,执行报错。 protoc-gen-go: program not found or is not executable 解决 Starting in Go 1.17, installing executables with go get is deprecated. go install may be used instead. In a future Go release, go get will no longer build packages; it will only be used to add, update, or remove dependencies in go.mod. Specifically, go get will act as if the -d flag were enabled. ...

2023-08-17 · 1 min · 195 words · Liudon

Golang解析json的一个问题

业务模块从php迁移到golang下了,最近遇到一个golang下json解析的问题: 请求接口,按返回包字段判断请求成功与否。 伪代码如下: package main import ( "encoding/json" "fmt" ) type Response struct { Code int `json:"code"` Msg string `json:"msg"` } func main() { // 场景1,返回包符合接口要求 str := `{"code":100,"msg":"failed"}` var res Response json.Unmarshal([]byte(str), &res) fmt.Printf("res=%+v\n", res) // 解析正确,符合预期 // res={Code:100 Msg:failed} // 场景2,返回包不符合接口要求,缺少相关字段 str = `{"retCode":100,"retMsg":"failed"}` var res1 Response json.Unmarshal([]byte(str), &res1) fmt.Printf("res=%+v\n", res1) // 解析错误,不符合预期 // res={Code:0 Msg:} } 这里由于接口地址配置错误,导致请求到其他接口,返回包不符合协议要求。 ...

2022-05-20 · 1 min · 424 words · Liudon