From afe79e8430302808004ac2f5b5cc7d21d4d5d170 Mon Sep 17 00:00:00 2001 From: JP Appel Date: Sat, 28 Sep 2024 03:31:28 -0400 Subject: Add simple http server --- net/net.go | 81 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 81 insertions(+) create mode 100644 net/net.go (limited to 'net/net.go') diff --git a/net/net.go b/net/net.go new file mode 100644 index 0000000..228d22d --- /dev/null +++ b/net/net.go @@ -0,0 +1,81 @@ +package net + +import ( + "fmt" + "html/template" + "net/http" + "os" + "slices" + + "github.com/jpappel/bingo-factory/bingo" +) + +func errLog(w http.ResponseWriter, err error, logInfo string, httpInfo string) { + fmt.Fprintln(os.Stderr, logInfo, err) + http.Error(w, httpInfo, http.StatusInternalServerError) +} + +func game(w http.ResponseWriter, req *http.Request) { + game := bingo.Game{ + Length: 3, + FreeSquare: false, + } + + tiles := make([]bingo.Tile, 9) + for i := range 9 { + tiles[i].Text = fmt.Sprintf("Tile %d", i) + } + + game.Board = tiles + + t, err := template.ParseFiles("templates/base.html", "templates/bingo.html") + if err != nil { + errLog(w, err, "parsing template", "parse error") + return + } + + rows := slices.Collect(game.Rows()) + + data := struct { + Game bingo.Game + Rows [][]bingo.Tile + }{ + Game: game, + Rows: rows, + } + + if err = t.Execute(w, data); err != nil { + errLog(w, err, "template execute failed", "execute error") + return + } +} + +func home(w http.ResponseWriter, req *http.Request) { + + t, err := template.ParseFiles("templates/base.html") + if err != nil { + errLog(w, err, "parsing base template: ", "template parse error") + return + } + + t.Parse(` +{{ define "content" }} +

Bingo Factory

+

We're currently under construction, please check back soon!

+{{ end }} + `) + + if err = t.Execute(w, nil); err != nil { + errLog(w, err, "executing template", "template execute error") + return + } +} + +func NewMux() *http.ServeMux { + mux := http.NewServeMux() + + mux.Handle("GET /", http.HandlerFunc(home)) + mux.Handle("GET /bingo", http.HandlerFunc(game)) + + return mux +} -- cgit v1.2.3