Comment

Comment by atombender

There's no need to put any dependencies in the context, ever. For HTTP servers, the easiest way is just to use a struct to hold the dependencies:

    type Server struct {
      logger *Logger
      users *UserService
      // etc.
    }
Assuming we use a router like Chi or similar:

    router.Get("/users", srv.HandleUsers)
...where HandleUsers is a method on Server.

Some people like to spread handlers in different packages. You can of course declare handlers as functions with no receiver struct, and pass the data as an argument:

    router.Get("/users", func(w io.ResponseWriter, r *http.Request) {
      userroutes.HandleUsers(srv, w, r)
    })
For middlewares, e.g. something that parses a session cookie and fetches the current user, do exactly the same thing.
parent atombender 3 years ago

Discussion

Live from the official Hacker News API

A modern reader for Hacker News · SvelteKit + Skeleton