summaryrefslogtreecommitdiff
path: root/main.go
blob: 14dec49a77d408994b2be8ca255995f83a907369 (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
package main

import (
	"encoding/json"
	"flag"
	"io"
	"log"
	"net/http"
	"os"
)

type option struct {
	Text string
	Arc  string
}

type arc struct {
	Title   string
	Story   []string
	Options []option
}

type story map[string]arc

func (s story) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	arc := r.PathValue("arc")
	title := s[arc].Title

	w.Header().Set("Content-Type", "text/plain")
	io.WriteString(w, title)
}

func main() {
	// Set up log flags.
	log.SetFlags(log.LstdFlags | log.Lshortfile)

	// Get any command-line flags (port, etc.)
	port := flag.String("port", "8080", "Server port")
	filename := flag.String("json", "adventure.json", "Adventure file (JSON)")
	flag.Parse()

	// Get the JSON.
	f, err := os.Open(*filename)
	if err != nil {
		log.Fatal(err)
	}
	defer f.Close()
	jsonBytes, err := io.ReadAll(f)
	if err != nil {
		log.Fatal(err)
	}

	var s story
	if err := json.Unmarshal(jsonBytes, &s); err != nil {
		log.Fatal(err)
	}

	// Set up the handlers and server.
	mux := http.NewServeMux()
	mux.Handle("/{arc}", &s)

	log.Fatal(runServer(mux, *port))
}

func runServer(h http.Handler, port string) error {
	srv := http.Server{
		Addr:    ":" + port,
		Handler: h,
	}

	log.Printf("Serving on port %s...\n", port)

	return srv.ListenAndServe()
}