contextplus

package module
v0.0.0-...-7b87aee Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Mar 20, 2023 License: MIT Imports: 2 Imported by: 0

README

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

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func WithOnlyValue

func WithOnlyValue(ctx context.Context) context.Context

WithOnlyValue returns a copy of parent with hide `cancel` and `deadline`

func WithRebirthCancel

func WithRebirthCancel(ctx context.Context) (context.Context, context.CancelFunc)

WithRebirthCancel returns a copy of parent with hide parent `cancel` and keep `deadline`. The returned context's Done channel is closed when the deadline expires, when the returned cancel function is called

func WithoutCancel

func WithoutCancel(ctx context.Context) context.Context

WithoutCancel returns a copy of parent with hide `cancel` but keep `deadline` The returned context's Done channel is closed when the deadline expires

Types

This section is empty.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL