Hi @sntshk,
A couple of things you can look into:
-
Per our documentation, the
mongo.Clienttype is safe for concurrent use, so if you’re always connecting to the same MongoDB instance, you can create a singleClientand re-use it between handlers rather than creating a new one in each handler. Note that this does come with some overhead, as aClientkeeps a connection pool per node in your MongoDB cluster, so if you perform a lot of concurrent database operations, you could potentially keep around a large connection pool. -
Go allows you to pass a function on a struct as a callback, so you can probably create a struct to store application state and helper functions. That struct could have separate functions for each of your HTTP requests and each handler function should have the signature
func(http.ResponseWriter,*http.Request)so it can be used withHandleFuncin gorilla/mux. -
To go even further into suggestion (2), you could maybe set things up so your struct has a single top-level handler to do common operations like validate the request and then have that call a struct function to handle a specific request type once it’s been validated.
There’s some examples for creating stateful handlers at Custom Handlers and Avoiding Globals in Go Web Applications · questionable services. Specifically, the appContext type discussed there seems similar to what you want. I’d also recommend asking this as a more general question (e.g. “how to create stateful HTTP handlers”) on the Go mailing list or Slack workspace to get advice from others as well.
– Divjot