Sovereign 8s.is mirror of standardgalactic/go-safe
Find a file
Repository files (latest commit first)
Filename Latest commit message Latest commit date
Kenkyu a1c4030001
Some checks failed
Go / test (push) Has been cancelled
Update
2021-11-30 16:58:25 +09:00
.github/workflows Update CI 2021-11-30 16:53:54 +09:00
go.mod Add 2019-10-30 00:22:28 +09:00
LICENSE Initial commit 2019-10-30 00:20:37 +09:00
README.md Update 2021-11-30 16:58:25 +09:00
safe.go Add 2019-10-30 00:22:28 +09:00
safe_test.go Cleanup 2021-05-13 23:01:17 +09:00

go-safe

test codecov go.dev reference go report card license Mentioned in Awesome Go

This Go package provides a sandbox for the safe execution of panic-inducing programs.

This package is intended for use in development and unit testing, and is not recommended for use in production.

Installation

go get -u github.com/kenkyu392/go-safe

Usage

package main

import (
	"log"

	"github.com/kenkyu392/go-safe"
)

func main() {
	// The panic that occurs in the function is automatically handled as an error.
	if err := safe.Do(func() error {
		// Something that might cause a panic...
		return nil
	}); err != nil {
		log.Fatal(err)
	}
}

The sandbox function can be used in combination with sync/errgroup.

package main

import (
	"log"

	"github.com/kenkyu392/go-safe"
	"golang.org/x/sync/errgroup"
)

func main() {
	// Create a sandboxed function.
	fn := safe.Func(func() error {
		// Something that might cause a panic...
		return nil
	})

	eg := new(errgroup.Group)
	for i := 0; i < 10; i++ {
		eg.Go(fn)
	}
	if err := eg.Wait(); err != nil {
		log.Fatal(err)
	}
}

License

MIT