Sovereign 8s.is mirror of standardgalactic/go-safe
- Go 100%
| Filename | Latest commit message | Latest commit date |
|---|---|---|
|
|
||
| .github/workflows | ||
| go.mod | ||
| LICENSE | ||
| README.md | ||
| safe.go | ||
| safe_test.go | ||
go-safe
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)
}
}