package main import ( "encoding/json" "github.com/gorilla/mux" "log" "net/http" ) func handleHome(w http.ResponseWriter, r *http.Request) { w.Write([]byte("stats OK")) } func handleEntryOptions(w http.ResponseWriter, r *http.Request) { w.Header().Set("Access-Control-Allow-Origin", "*") w.Header().Set("Access-Control-Allow-Methods", "POST") 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") 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 } } func handleRequests() { router := mux.NewRouter() router.HandleFunc("/", handleHome) router.HandleFunc("/entry", handleEntryPost).Methods("POST") router.HandleFunc("/entry", handleEntryOptions).Methods("OPTIONS") log.Fatal(http.ListenAndServe(":8080", router)) } func main() { log.Println("Starting up") InitEntries() defer CloseEntries() handleRequests() }