Build Caddy with modules in devenv shell

Oh wow, this turned out to be a lot simpler than I anticipated :smiley: Thanks so much!

I ended up with the following devenv (left out the irrelevant parts), just in case someone else is thinking about doing the same thing:

{ pkgs, config, ... }:

let
    caddy = with pkgs; stdenv.mkDerivation rec {
        pname = "caddy";
        version = "2.6.2";
        dontUnpack = true;

        nativeBuildInputs = [ git go xcaddy ];

        plugins = [
            "github.com/dunglas/mercure@v0.14.4"
            "github.com/dunglas/mercure/caddy@ddcf0045223c6f3fcc8be21fba3414bbbf2af730"
        ];

        configurePhase = ''
            export GOCACHE=$TMPDIR/go-cache
            export GOPATH="$TMPDIR/go"
        '';

        buildPhase = let
          pluginArgs = lib.concatMapStringsSep " " (plugin: "--with ${plugin}") plugins;
        in ''
          runHook preBuild
          ${xcaddy}/bin/xcaddy build "v${version}" ${pluginArgs}
          runHook postBuild
        '';

        installPhase = ''
          runHook preInstall
          mkdir -p $out/bin
          mv caddy $out/bin
          runHook postInstall
        '';
    };
in
{

    services.caddy.package = caddy;
    services.caddy.enable = true;
    services.caddy.config = ''
        {
            debug
        }

        customcaddy.test

        tls ./etc/customcaddy.test.pem ./etc/customcaddy.test-key.pem

        route {
            root * ./public
            mercure {
                # Transport to use (default to Bolt)
                transport_url {$MERCURE_TRANSPORT_URL:bolt:///data/mercure.db}
                # Publisher JWT key
                publisher_jwt {env.MERCURE_PUBLISHER_JWT_KEY} {env.MERCURE_PUBLISHER_JWT_ALG}
                # Subscriber JWT key
                subscriber_jwt {env.MERCURE_SUBSCRIBER_JWT_KEY} {env.MERCURE_SUBSCRIBER_JWT_ALG}
                # Allow anonymous subscribers (double-check that it's what you want)
                anonymous
                # Enable the subscription API (double-check that it's what you want)
                subscriptions
                # Extra directives
                {$MERCURE_EXTRA_DIRECTIVES}
            }
        }
    '';
}

I do think I need to brush up on my nix skills though :sweat_smile:

1 Like