mmg/main.go

71 lines
1.5 KiB
Go

package main
import (
"flag"
"fmt"
"log"
"math/rand"
"net/http"
"os"
"time"
"github.com/gorilla/sessions"
)
const MAX = 12
var port = flag.Int("port", 8000, "listen on this port")
var store = sessions.NewCookieStore([]byte(os.Getenv("MMG_SECRET_KEY")))
var statics map[string][]byte
func main() {
statics = map[string][]byte{
"/": staticIndexHtml,
"/jquery.js": staticJqueryJs,
"/math.css": staticMathCss,
"/math.js": staticMathJs,
"/addsub/": staticAddsubHtml,
"/mul/": staticMulHtml,
}
rand.Seed(time.Now().UTC().UnixNano())
flag.Parse()
http.HandleFunc("/api/v0/addsub/problem/", addsub)
http.HandleFunc("/api/v0/mul/problem/", mul)
http.HandleFunc("/api/v0/attempt/", attempt)
http.HandleFunc(
"/",
static,
)
http.HandleFunc(
"/reset/",
reset,
)
hostname, err := os.Hostname()
if err != nil {
log.Fatal("problem getting hostname:", err)
}
log.Printf("serving at: http://%s:%d/", hostname, *port)
if err := http.ListenAndServe(fmt.Sprintf(":%d", *port), nil); err != nil {
log.Fatal("ListenAndServe:", err)
}
}
func static(w http.ResponseWriter, req *http.Request) {
if content, ok := statics[req.URL.Path]; !ok {
http.Error(w, "file not found", http.StatusNotFound)
return
} else {
if req.URL.Path == "/math.css" {
w.Header().Set("Content-Type", "text/css")
}
_, err := w.Write(content)
if err != nil {
http.Error(w, "problem writing response", http.StatusInternalServerError)
return
}
}
}