{"id":20578332,"url":"https://github.com/mikestefanello/hooks","last_synced_at":"2025-07-30T18:09:57.282Z","repository":{"id":58752517,"uuid":"532538749","full_name":"mikestefanello/hooks","owner":"mikestefanello","description":"Simple, type-safe hook system to enable easier modularization of your Go code.","archived":false,"fork":false,"pushed_at":"2022-09-14T21:30:24.000Z","size":32,"stargazers_count":96,"open_issues_count":0,"forks_count":3,"subscribers_count":3,"default_branch":"main","last_synced_at":"2025-05-28T23:04:11.588Z","etag":null,"topics":["decoupling","generics","go","golang","hook","hooks","lifecycle-hooks","module","type-safe","typesafe"],"latest_commit_sha":null,"homepage":"","language":"Go","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/mikestefanello.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2022-09-04T12:48:31.000Z","updated_at":"2025-04-14T04:38:04.000Z","dependencies_parsed_at":"2023-01-18T08:01:10.251Z","dependency_job_id":null,"html_url":"https://github.com/mikestefanello/hooks","commit_stats":null,"previous_names":[],"tags_count":1,"template":false,"template_full_name":null,"purl":"pkg:github/mikestefanello/hooks","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/mikestefanello%2Fhooks","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/mikestefanello%2Fhooks/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/mikestefanello%2Fhooks/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/mikestefanello%2Fhooks/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/mikestefanello","download_url":"https://codeload.github.com/mikestefanello/hooks/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/mikestefanello%2Fhooks/sbom","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":267914753,"owners_count":24164783,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","status":"online","status_checked_at":"2025-07-30T02:00:09.044Z","response_time":70,"last_error":null,"robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":true,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["decoupling","generics","go","golang","hook","hooks","lifecycle-hooks","module","type-safe","typesafe"],"created_at":"2024-11-16T06:12:27.652Z","updated_at":"2025-07-30T18:09:57.248Z","avatar_url":"https://github.com/mikestefanello.png","language":"Go","funding_links":[],"categories":[],"sub_categories":[],"readme":"# Hooks\n\n[![Go Report Card](https://goreportcard.com/badge/github.com/mikestefanello/hooks)](https://goreportcard.com/report/github.com/mikestefanello/hooks)\n[![Test](https://github.com/mikestefanello/hooks/actions/workflows/test.yml/badge.svg)](https://github.com/mikestefanello/hooks/actions/workflows/test.yml)\n[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)\n[![Go Reference](https://pkg.go.dev/badge/github.com/mikestefanello/hooks.svg)](https://pkg.go.dev/github.com/mikestefanello/hooks)\n[![GoT](https://img.shields.io/badge/Made%20with-Go-1f425f.svg)](https://go.dev)\n\n## Overview\n\n_Hooks_ provides a simple, **type-safe** hook system to enable easier modularization of your Go code. A _hook_ allows various parts of your codebase to tap into events and operations happening elsewhere which prevents direct coupling between the producer and the consumers/listeners. For example, a _user_ package/module in your code may dispatch a _hook_ when a user is created, allowing your _notification_ package to send the user an email, and a _history_ package to record the activity without the _user_ module having to call these components directly. A hook can also be used to allow other modules to alter and extend data before it is processed.\n\nHooks can be very beneficial especially in a monolithic application both for overall organization as well as in preparation for the splitting of modules into separate synchronous or asynchronous services.\n\n## Installation\n\n`go get github.com/mikestefanello/hooks`\n\n## Usage\n\n1) Start by declaring a new hook which requires specifying the _type_ of data that it will dispatch as well as a name. This can be done in a number of different way such as a global variable or exported field on a _struct_:\n\n```go\npackage user\n\ntype User struct {\n    ID int\n    Name string\n    Email string\n    Password string\n}\n\nvar HookUserInsert = hooks.NewHook[User](\"user.insert\")\n```\n\n2) Listen to a hook:\n\n```go\npackage greeter\n\nfunc init() {\n    user.HookUserInsert.Listen(func(e hooks.Event[user.User]) {\n        sendEmail(e.Msg.Email)\n    })\n}\n```\n\n3) Dispatch the data to the hook _listeners_:\n\n```go\nfunc (u *User) Insert() {\n    db.Insert(\"INSERT INTO users ...\")\n\n    HookUserInsert.Dispatch(\u0026u)\n}\n```\n\nOr, dispatch all listeners asynchronously with `HookUserInsert.DispatchAsync(u)`.\n\n### Things to know\n\n- The `Listen()` callback does not have to be an anonymous function. You can also do:\n\n```go\npackage greeter\n\nfunc init() {\n    user.HookUserInsert.Listen(onUserInsert)\n}\n\nfunc onUserInsert(e hooks.Event[user.User]) {\n    sendEmail(e.Msg.Email)\n}\n```\n\n- If you are using `init()` to register your hook listeners and your package isn't being imported elsewhere, you need to import it in order for that to be executed. You can simply include something like `import _ \"myapp/greeter\"` in your `main` package.\n- The `hooks.Event[T]` parameter contains the data that was passed in at `Event.Msg` and the hook at `Event.Hook`. Having the hook available in the listener means you can use a single listener for multiple hooks, ie:\n\n```go\nHookOne.Listen(listener)\nHookTwo.Listen(listener)\n\nfunc listener(e hooks.Event[SomeType]) {\n    switch e.Hook {\n    case HookOne:\n    case HookTwo:\n    }\n}\n```\n\n- If the `Msg` is provided as a _pointer_, a hook can modify the the data which can be useful to allow for modifications prior to saving a user, for example.\n- You do not have to use `init()` to listen to hooks. For example, another pattern for this example could be:\n\n```go\npackage greeter\n\ntype Greeter struct {\n    emailClient email.Client\n}\n\nfunc NewGreeter(client email.Client) *Greeter {\n    g := \u0026Greeter{emailClient: client}\n    \n    user.HookUserInsert.Listen(func (e hooks.Event[user.User]) {\n        g.sendEmail(e.Msg.Email)\n    })\n    \n    return g\n}\n```\n\n- Following the previous example, hooks can be provided as part of exported _structs_ rather than just global variables, for example:\n\n```go\npackage greeter\n\ntype Greeter struct {\n    HookSendEmail *hooks.Hook[Email]\n    emailClient email.Client\n}\n\nfunc NewGreeter(client email.Client) *Greeter {\n    g := \u0026Greeter{emailClient: client}\n\n    user.HookUserInsert.Listen(func (e hooks.Event[user.User]) {\n        g.sendEmail(e.Msg.Email)\n    })\n\n    return g\n}\n\nfunc (g *Greeter) sendEmail(email string) error {\n    e := Email{To: email}\n    if err := g.emailClient.Send(e); err != nil {\n        return err\n    }\n\n    g.HookSendEmail.Dispatch(e)\n}\n```\n\n## More examples\n\nWhile event-driven usage as shown above is the most common use-case of hooks, they can also be used to extend functionality and logic or the process in which components are built. Here are some more examples.\n\n### Router construction\n\nIf you're building a web service, it could be useful to separate the registration of each of your module's endpoints. Using [Echo](https://github.com/labstack/echo) as an example:\n\n```go\npackage main\n\nimport (\n    \"github.com/labstack/echo/v4\"\n    \"github.com/myapp/router\"\n    \n    // Modules\n    _ \"github.com/myapp/modules/todo\"\n    _ \"github.com/myapp/modules/user\"\n)\n\nfunc main() {\n    e := echo.New()\n    router.BuildRouter(e)\n    e.Start(\"localhost:9000\")\n}\n```\n\n```go\npackage router\n\nimport (\n    \"net/http\"\n    \n    \"github.com/labstack/echo/v4\"\n    \"github.com/labstack/echo/v4/middleware\"\n    \"github.com/mikestefanello/hooks\"\n)\n\nvar HookBuildRouter = hooks.NewHook[echo.Echo](\"router.build\")\n\nfunc BuildRouter(e *echo.Echo) {\n    e.Use(\n        middleware.RequestID(),\n        middleware.Logger(),\n    )\n    \n    e.GET(\"/\", func(ctx echo.Context) error {\n        return ctx.String(http.StatusOK, \"hello world\")\n    })\n    \n    // Allow all modules to build on the router\n    HookBuildRouter.Dispatch(e)\n}\n```\n\n```go\npackage todo\n\nimport (\n    \"github.com/labstack/echo/v4\"\n    \"github.com/mikestefanello/hooks\"\n    \"github.com/myapp/router\"\n)\n\nfunc init() {\n    router.HookBuildRouter.Listen(func(e hooks.Event[echo.Echo]) {\n        e.Msg.GET(\"/todo\", todoHandler.Index)\n        e.Msg.GET(\"/todo/:todo\", todoHandler.Get)\n        e.Msg.POST(\"/todo\", todoHandler.Post)\n    })\n}\n```\n\n### Dependency creation (and injection)\n\nRather than inititalize all of your dependencies in a single place, hooks can be used to distribute these tasks to the providing packages and great dependency injection libraries like _[do](https://github.com/samber/do)_ can be used to manage them.\n\n```go\npackage main\n\nimport (\n    \"github.com/mikestefanello/hooks\"\n    \"github.com/samber/do\"\n\n    \"example/services/app\"\n    \"example/services/web\"\n)\n\nfunc main() {\n    i := app.Boot()\n\n    server := do.MustInvoke[*web.Web](i)\n    server.Start()\n}\n```\n```go\npackage app\n\nimport (\n    \"github.com/mikestefanello/hooks\"\n    \"github.com/samber/do\"\n)\n\nvar HookBoot = hooks.NewHook[*do.Injector](\"boot\")\n\nfunc Boot() *do.Injector {\n    injector := do.New()\n    HookBoot.Dispatch(injector)\n    return injector\n}\n```\n\n```go\npackage web\n\nimport (\n    \"net/http\"\n\n    \"github.com/mikestefanello/hooks\"\n    \"github.com/samber/do\"\n\n    \"example/services/app\"\n)\n\ntype (\n    Web interface {\n        Start() error\n    }\n\n    web struct {}\n)\n\nfunc init() {\n    app.HookBoot.Listen(func(e hooks.Event[*do.Injector]) {\n        do.Provide(e.Msg, NewWeb)\n    })\n}\n\nfunc NewWeb(i *do.Injector) (Web, error) {\n    return \u0026web{}, nil\n}\n\nfunc (w *web) Start() error {\n    return http.ListenAndServe(\":8080\", nil)\n}\n```\n\n\n### Modifications\n\nHook listeners can be used to make modifications to data prior to some operation being executed if the _message_ is provided as a pointer. For example, using the `User` from above:\n\n```go\nvar HookUserPreInsert = hooks.NewHook[*User](\"user.pre_insert\")\n\nfunc (u *User) Insert() {\n    // Let other modules make any required changes prior to inserting\n    HookUserPreInsert.Dispatch(u)\n\t\n    db.Insert(\"INSERT INTO users ...\")\n    \n    // Notify other modules of the inserted user\n    HookUserInsert.Dispatch(*u)\n}\n```\n\n```go\nHookUserPreInsert.Listen(func(e hooks.Event[*user.User]) {\n    // Change the user's name\n    e.Msg.Name = fmt.Sprintf(\"%s-changed\", e.Msg.Name)\n})\n```\n\n### Validation\n\nHook listeners can also provide validation or other similar input on data that is being acted on. For example, using the `User` again.\n\n```go\ntype UserValidation struct {\n    User User\n    Errors *[]error\n}\n\nvar HookUserValidate = hooks.NewHook[UserValidation](\"user.validate\")\n\nfunc (u *User) Validate() []error {\n    errs := make([]error, 0)\n    uv := UserValidation{\n        User:   *u,\n        Errors: \u0026errs,\n    }\n\n    if u.Email == \"\" {\n        uv.Errors = append(uv.Errors, errors.New(\"missing email\"))\n    }\n    \n    // Let other modules validate\n    HookUserValidate.Dispatch(uv)\n\t\n    return uv.Errors\n}\n```\n\n```go\nHookUserValidate.Listen(func(e hooks.Event[user.UserValidate]) {\n    if len(e.Msg.User.Password) \u003c 10 {\n        e.Msg.Errors = append(e.Msg.Errors, errors.New(\"password too short\"))\n    }\n})\n```\n\n### Full application example\n\nFor a full application example see [hooks-example](https://github.com/mikestefanello/hooks-example). This aims to provide a modular monolithic architectural approach to a Go application using _hooks_ and [do](https://github.com/samber/do) _(dependency injection)_.\n\n## Logging\n\nBy default, nothing will be logged, but you have the option to specify a _logger_ in order to have insight into what is happening within the hooks. Pass a function in to `SetLogger()`, for example:\n\n```go\nhooks.SetLogger(func(format string, args ...any) {\n    log.Printf(format, args...)\n})\n```\n\n```\n2022/09/07 13:42:19 hook created: user.update\n2022/09/07 13:42:19 registered listener with hook: user.update\n2022/09/07 13:42:19 registered listener with hook: user.update\n2022/09/07 13:42:19 registered listener with hook: user.update\n2022/09/07 13:42:19 dispatching hook user.update to 3 listeners (async: false)\n2022/09/07 13:42:19 dispatch to hook user.update complete\n```","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fmikestefanello%2Fhooks","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fmikestefanello%2Fhooks","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fmikestefanello%2Fhooks/lists"}