75 lines
1.4 KiB
Go
75 lines
1.4 KiB
Go
package main
|
|
|
|
import (
|
|
"encoding/json"
|
|
"io/ioutil"
|
|
"net/http"
|
|
)
|
|
|
|
type vote struct {
|
|
item byte
|
|
weight int
|
|
}
|
|
|
|
var homeHtml []byte
|
|
var displayHtml []byte
|
|
|
|
var stats = make([]int, 2)
|
|
|
|
func main() {
|
|
var err error
|
|
homeHtml, err = ioutil.ReadFile("index.html")
|
|
if err != nil {
|
|
panic(err)
|
|
}
|
|
|
|
displayHtml, err = ioutil.ReadFile("display.html")
|
|
if err != nil {
|
|
panic(err)
|
|
}
|
|
|
|
var manager = make(chan vote)
|
|
go manage(manager)
|
|
|
|
go func() {
|
|
mux := http.NewServeMux()
|
|
mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
|
|
w.WriteHeader(http.StatusOK)
|
|
w.Write(displayHtml)
|
|
})
|
|
mux.HandleFunc("/stats", func(w http.ResponseWriter, r *http.Request) {
|
|
w.WriteHeader(http.StatusOK)
|
|
json.NewEncoder(w).Encode(stats)
|
|
})
|
|
http.ListenAndServe("127.0.0.1:8081", mux)
|
|
}()
|
|
|
|
mux := http.NewServeMux()
|
|
mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
|
|
w.WriteHeader(http.StatusOK)
|
|
w.Write(homeHtml)
|
|
})
|
|
mux.HandleFunc("/vote", func(w http.ResponseWriter, r *http.Request) {
|
|
var key = r.URL.Query().Get("key")
|
|
switch key {
|
|
case "0":
|
|
manager <- vote{item: 0, weight: 1}
|
|
case "1":
|
|
manager <- vote{item: 1, weight: 1}
|
|
default:
|
|
w.WriteHeader(http.StatusBadRequest)
|
|
return
|
|
}
|
|
w.WriteHeader(http.StatusNoContent)
|
|
})
|
|
http.ListenAndServe(":8080", mux)
|
|
}
|
|
|
|
func manage(ch chan vote) {
|
|
for v := range ch {
|
|
if int(v.item) < len(stats) {
|
|
stats[v.item] += v.weight
|
|
}
|
|
}
|
|
}
|