📚 contextplus - Awesome Go Library for Utilities

Go Gopher mascot for contextplus

Package contextplus provide more easy to use functions for contexts.

🏷️ Utilities
📂 General utilities and tools to make your life easier.
16 stars
View on GitHub 🔗

Detailed Description of contextplus

Go Report Card PkgGoDev Go package codecov Mentioned in Awesome Go

contextplus

Package contextplus provide more easy to use functions for contexts.

Use

go get -u github.com/contextplus/contextplus

Example

This is how an http.Handler should run a goroutine that need values from the context. Pretend to use the middleware that timeout after one second.

func myMiddleware(next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		ctx := r.Context()
		ctx, cancel := context.WithTimeout(time.Second)
		defer cancel()
		r = r.WithContext(ctx)
		next.ServeHTTP(w, r)
	})
}
func handle(w http.ResponseWriter, r *http.Request) {
	asyncCtx := contextplus.WithOnlyValue(r.Context())
	go func() {
		// will not cancel if timeout
		// will not cancel if call 'cancel'
		asyncTask(asyncCtx)
	}()
}
func handle(w http.ResponseWriter, r *http.Request) {
	asyncCtx := contextplus.WithoutCancel(r.Context())
	go func() {
		// will cancel if timeout
		// will not cancel if call 'cancel'
		asyncTask(asyncCtx)
	}()
}