contextplus / contextplus

Package contextplus provide more easy to use functions for contexts.

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

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)
	}()
}

About

Package contextplus provide more easy to use functions for contexts.

License:MIT License


Languages

Language:Go 100.0%