contextify

package module
v0.0.0-...-1cf786f Latest Latest
Warning

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

Go to latest
Published: Oct 5, 2017 License: MIT Imports: 1 Imported by: 0

README

contextify

contextify is a Go package which provides a utility function to convert a context-unaware run function and a cancel function to a context-aware function.

Documentation

Overview

Package contextify provides a utility function to convert a context-unaware run function and a cancel function to a context-aware function.

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func Contextify

func Contextify(run func() error, cancel func() error,
	pickError func(errFromRun, errFromCancel, errFromContext error) error) func(context.Context) error

Contextify convert a context-unaware run function and a cancel function to a context-aware function.

If context.Context is not cancelled before run() finishes, the return value function waits for run() to be finished and returns the return value of run().

If context.Context is cancelled before run() finishes, the return value function waits for both the run() and cancel() to be finished.

If pickError is nil, the first non-nil error will be retruned of the return value of run(), cancel(), and context.Context.Err(). You can change this behavior with writing a function to pick a desired error and pass it to the pickError argument.

Example
package main

import (
	"context"
	"log"
	"net/http"
	"os"
	"os/signal"

	"github.com/hnakamur/contextify"
)

func main() {
	ctx, cancel := context.WithCancel(context.Background())
	go func() {
		c := make(chan os.Signal, 1)
		signal.Notify(c, os.Interrupt)

		s := <-c
		log.Printf("received signal, %s", s)
		cancel()
		log.Printf("cancelled context")
	}()

	http.HandleFunc("/", func(w http.ResponseWriter, _ *http.Request) {
		w.Write([]byte("Hello, example http server\n"))
	})
	s := http.Server{Addr: ":8080"}
	run := contextify.Contextify(func() error {
		return s.ListenAndServe()
	}, func() error {
		return s.Shutdown(context.Background())
	}, nil)
	err := run(ctx)
	if err != nil {
		log.Printf("got error, %v", err)
	}
	log.Print("exiting")
}
Output:

Types

This section is empty.

Directories

Path Synopsis
example

Jump to

Keyboard shortcuts

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