summaryrefslogtreecommitdiff
path: root/src/hsts.go
blob: 93f76ca2e11f92d1f710503c33d48dfb8254d26a (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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
package hsts

import (
	"fmt"
	"log/slog"
	"net"
	"net/http"
	"os"

	"uuid"
	g "gobang"
	gt "gotext"
)



var countRedirection = g.MakeCounter("request-redirection")



func redirectHandler(w http.ResponseWriter, r *http.Request) {
	target := "https://" + r.Host + r.RequestURI
	http.Redirect(w, r, target, http.StatusMovedPermanently)
	countRedirection(
		"id",          uuid.New().String(),
		"url-path",    r.URL.Path,
		"req-pattern", r.Pattern,
		"method",      r.Method,
		"host",        r.Host,
		"uri",         r.RequestURI,
	)
}

func listen(fromAddr string) net.Listener {
	listener, err := net.Listen("unix", fromAddr)
	g.FatalIf(err)
	g.Info(
		"Started listening", "listen-start",
		"from-address", fromAddr,
		slog.Group(
			"versions",
			"uuid",  uuid.Version,
			"gobang",     g.Version,
			"hsts",         Version,
		),
	)
	return listener
}



func Main() {
	g.Init("program", "hsts")

	if len(os.Args) != 2 {
		fmt.Fprintf(os.Stderr, gt.Gettext("Usage: %s LISTEN.socket\n"), os.Args[0])
		os.Exit(2)
	}

	listener := listen(os.Args[1])
	err := http.Serve(listener, http.HandlerFunc(redirectHandler))
	g.FatalIf(err)
}