aboutsummaryrefslogtreecommitdiff
path: root/services/service-router.service.nix
blob: e52280fd9f0d864fd585e48621f01ff6633e4c2a (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
{ config, lib, ... }:
with lib;
let
  cfg = config.services.service-router;
in {
  imports = [
    ./bacchus-dns.service.nix
  ];

  options.services.service-router = {
    enable = mkEnableOption "enable router";
    routes = mkOption {
      type = types.attrsOf (types.submodule { options = {
        port = mkOption { type = types.int; };
        host = mkOption { type = types.str; default = "127.0.0.1"; };
        protocol = mkOption { type = types.str; default = "http"; };
        basePath = mkOption { type = types.str; default = ""; };
        extraNginxOptions = mkOption { type = types.attrs; default = {}; };
      }; });
      default = {};
    };
  };

  config = lib.mkIf cfg.enable {
    services.nginx = {
      enable = true;
      recommendedOptimisation = true;
      virtualHosts = lib.mapAttrs (_: val:
        let
          opts = if hasAttr "extraNginxOptions" val then val.extraNginxOptions else {};
        in {
          locations."/" = {
            proxyPass =
              "${val.protocol}://${val.host}:${toString val.port}${val.basePath}";
            proxyWebsockets = true;
          } // opts;
        }
      ) cfg.routes;
    };

    # Hostname mapping
    services.bacchus-dns = {
      enable = true;
      hosts = mapAttrs (_: val: val.host) cfg.routes;
    };
  };
}