-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
81 lines (68 loc) · 1.42 KB
/
main.go
File metadata and controls
81 lines (68 loc) · 1.42 KB
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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
package main
import (
"encoding/json"
"log"
"math/rand"
"net/http"
"sync"
"time"
"github.com/google/uuid"
)
type Question struct {
UUID string `json:"uuid"`
A int `json:"a"`
B int `json:"b"`
}
type Answer struct {
UUID string `json:"uuid"`
Sum int `json:"sum"`
}
type Response struct {
Ok bool `json:"ok"`
Error string `json:"error"`
}
var timeout = time.Minute
var DB sync.Map
func handler(w http.ResponseWriter, req *http.Request) {
log.Printf("%v from %v\n", req.Method, req.RemoteAddr)
switch req.Method {
case "GET":
q := Question{
UUID: uuid.NewString(),
A: rand.Intn(1 << 30),
B: rand.Intn(1 << 30),
}
qRes, _ := json.Marshal(q)
DB.Store(q.UUID, q.A+q.B)
time.AfterFunc(timeout, func() { DB.Delete(q.UUID) })
w.Write(qRes)
case "POST":
A := Answer{}
err := json.NewDecoder(req.Body).Decode(&A)
if err != nil {
errRes, _ := json.Marshal(Response{false, err.Error()})
w.Write(errRes)
return
}
sum, ok := DB.LoadAndDelete(A.UUID)
if !ok {
errRes, _ := json.Marshal(Response{false, "uuid not found"})
w.Write(errRes)
return
}
if sum.(int) != A.Sum {
res, _ := json.Marshal(Response{false, "wrong answer"})
w.Write(res)
} else {
res, _ := json.Marshal(Response{true, ""})
w.Write(res)
}
}
}
func main() {
http.HandleFunc("/tutorial", handler)
err := http.ListenAndServe(":8080", nil)
if err != nil {
log.Fatalln(err)
}
}