Plugin System

Wikipedia: Plug-in
Scripts can register named event handlers that the host dispatches when events fire. End users extend application behaviour without touching Go code, and different scripts can register different sets of handlers for the same event bus.

fmt := import("fmt")
handlers := {
    on_user_login: func(e) {
        fmt.printf("login:  %s (admin=%v)\n", e.username, e.is_admin)
        if e.is_admin {
            fmt.println("        → audit log entry written")
        }
    },

    on_order_placed: func(e) {
        total := float(e.price) * float(e.qty)
        fmt.printf("order:  %s ×%d = $%.2f\n", e.item, e.qty, total)
        if total > 500.0 {
            fmt.println("        → fraud review triggered")
        }
    },

    on_user_logout: func(e) {
        fmt.printf("logout: %s\n", e.username)
    },
}
dispatch := func(event, payload) {
    h := handlers[event]
    if is_undefined(h) {
        fmt.printf("(no handler for %q)\n", event)
        return
    }
    h(payload)
}
dispatch("on_user_login",    {username: "alice", is_admin: false})
dispatch("on_user_login",    {username: "root",  is_admin: true})
dispatch("on_order_placed",  {item: "Graphics card", price: 349, qty: 2})
dispatch("on_order_placed",  {item: "Mouse pad",     price: 12,  qty: 1})
dispatch("on_user_logout",   {username: "alice"})
dispatch("on_password_reset",{username: "alice"})

try it

login:  alice (admin=false)
login:  root (admin=true)
        → audit log entry written
order:  Graphics card ×2 = $698.00
        → fraud review triggered
order:  Mouse pad ×1 = $12.00
logout: alice
(no handler for "on_password_reset")
loading…