ctx

package module
v0.0.0-...-7303dbc Latest Latest
Warning

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

Go to latest
Published: Aug 15, 2020 License: MIT Imports: 9 Imported by: 2

Documentation

Overview

Example
package main

import (
	"io"
	"log"
	"time"

	"github.com/zncoder/ctx"
)

func main() {
	cx := ctx.New(nil)
	cx.Close()

	cx = ctx.New(nil).WithTrace("foo/bar")
	cx.Printf("trace an operation")
	cx.Close()

	cx = ctx.New(nil).WithTimeout(time.Millisecond)
	cx.Sleep(time.Hour, time.Hour)
	cx.Close()

	cx = ctx.New(nil).WithLog()
	cx.Printf("log an operation")
	cx.Close()

	cx = ctx.New(nil).WithLog()
	_ = cx.Errorf(io.EOF, "EOF error")
	cx.Close()

	type key1 struct{}
	type key2 struct{}
	cx1 := ctx.New(nil).WithValue(key1{}, "key1")
	cx2 := cx1.WithValue(key2{}, "key2")
	if v1, ok := cx1.Value(key1{}).(string); ok {
		if v1 != "key1" {
			log.Fatal(v1)
		}
	} else {
		log.Fatal("key1 not found")
	}
	if _, ok := cx1.Value(key2{}).(string); ok {
		log.Fatal("key2 shouldn't be found")
	}
	if v1, ok := cx2.Value(key1{}).(string); ok {
		if v1 != "key1" {
			log.Fatal(v1)
		}
	} else {
		log.Fatal("key1 not found")
	}
	if v2, ok := cx2.Value(key2{}).(string); ok {
		if v2 != "key2" {
			log.Fatal(v2)
		}
	} else {
		log.Fatal("key2 not found")
	}

}
Output:

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Context

type Context struct {
	context.Context
}

Context adds tracing to a context. It encapsulates CancelFunc and provides Close to cancel.

func New

func New(parent context.Context) Context

func (Context) Close

func (cx Context) Close()

func (Context) Errorf

func (cx Context) Errorf(err error, format string, args ...interface{}) error

func (Context) PrintSkip

func (cx Context) PrintSkip(skip int, s string)

func (Context) Printf

func (cx Context) Printf(format string, args ...interface{})

func (Context) Sleep

func (cx Context) Sleep(min, max time.Duration)

func (Context) WithLog

func (cx Context) WithLog() Context

WithLog prints trace to log. To help trace, a random tag is chosen and printed in each log line.

func (Context) WithTimeout

func (cx Context) WithTimeout(timeout time.Duration) Context

func (Context) WithTrace

func (cx Context) WithTrace(name string) Context

WithTrace associates trace with cx. Name is "family/title".

func (Context) WithValue

func (cx Context) WithValue(key, value interface{}) Context

Jump to

Keyboard shortcuts

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