I am developing a Caddy middleware plugin with custom authentication logic. The plugin is added to multiple routes. As part of the middleware logic, I need to connect to a postgresql database, but I do not think it is efficient to instantiate a DB connection for each “instance” of the plugin. Is there a recommended way to share a connection among plugin instances, for example a singleton pattern, or something similar?
Great question – yes, definitely just do this once if possible.
You can use a UsagePool to share instances of a DB connection across instances of a module, and even across config reloads that use the same DB connection:
Alternatively, if the UsagePool stuff is too complicated to manage, you could ensure there’s only a single instance of the HTTP handler by using named routes in the config. Obviously this makes the config author responsible for using that feature instead of the plugin itself taking responsibility for pooling the connections, so it’s a tradeoff.