Skip to content

Instantly share code, notes, and snippets.

@mcastelino
Last active March 30, 2021 23:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mcastelino/267ae5da60ae5f52802b72822b888ef3 to your computer and use it in GitHub Desktop.
Save mcastelino/267ae5da60ae5f52802b72822b888ef3 to your computer and use it in GitHub Desktop.
Golang: Create a Acyclic function graph
package main
import (
"fmt"
)
// Data that flows through the processing pipeline
type Data struct {
Type string
Data string
}
// The Handler function processes the data and then
// call the handlers downstream from itself
// Each downstream function gets its own copy of the data
type Handler func(Data) error
type HandlerChain interface {
Chain([]Handler) Handler
}
type Node struct {
Name string
}
func (n *Node) Chain(h ...Handler) Handler {
return func(d Data) error {
downstreamHandlers := h
d.Data = d.Data + "->" + n.Name
for _, f := range downstreamHandlers {
if f == nil {
fmt.Println(d.Data)
return nil
}
if err := f(d); err != nil {
return err
}
}
return nil
}
}
func main() {
a := Node{"A"}
b := Node{"B"}
c := Node{"C"}
d := Node{"D"}
e := Node{"E"}
f := Node{"F"}
path1 := b.Chain(c.Chain(nil))
path2 := d.Chain(d.Chain(e.Chain(nil)))
path3 := f.Chain(path1, path2)
tree := a.Chain(path1, path2, path3)
tree(Data{Data: "hello"})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment