Skip to content

tomruk/cc4echo

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

9 Commits
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Concurrency-Safe Context for Echo

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.

Usage

go get -u github.com/tomruk/cc4echo

Replace Context in place:

func handler(c echo.Context) error {
	c = cc4echo.New(c)
	// Run your goroutines here...
	return nil
}

Or use middleware:

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")

Why?

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.

About

No description, website, or topics provided.

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages