A simple easy to use go Finite State Machine library. FSM is a programmatic map of whitelisted transitions, where each transition triggers a synchronous operation within the context of a State.
go get github.com/edge/fsm
// Create new instance of FSM with a context
ctx := context.Background()
f := fsm.New().WithContext(ctx)
// FromAny states are useful for transitioning to
// an Error, Shutdown or other universally accessible states.
f.NewState().FromAny().To("ERROR").OnEnter(func(*fsm.State) {
// Do something
})
// Parallel transitions are none blocking.
f.NewState().From("INITIALIZING").To("READY").OnEnter(func(*fsm.State) {
// Do something here
}).Parallel(true)
// FromStart identifies transitions that can come from the launch state.
f.NewState().FromStart().To("READY").OnEnter(func(*fsm.State) {
// Do something here
})
// Each state has a context that is closed before the state changes.
// You can use this with methods called within the state OnEnter method.
f.NewState().From("FETCHING_DATA").To("STARTING_SERVER").OnEnter(func(st *fsm.State) {
doSomething(st.Context())
})
// Run an action before each transition
f.BeforeTransition(func(t *fsm.Transition) {
fmt.Printf(`Transition to %s`, t.To.Destination)
})
f.OnStart(func(st *fsm.State) {
runLaunchCode(st.Context())
})
// Start tells the state machine to enter the initial state.
f.Start()