appctx

package module
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Sep 16, 2019 License: MIT Imports: 7 Imported by: 3

README

appctx

GoDoc GitHub release GitHub

Examples

Global
// canceled this context when received os signals for termination
ctx := appctx.Global()
Clone
baseCtx, cancel := context.WithCancel(context.Background())
baseCtx = context.WithValue(baseCtx, "user_id", 123)

newCtx := appctx.Clone(baseCtx)
cancel()

fmt.Println(newCtx.Value("user_id"), baseCtx.Value("user_id")) // => 123 123
fmt.Println(newCtx.Err(), baseCtx.Err()) // => <nil> context canceled

Documentation

Index

Examples

Constants

This section is empty.

Variables

View Source
var (

	// Signals are os signals that are handled by Global context in default.
	Signals = []os.Signal{os.Interrupt, syscall.SIGINT, syscall.SIGTERM}
	// TerminateLimit is a maximum count of received signals until force shutdown.
	TerminateLimit = 3
	// ErrorLog is used for logging received signals.
	ErrorLog Logger = new(defaultLogger)
)

Functions

func Clone

func Clone(base context.Context) context.Context

Clone creates a new Context object but inherits values from the base context object.

Example
package main

import (
	"context"
	"fmt"

	"github.com/srvc/appctx"
)

func main() {
	debug := func(ctx context.Context) {
		fmt.Println(
			"user_id: ", ctx.Value("user_id"), "\t",
			"request_id: ", ctx.Value("request_id"), "\t",
			"error: ", ctx.Err(),
		)
	}

	baseCtx, cancel := context.WithCancel(context.Background())
	baseCtx = context.WithValue(baseCtx, "user_id", 123)
	baseCtx = context.WithValue(baseCtx, "request_id", "7de4f345-8a68-47bc-a1df-90299f95d753")

	newCtx := appctx.Clone(baseCtx)
	cancel()

	debug(baseCtx)
	debug(newCtx)
}
Output:

user_id:  123 	 request_id:  7de4f345-8a68-47bc-a1df-90299f95d753 	 error:  context canceled
user_id:  123 	 request_id:  7de4f345-8a68-47bc-a1df-90299f95d753 	 error:  <nil>

func Global

func Global() context.Context

Global returns a singleton application-scope context that handles termination signals.

func WithSignal

func WithSignal(parent context.Context, sigs ...os.Signal) (context.Context, context.CancelFunc)

WithSignal returns a copy of parent which is done with os signals.

Types

type Logger

type Logger interface {
	Print(v ...interface{})
	Fatal(v ...interface{})
}

Jump to

Keyboard shortcuts

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