package main import ( "encoding/json" "fmt" "net/http" "strings" "git.andreafazzi.eu/andrea/testhub/store" ) const jsonContentType = "application/json" type PlayerServer struct { store store.PlayerStore http.Handler } 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 } 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) { 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) } } func (ps *PlayerServer) processWin(w http.ResponseWriter, player string) { ps.store.RecordWin(player) w.WriteHeader(http.StatusAccepted) }