mmg/handlers.go

56 lines
936 B
Go

package main
import (
"encoding/json"
"fmt"
"log"
"math/rand"
"net/http"
)
type prob struct {
Operation string
First int
Last int
}
type JsonHandler func(http.ResponseWriter, *http.Request)
func (h JsonHandler) ServeHTTP(w http.ResponseWriter, req *http.Request) {
w.Header().Set("Content-Type", "application/json")
h(w, req)
}
func problem(w http.ResponseWriter, req *http.Request) {
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)
}
r := prob{operation, first, second}
b, err := json.Marshal(r)
if err != nil {
log.Fatal("issue with json marshalling")
}
j := string(b)
fmt.Println(j)
fmt.Fprintf(w, j)
}
func attempt(w http.ResponseWriter, req *http.Request) {
fmt.Fprintf(w, "hello world")
}