aboutsummaryrefslogtreecommitdiff
path: root/cmd/todayinmarch2020/main.go
blob: 7c3f7734cb28009770d00b8a602783d87a7a2469 (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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
package main

import (
	"embed"
	"encoding/json"
	"flag"
	"log"
	"math/rand"
	"net"
	"net/http"
	"os"
	"time"

	"github.com/a-h/templ"
	"within.website/x/xess"
)

//go:generate go tool templ generate

var (
	port     = flag.String("port", "23698", "TCP port to listen on")
	sockPath = flag.String("socket", "", "Unix socket to listen on")

	//go:embed quips.json
	content embed.FS

	quips []string
)

func main() {
	flag.Parse()

	fin, err := content.Open("quips.json")
	if err != nil {
		log.Fatal(err)
	}

	err = json.NewDecoder(fin).Decode(&quips)
	if err != nil {
		log.Fatal(err)
	}

	mux := http.NewServeMux()
	xess.Mount(mux)
	mux.Handle("/{$}", index())
	mux.Handle("/api", api())

	var l net.Listener
	if *sockPath != "" {
		os.Remove(*sockPath)
		l, err = net.Listen("unix", *sockPath)
	} else {
		l, err = net.Listen("tcp", ":"+*port)
	}

	if err != nil {
		log.Fatal(err)
	}

	srv := &http.Server{
		Handler: mux,
	}
	log.Fatal(srv.Serve(l))
}

func api() http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		w.Header().Add("Content-Type", "application/json")

		then := time.Date(2020, time.March, 1, 0, 0, 0, 0, time.UTC)
		now := time.Now().UTC()
		dur := now.Sub(then)

		json.NewEncoder(w).Encode(struct {
			Day  int    `json:"day"`
			Quip string `json:"quip"`
		}{
			Day:  int(dur.Hours()/24) + 1,
			Quip: quips[rand.Intn(len(quips))],
		})
	})
}

func index() http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		then := time.Date(2020, time.March, 1, 0, 0, 0, 0, time.UTC)
		now := time.Now().UTC()
		dur := now.Sub(then)

		day := int(dur.Hours()/24) + 1
		quip := quips[rand.Intn(len(quips))]

		templ.Handler(xess.Base(
			"What day of 2020 is it?",
			headArea(),
			nil,
			body(day, quip),
			footer(),
		)).ServeHTTP(w, r)
	})
}