Skip to content
This repository has been archived by the owner on Jan 25, 2024. It is now read-only.

fxrlv/detach

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

5 Commits
 
 
 
 
 
 
 
 

Repository files navigation

detach Go Reference

package main

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

	"github.com/fxrlv/detach"
)

func main() {
	main, cancel := signal.NotifyContext(
		context.Background(), os.Interrupt,
	)
	defer cancel()

	http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		// For incoming server requests, the context is canceled when the
		// client's connection closes, the request is canceled (with HTTP/2),
		// or when the ServeHTTP method returns.
		ctx := r.Context()

		ctx = detach.WithCancel(ctx, main)
		go func() {
			// Will be cancelled by signal.
			<-ctx.Done()

			// Values are associated with http.Request context.
			server := ctx.Value(http.ServerContextKey).(*http.Server)
			server.Close()
		}()
	})

	http.ListenAndServe(":8080", nil)
}

About

No description, website, or topics provided.

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Languages