This is a safe to access from multiple goroutines (concurrency-safe) wrapper for Echo's Context
. The idea of a custom Context
for concurrent access might seem redundant at first, but given a deep thought, there are times when you run goroutines inside an HTTP handler. For projects that heavily make use of goroutines, I wrapped Context
with a mutex to make it safe for concurrent access.
Note: This is experimental.
go get -u github.com/tomruk/cc4echo
func handler(c echo.Context) error {
c = cc4echo.New(c)
// Run your goroutines here...
return nil
}
e := echo.New()
// Make sure that cc4echo's wrapper is registered first.
e.Use(cc4echo.Wrapper())
e.Use(middleware.Logger())
e.Use(middleware.Recover())
e.Start("127.0.0.1:3000")
Context
has functions that are dangerous to be executed from multiple goroutines. For example have a look at Request and SetRequest.
Add the route below to your code and compile with race detector enabled: go build -race
. Then send an HTTP request to it, and see what happens.
func handler(c echo.Context) error {
go func() {
for i := 0; i < 100; i++ {
r := c.Request()
r, _ = http.NewRequest("GET", "/", nil)
c.SetRequest(r)
}
}()
for i := 0; i < 100; i++ {
r := c.Request()
r, _ = http.NewRequest("GET", "/", nil)
c.SetRequest(r)
}
return nil
}
This package is an opt-in solution to this problem.