A simple finite state machine in Go that is safe for concurrent use
Go

README.md

go-fsm

TravisCI Build Status GoDoc

fsm is a finite state machine written in Go. This package aims to be very simple, while making it easy to maintain predictable state.

License

This code is released for use under the MIT License, of which the full contents can be found within the LICENSE file.

This license is extremely permissve, and should allow the full use of this code in almost all situations. When in doubt, consult a lawyer.

Installation

go get github.com/theckman/go-fsm

Usage

The purpose of the machine is to be a field within your struct. You then interact with the machine to enforce the state of struct. For the full API documentation, check out the GoDoc page. Here's an example of a machine with some states you can transition between:

import "github.com/theckman/go-fsm"

type T struct {
    M *fsm.Machine
}

func main() {
    t := &T{M: &fsm.Machine{}}

    // add initial rule
    err := t.M.AddStateTransitionRules("started", "finished", "aborted", "exited")

    if err != nil {
        // handle
    }

    // add rest of rules
    t.M.AddStateTransitionRules("aborted", "started")
    t.M.AddStateTransitionRules("finished", "started")
    t.M.AddStateTransitionRules("exited") // final state

    // set initial state
    err = t.M.StateTransition("aborted") // nil

    // get the current state
    state := t.M.CurrentState() // "aborted"

    // try to transition to an non-whitelisted state
    err = t.M.StateTransition("finished") // ErrTransitionNotPermitted

    // try to transition to a permitted state
    err = t.M.StateTransition("started") // nil
}