safe

package module
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Jul 26, 2023 License: MIT Imports: 4 Imported by: 1

README ¶

A library for safely using go-routine.


elliotxx/safe is a library for safely using go-routine, inspired by safe!

📜 Language

English | 简体中文

âš¡ Usage

go get -u github.com/elliotxx/safe

📚 Examples

package main

import "github.com/elliotxx/safe"

func doSomething() {
	panic("BOOM!")
}

func customRecoverHandler(r interface{}) {
	log.Printf("Recovered from %v", r)
}

func main() {
	// Go starts a recoverable goroutine.
	safe.Go(
		doSomething,
	)

	// GoR starts a recoverable goroutine using given recover handler.
	safe.GoR(
		doSomething,
		customRecoverHandler
	)

	// DefaultHandleCrash simply catches a crash with the default recover handler.
	go func() {
		defer safe.DefaultHandleCrash()
		doSomething()
	}()

	// HandleCrash catches a crash with the custom recover handlers.
	go func() {
		defer safe.HandleCrash(customRecoverHandler)
		doSomething()
	}()
}

Documentation ¶

Index ¶

Constants ¶

This section is empty.

Variables ¶

This section is empty.

Functions ¶

func DefaultHandleCrash ¶

func DefaultHandleCrash()

DefaultHandleCrash simply catches a crash with the default recover handler.

Example:

go func() {
  defer DefaultHandleCrash()
  ...
}()

func Go ¶

func Go(do DoFunc)

Go starts a recoverable goroutine.

Example:

safe.Go(
  func() { ... },
)

func GoR ¶

func GoR(do DoFunc, handlers ...RecoverHandler)

GoR starts a recoverable goroutine using given recover handler.

Example:

safe.GoR(
  func() { ... },
  customRecoverHandler
)

func HandleCrash ¶

func HandleCrash(handlers ...RecoverHandler)

HandleCrash catches a crash with the custom recover handlers.

Example:

go func() {
  defer HandleCrash(customRecoverHandler)
  ...
}()

Types ¶

type DoCtxFunc ¶

type DoCtxFunc func(ctx context.Context)

type DoFunc ¶

type DoFunc func()

type Pool ¶

type Pool struct {
	// contains filtered or unexported fields
}

Pool is a pool of go routines.

func NewPool ¶

func NewPool(parentCtx context.Context) *Pool

NewPool creates a Pool.

func (*Pool) GoCtx ¶

func (p *Pool) GoCtx(do DoCtxFunc)

GoCtx starts a recoverable goroutine with a context.

func (*Pool) Stop ¶

func (p *Pool) Stop()

Stop stops all started routines, waiting for their termination.

func (*Pool) Wait ¶

func (p *Pool) Wait()

Wait waits all started routines.

type RecoverHandler ¶

type RecoverHandler func(r interface{})
var DefaultRecoverHandler RecoverHandler = func(r interface{}) {
	log.Printf("Recovered in goroutine: %s, stack: %s\n", r, debug.Stack())
}

Jump to

Keyboard shortcuts

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