How to Implement a Hook/Event System in Go

Implement a Go hook system by defining a function type, storing callbacks in a slice, and iterating to execute them on events.

Implement a hook system in Go by defining a function type, storing a slice of these functions, and iterating over the slice to invoke them.

package main

import "fmt"

type Hook func(string)

var hooks []Hook

func Register(h Hook) {
	hooks = append(hooks, h)
}

func Fire(event string) {
	for _, h := range hooks {
		h(event)
	}
}

func main() {
	Register(func(s string) { fmt.Println("Hook 1:", s) })
	Register(func(s string) { fmt.Println("Hook 2:", s) })
	Fire("user-logged-in")
}