Fsm
Finite State Machine for Go
Install / Use
/learn @looplab/FsmREADME
FSM for Go
FSM is a finite state machine for Go.
It is heavily based on two FSM implementations:
-
Javascript Finite State Machine, https://github.com/jakesgordon/javascript-state-machine
-
Fysom for Python, https://github.com/oxplot/fysom (forked at https://github.com/mriehl/fysom)
For API docs and examples see http://godoc.org/github.com/looplab/fsm
Basic Example
From examples/simple.go:
package main
import (
"context"
"fmt"
"github.com/looplab/fsm"
)
func main() {
fsm := fsm.NewFSM(
"closed",
fsm.Events{
{Name: "open", Src: []string{"closed"}, Dst: "open"},
{Name: "close", Src: []string{"open"}, Dst: "closed"},
},
fsm.Callbacks{},
)
fmt.Println(fsm.Current())
err := fsm.Event(context.Background(), "open")
if err != nil {
fmt.Println(err)
}
fmt.Println(fsm.Current())
err = fsm.Event(context.Background(), "close")
if err != nil {
fmt.Println(err)
}
fmt.Println(fsm.Current())
}
Usage as a struct field
From examples/struct.go:
package main
import (
"context"
"fmt"
"github.com/looplab/fsm"
)
type Door struct {
To string
FSM *fsm.FSM
}
func NewDoor(to string) *Door {
d := &Door{
To: to,
}
d.FSM = fsm.NewFSM(
"closed",
fsm.Events{
{Name: "open", Src: []string{"closed"}, Dst: "open"},
{Name: "close", Src: []string{"open"}, Dst: "closed"},
},
fsm.Callbacks{
"enter_state": func(_ context.Context, e *fsm.Event) { d.enterState(e) },
},
)
return d
}
func (d *Door) enterState(e *fsm.Event) {
fmt.Printf("The door to %s is %s\n", d.To, e.Dst)
}
func main() {
door := NewDoor("heaven")
err := door.FSM.Event(context.Background(), "open")
if err != nil {
fmt.Println(err)
}
err = door.FSM.Event(context.Background(), "close")
if err != nil {
fmt.Println(err)
}
}
License
FSM is licensed under Apache License 2.0
http://www.apache.org/licenses/LICENSE-2.0
Related Skills
node-connect
345.4kDiagnose OpenClaw node connection and pairing failures for Android, iOS, and macOS companion apps
frontend-design
104.6kCreate distinctive, production-grade frontend interfaces with high design quality. Use this skill when the user asks to build web components, pages, or applications. Generates creative, polished code that avoids generic AI aesthetics.
openai-whisper-api
345.4kTranscribe audio via OpenAI Audio Transcriptions API (Whisper).
qqbot-media
345.4kQQBot 富媒体收发能力。使用 <qqmedia> 标签,系统根据文件扩展名自动识别类型(图片/语音/视频/文件)。
