Contextio Save

Context-aware I/O streams (Writer, Reader) for Go

Project README

contextio - Context-aware I/O streams for Go

GoDoc stability: stable codecov Travis-CI Go Report Card

Author: @dolmen (Olivier Mengué).

Example

go test -run ExampleWriter

func main() {
	// interrupt context after 500ms
	ctx, cancel := context.WithTimeout(context.Background(), 500*time.Millisecond)
	defer cancel()
	// interrupt context with SIGTERM (CTRL+C)
	sigs := make(chan os.Signal, 1)
	signal.Notify(sigs, os.Interrupt)
	go func() {
		<-sigs
		cancel()
	}()

	f, err := os.OpenFile(os.DevNull, os.O_WRONLY, 0)
	if err != nil {
		log.Fatal(err)
	}
	defer f.Close()

	// Writer that fails when context is canceled
	out := contextio.NewWriter(ctx, f)

	// Infinite loop. Will only be interrupted once write fails.
	for {
		if _, err := out.Write([]byte{'a', 'b', 'c'}); err != nil {
			fmt.Println("Err:", err)
			break
		}
	}

	fmt.Println("Closing.")
}

See Also

Open Source Agenda is not affiliated with "Contextio" Project. README Source: dolmen-go/contextio
Stars
48
Open Issues
1
Last Commit
1 year ago
Repository
License

Open Source Agenda Badge

Open Source Agenda Rating