FSM library to create a finite-state-machine
See: go-fsm Documentation
To start using go-fsm, install Go and run go get
:
$ go get github.com/ThibaultRiviere/go-fsm
import (
"fmt"
"github.com/ThibaultRiviere/go-fsm"
)
func main() {
states := []string{"locked", "close", "open"}
defaultState := "close"
door, err := fsm.New(states, defaultState)
}
// transition name, state needed, next state, handler
door.AddTransition("unlock door", "locked", "close", func() {
fmt.Println("The door have been unlock")
})
currentState, err := door.HandleTransition("unlock door")
if err != nil {
fmt.Println("Couldn't unlock the door because the state is ", currentState)
} else {
fmt.Println("The door state now is ", currentState)
}
If the current state is locked
, then the door will be unlock and the current state will be change to close
.
In case where the current state is not lock then the transition unlock door
will failed returning an error and the current state of the door.
// action name, state needed, handler
door.AddAction("travers door", "open", func() {
fmt.Println("Someone go through the door")
})
err := door.HandleAction("travers door")
if err != nil {
fmt.Println("Impossible to travers the door"
} else {
fmt.Println("New people in the room")
}
If the current state of the door is open
, then it's possible to go through the door and enter in the room.
ErrUnknowState
when using an undefined state
fsm, err := fsm.New([]string{"a", "b"}, "b")
fsm.addAction("oups", "c")
ErrUnknowAction
when using an undefined action
fsm, err := fsm.New([]string{"a", "b"}, "b")
fsm.HandleAction("Action is not define")
ErrUnknowTransition
when using an undefined transition
fsm, err := fsm.New([]string{"a", "b"}, "b")
fsm.HandleTransition("Transition is not define")
ErrBadState
current state is not the state needed for the action/transition
fsm, err := fsm.New([]string{"a", "b"}, "b")
fsm.AddAction("test", "a", func() {
fmt.Println("this is an action")
})
fsm.HandleAction("test")
MIT