Skip to content

Instantly share code, notes, and snippets.

@mortymacs
Created August 21, 2022 07:22
Show Gist options
  • Save mortymacs/6ecd6b6424b40adf1de659ef7f15516b to your computer and use it in GitHub Desktop.
Save mortymacs/6ecd6b6424b40adf1de659ef7f15516b to your computer and use it in GitHub Desktop.
Sample enableIf in Go
package main
import "log"
// types.
type Fn func(id string, name string) error
// actions.
func Insert(id string, name string) error {
log.Println("Insert ID:", id, " Name:", name)
return nil
}
func Update(id string, name string) error {
log.Println("Update ID:", id, " Name:", name)
return nil
}
func Delete(id string, name string) error {
log.Println("Delete ID:", id, " Name:", name)
return nil
}
func Select(id string, name string) error {
log.Println("Select ID:", id, " Name:", name)
return nil
}
// Pipeline.
type Action struct {
Name string
Fn Fn
}
var Pipeline = []Action{
{Name: "add_user", Fn: Insert},
{Name: "select_user", Fn: EnableIf(Select)},
{Name: "update_user", Fn: Update},
{Name: "select_user", Fn: EnableIf(Select)},
{Name: "delete_user", Fn: Delete},
}
// enable if
// If ID:20 and Name:Root, then enable Select action!
func EnableIf(fn Fn) Fn {
return func(id string, name string) error {
if id == "20" && name == "Root" {
return fn(id, name)
}
return nil
}
}
func main() {
for _, action := range Pipeline {
if err := action.Fn("20", "Root"); err != nil {
log.Println("Action:", action.Name, " failed!")
return
} else {
log.Println("Action:", action.Name, " succeed!")
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment