summaryrefslogtreecommitdiffstats
path: root/krebs/3modules/go.nix
blob: 5686fea3f8b62b15c41d644ff3cd9fae7e71a2f3 (plain)
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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
{ config, lib, pkgs, ... }:

with import <stockholm/lib>;

let
  cfg = config.krebs.go;

  out = {
    options.krebs.go = api;
    config = lib.mkIf cfg.enable imp;
  };

  api = {
    enable = mkEnableOption "Enable go url shortener";
    port = mkOption {
      type = types.int;
      default = 1337;
      description = "on which port go should run on";
    };
  };

  imp = {
    services.redis = {
      enable = true;
    };

    krebs.htgen.go = {
      port = cfg.port;
      script = ''. ${pkgs.writeDash "go" ''
        set -x

        case "$Method $Request_URI" in
          "GET /"*)
            if item=$(${pkgs.redis}/bin/redis-cli --raw get "''${Request_URI#/}"); then
              printf 'HTTP/1.1 302 Found\r\n'
              printf 'Content-Type: text/plain\r\n'
              printf 'Connection: closed\r\n'
              printf 'Location: %s\r\n' "$item"
              printf '\r\n'
              exit
            fi
          ;;
          "POST /")
            uri=$(head -c "$req_content_length" \
              | sed 's/+/ /g;s/%\(..\)/\\x\1/g;' \
              | xargs -0 echo -e \
              | tee /tmp/tee.log \
              | ${pkgs.urix}/bin/urix \
              | head -1 \
            )

            sha256=$(echo "$uri" | sha256sum -b | cut -d\  -f1)
            base32=$(${pkgs.nixStable}/bin/nix-hash --to-base32 --type sha256 "$sha256")
            base32short=$(echo "$base32" | cut -b-5)
            ${pkgs.redis}/bin/redis-cli set "$base32short" "$uri" >/dev/null

            ref="http://$req_host/$base32short"

            printf 'HTTP/1.1 200 OK\r\n'
            printf 'Content-Type: text/plain; charset=UTF-8\r\n'
            printf 'Connection: close\r\n'
            printf '\r\n'
            printf '%s\n' "$ref"
            exit
          ;;
        esac
      ''}'';
    };
  };

in out