Newer
Older
import (
"bytes"
"encoding/json"
"fmt"
"log"
"net/http"
"sync"
"time"
rad "gitlab.utc.fr/gvandevi/ia04binome2a" // à remplacer par le nom du dossier actuel
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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
)
type RestServerAgent struct {
sync.Mutex
id string
reqCount int
addr string
}
func NewRestServerAgent(addr string) *RestServerAgent {
return &RestServerAgent{id: addr, addr: addr}
}
// Test de la méthode
func (rsa *RestServerAgent) checkMethod(method string, w http.ResponseWriter, r *http.Request) bool {
if r.Method != method {
w.WriteHeader(http.StatusMethodNotAllowed)
fmt.Fprintf(w, "method %q not allowed", r.Method)
return false
}
return true
}
func (*RestServerAgent) decodeRequest(r *http.Request) (req rad.BallotRequest, err error) {
buf := new(bytes.Buffer)
buf.ReadFrom(r.Body)
err = json.Unmarshal(buf.Bytes(), &req)
return
}
func (rsa *RestServerAgent) doCalc(w http.ResponseWriter, r *http.Request) {
// mise à jour du nombre de requêtes
rsa.Lock()
defer rsa.Unlock()
rsa.reqCount++
// vérification de la méthode de la requête
if !rsa.checkMethod("POST", w, r) {
return
}
// décodage de la requête
req, err := rsa.decodeRequest(r)
if err != nil {
w.WriteHeader(http.StatusBadRequest)
fmt.Fprint(w, err.Error())
return
}
// traitement de la requête
var resp rad.Ballot
resp.BallotID = "ballot1"
switch req.Rule {
case "majority":
case "borda":
case "approval":
case "stv":
default:
w.WriteHeader(http.StatusNotImplemented)
msg := fmt.Sprintf("Unkonwn rule '%s'", req.Rule)
w.Write([]byte(msg))
return
}
w.WriteHeader(http.StatusOK)
serial, _ := json.Marshal(resp)
w.Write(serial)
}
func (rsa *RestServerAgent) doReqcount(w http.ResponseWriter, r *http.Request) {
if !rsa.checkMethod("GET", w, r) {
return
}
w.WriteHeader(http.StatusOK)
rsa.Lock()
defer rsa.Unlock()
serial, _ := json.Marshal(rsa.reqCount)
w.Write(serial)
}
func (rsa *RestServerAgent) Start() {
// création du multiplexer
mux := http.NewServeMux()
mux.HandleFunc("/calculator", rsa.doCalc)
mux.HandleFunc("/reqcount", rsa.doReqcount)
// création du serveur http
s := &http.Server{
Addr: rsa.addr,
Handler: mux,
ReadTimeout: 10 * time.Second,
WriteTimeout: 10 * time.Second,
MaxHeaderBytes: 1 << 20}
// lancement du serveur
log.Println("Listening on", rsa.addr)
go log.Fatal(s.ListenAndServe())
}