Singleton Modules

I was planning to build an app inside caddy. Need help to figure out this use case.

I want to make a module which will have a single instance in the entire process. This module needs to expose some methods which could be used by several other modules.

Example -
Make a database module to perform crud operations

Several other modules like RBAC and user management will use this module. The default implementation will create one instance of the database module for each host module. I can’t do that for obvious reasons.

My first preference would be to embed caddy into my app, but it seems like v2 favors the opposite.

Yeah, so “apps” are typically singletons in Caddy. I don’t think it’s actually possible to have multiple instances of an app, due to the way Caddy is configured, where the apps are keys in the JSON. For example:

    "apps": {
        "http": {

So it doesn’t really permit you to have more than one of the same app.

I assume you’ve read this section?

1 Like

Yes. I understand this. But can i import an app in a module or another app?

Yes, as long as there aren’t import cycles. For example:

1 Like

Wow. This is absolutely Insane. I love the fact that we’ve tried to use the standard go constructs (like the http.Handler). Great work!!!

Last question. How do you recommend building a custom endpoint in Caddy? Should it be an implementation of http.Handler module or and out of process sidecar which then configures my app and modules in caddy? Or maybe there’s another way?

An HTTP handler is probably the right way so that you can plug it into the middleware pipeline and use matchers to route, but you may have the handler reach out to your app to do the “work” if you need a singleton (cause you have have multiple of your HTTP handlers in your middleware chain)

1 Like

I’m planning to migrate SpaceCloud’s security module to a Caddy App/module (Security Rules | Space Cloud Docs).

Our security module is capable of doing authorisation based on jwt tokens and database query & webhook results. It can even encrypt, hash, decrypt fields if need be. Only works for json payloads however.

Let me know if this is something which sounds interesting to you guys.

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.