mmg/handlers.go

138 lines
2.4 KiB
Go

package main
import (
"encoding/json"
"log"
"math/rand"
"net/http"
"strconv"
"github.com/gorilla/sessions"
)
type prob struct {
Operation string
First int
Second int
Score int
}
type solution struct {
Status bool
Score int
}
func getScore(session *sessions.Session) int {
score := session.Values["Score"]
var parsed_score int
if score == nil {
parsed_score = 0
} else {
parsed_score = score.(int)
}
return parsed_score
}
func addsub(w http.ResponseWriter, req *http.Request) {
w.Header().Set("Content-Type", "application/json")
operation := "+"
if r := rand.Intn(2); r == 0 {
operation = "-"
}
first := rand.Intn(MAX)
var second int
if operation == "-" {
if first == 0 {
second = 0
} else {
second = rand.Intn(first)
}
} else {
second = rand.Intn(MAX)
}
session, _ := store.Get(req, "Score")
score := getScore(session)
r := prob{operation, first, second, score}
err := json.NewEncoder(w).Encode(r)
if err != nil {
log.Fatal("issue with json marshalling", err)
}
}
func mul(w http.ResponseWriter, req *http.Request) {
w.Header().Set("Content-Type", "application/json")
session, _ := store.Get(req, "Score")
score := getScore(session)
err := json.NewEncoder(w).Encode(
prob{
"x",
rand.Intn(11),
rand.Intn(11),
score,
},
)
if err != nil {
log.Fatal("issue with json marshalling", err)
}
}
func attempt(w http.ResponseWriter, req *http.Request) {
w.Header().Set("Content-Type", "application/json")
first, err := strconv.Atoi(req.FormValue("first"))
if err != nil {
log.Fatal("cannot parse first", err)
}
operation := req.FormValue("operation")
second, err := strconv.Atoi(req.FormValue("second"))
if err != nil {
log.Fatal("cannot parse second", err)
}
var guess int
answer := req.FormValue("answer")
if answer == "" {
guess = 0
} else {
guess, err = strconv.Atoi(answer)
if err != nil {
log.Fatal("cannot parser answer", err)
}
}
var result bool
switch operation {
case "+":
result = first+second == guess
case "-":
result = first-second == guess
case "*", "x":
result = first*second == guess
}
session, _ := store.Get(req, "Score")
score := getScore(session)
if result {
score += 1
} else {
score -= 1
}
session.Values["Score"] = score
session.Save(req, w)
err = json.NewEncoder(w).Encode(
solution{
result,
score,
},
)
if err != nil {
log.Fatal("cannot marshal solution", err)
}
}