testhub/server.go

57 lines
1.2 KiB
Go
Raw Normal View History

2022-05-25 12:04:53 +02:00
package main
import (
2022-05-25 18:09:54 +02:00
"encoding/json"
2022-05-25 12:04:53 +02:00
"fmt"
"net/http"
"strings"
2022-05-25 12:21:32 +02:00
"git.andreafazzi.eu/andrea/testhub/store"
)
2022-05-25 12:04:53 +02:00
2022-05-25 18:09:54 +02:00
const jsonContentType = "application/json"
2022-05-25 12:04:53 +02:00
type PlayerServer struct {
2022-05-25 12:21:32 +02:00
store store.PlayerStore
2022-05-25 18:09:54 +02:00
http.Handler
2022-05-25 12:04:53 +02:00
}
2022-05-25 18:09:54 +02:00
func NewPlayerServer(store store.PlayerStore) *PlayerServer {
ps := new(PlayerServer)
ps.store = store
router := http.NewServeMux()
router.Handle("/players/", http.HandlerFunc(ps.playersHandler))
router.Handle("/league", http.HandlerFunc(ps.leagueHandler))
ps.Handler = router
return ps
2022-05-25 12:04:53 +02:00
}
2022-05-25 18:09:54 +02:00
func (ps *PlayerServer) leagueHandler(w http.ResponseWriter, r *http.Request) {
w.Header().Set("content-type", jsonContentType)
json.NewEncoder(w).Encode(ps.store.GetLeague())
}
func (ps *PlayerServer) playersHandler(w http.ResponseWriter, r *http.Request) {
2022-05-25 12:04:53 +02:00
player := strings.TrimPrefix(r.URL.Path, "/players/")
switch r.Method {
case http.MethodGet:
score := ps.store.GetPlayerScore(player)
if score == 0 {
w.WriteHeader(http.StatusNotFound)
}
fmt.Fprint(w, score)
case http.MethodPost:
ps.processWin(w, player)
}
}
2022-05-25 18:09:54 +02:00
func (ps *PlayerServer) processWin(w http.ResponseWriter, player string) {
ps.store.RecordWin(player)
w.WriteHeader(http.StatusAccepted)
}