-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
54 lines (43 loc) · 1.05 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
package main
import (
"encoding/json"
"fmt"
"io/ioutil"
"log"
"net/http"
"github.com/enceeobee/crib/hand"
)
func countHandler(w http.ResponseWriter, r *http.Request) {
body, err := ioutil.ReadAll(r.Body)
if err != nil {
log.Printf("Error reading body: %v", err)
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
h := &hand.Hand{}
err = json.Unmarshal(body, h)
if err != nil {
log.Printf("Error unmarshaling hand: %v", err)
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
err = h.Validate()
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
response := &hand.CountResponse{
Points: h.Count(),
}
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(response)
}
func rootHandler(w http.ResponseWriter, r *http.Request) {
fmt.Fprint(w, "Welcome to Cribbage!")
}
func main() {
http.HandleFunc("/", rootHandler)
http.HandleFunc("/count", countHandler)
fmt.Println("\nCribbage server started")
log.Fatal(http.ListenAndServe(":8456", nil))
}