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() }