在我用 golang 编写的 HTTP 应用程序中,我有一些依赖第三方服务(和销售代码)的路由在我实际能够注册路由之前做一些工作。这可能会失败或需要重试,但我仍然希望应用程序在这个过程可能正在进行时响应其他请求。
这意味着我正在从 main
函数生成的 goroutine 中的 http.DefaultServeMux
上注册处理程序。这按预期工作,但我会发现我的测试现在提示数据争用。
重现的最小案例如下所示:
package main
import (
"log"
"net/http"
)
func main() {
go func() {
http.HandleFunc("/hello", func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("hello"))
})
}()
srv := http.Server{
Addr: ":3000",
}
log.Fatal(srv.ListenAndServe())
}
像这样的测试:
package main
import (
"io/ioutil"
"net/http"
"os"
"testing"
"time"
)
func TestMain(m *testing.M) {
go main()
time.Sleep(time.Second)
os.Exit(m.Run())
}
func TestHello(t *testing.T) {
t.Run("default", func(t *testing.T) {
res, err := http.DefaultClient.Get("http://0.0.0.0:3000/hello")
if err != nil {
t.Fatalf("Calling /hello returned %v", err)
}
if res.StatusCode != http.StatusOK {
b, _ := ioutil.ReadAll(res.Body)
defer res.Body.Close()
t.Errorf("Expected /hello to return 200 response, got %v with body %v", res.StatusCode, string(b))
}
})
}
将显示以下输出:
==================
WARNING: DATA RACE
Read at 0x000000a337d8 by goroutine 14:
net/http.(*ServeMux).shouldRedirect()
/usr/local/go/src/net/http/server.go:2239 +0x162
net/http.(*ServeMux).redirectToPathSlash()
/usr/local/go/src/net/http/server.go:2224 +0x64
net/http.(*ServeMux).Handler()
/usr/local/go/src/net/http/server.go:2293 +0x184
net/http.(*ServeMux).ServeHTTP()
/usr/local/go/src/net/http/server.go:2336 +0x6d
net/http.serverHandler.ServeHTTP()
/usr/local/go/src/net/http/server.go:2694 +0xb9
net/http.(*conn).serve()
/usr/local/go/src/net/http/server.go:1830 +0x7dc
Previous write at 0x000000a337d8 by goroutine 8:
net/http.(*ServeMux).Handle()
/usr/local/go/src/net/http/server.go:2357 +0x216
net/http.(*ServeMux).HandleFunc()
/usr/local/go/src/net/http/server.go:2368 +0x62
net/http.HandleFunc()
/usr/local/go/src/net/http/server.go:2380 +0x68
github.com/m90/test.main.func1()
/home/frederik/projects/go/src/github.com/m90/test/main.go:10 +0x4f
Goroutine 14 (running) created at:
net/http.(*Server).Serve()
/usr/local/go/src/net/http/server.go:2795 +0x364
net/http.(*Server).ListenAndServe()
/usr/local/go/src/net/http/server.go:2711 +0xc4
github.com/m90/test.main()
/home/frederik/projects/go/src/github.com/m90/test/main.go:17 +0xb6
Goroutine 8 (finished) created at:
github.com/m90/test.main()
/home/frederik/projects/go/src/github.com/m90/test/main.go:9 +0x46
==================
据我了解阅读the code of package http堆栈跟踪中的 net/http.(*ServeMux).Handler()
不会锁定保护处理程序映射的互斥锁,因为它希望由 net/http.(* ServeMux).handler()
在我的场景中没有被调用。
我是否在做一些不应该做的事情?这是标准库的问题吗?我在 goroutine 中附加处理程序的方式有问题吗?
最佳答案
这似乎是包 http 本身的问题,已解决 via this Pull Request .
截至 2018 年 4 月,该补丁未包含在 go1.10.1
中,但它应该随 go1.11
关于go - 在 goroutine 中添加处理程序时如何防止数据竞争?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50101853/