package main import ( "embed" "encoding/json" "log" "net/http" "os" "github.com/gorilla/mux" ) //go:embed *.js //go:embed *.html var content embed.FS func handleEntryOptions(w http.ResponseWriter, r *http.Request) { w.Header().Set("Access-Control-Allow-Origin", "*") w.Header().Set("Access-Control-Allow-Methods", "POST, OPTIONS") w.Header().Set("Access-Control-Allow-Headers", "Content-Type") w.WriteHeader(http.StatusNoContent) } func handleEntryPost(w http.ResponseWriter, r *http.Request) { w.Header().Set("Access-Control-Allow-Origin", "*") w.Header().Set("Access-Control-Allow-Methods", "POST, OPTIONS") w.Header().Set("Access-Control-Allow-Headers", "Content-Type") var entry Entry err := json.NewDecoder(r.Body).Decode(&entry) if err != nil { http.Error(w, err.Error(), http.StatusBadRequest) return } err = InsertEntry(&entry) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } log.Println("New entry for", entry.Location) } func handleRequests() { router := mux.NewRouter() router.HandleFunc("/entry", handleEntryPost).Methods("POST") router.HandleFunc("/entry", handleEntryOptions).Methods("OPTIONS") router.PathPrefix("/").Handler(http.FileServer(http.FS(content))) log.Fatal(http.ListenAndServe(configure(), router)) } func configure() string { at := os.Getenv("STATSAT") if at == "" { log.Println("Defaulting to STATSAT=:8080") at = ":8080" } return at } func main() { log.Println("Starting up") InitEntries() defer CloseEntries() handleRequests() }