Skip to content
Snippets Groups Projects
Commit 9aaf8ff9 authored by Balthazar Wilson's avatar Balthazar Wilson
Browse files

fix: imports + add: ballot creation

parent adbea6e7
No related branches found
No related tags found
1 merge request!7Partie serveur
......@@ -12,19 +12,20 @@ import (
rad "gitlab.utc.fr/gvandevi/ia04binome2a" // à remplacer par le nom du dossier actuel
)
type RestServerAgent struct {
type BallotServerAgent struct {
sync.Mutex
id string
reqCount int
addr string
ballots map[rad.Ballot]BallotInfo
}
func NewRestServerAgent(addr string) *RestServerAgent {
return &RestServerAgent{id: addr, addr: addr}
func NewBallotServerAgent(addr string) *BallotServerAgent {
return &BallotServerAgent{id: addr, addr: addr}
}
// Test de la méthode
func (rsa *RestServerAgent) checkMethod(method string, w http.ResponseWriter, r *http.Request) bool {
func (rsa *BallotServerAgent) 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)
......@@ -33,58 +34,14 @@ func (rsa *RestServerAgent) checkMethod(method string, w http.ResponseWriter, r
return true
}
func (*RestServerAgent) decodeRequest(r *http.Request) (req rad.BallotRequest, err error) {
func (*BallotServerAgent) 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) {
func (rsa *BallotServerAgent) doReqcount(w http.ResponseWriter, r *http.Request) {
if !rsa.checkMethod("GET", w, r) {
return
}
......@@ -96,11 +53,14 @@ func (rsa *RestServerAgent) doReqcount(w http.ResponseWriter, r *http.Request) {
w.Write(serial)
}
func (rsa *RestServerAgent) Start() {
func (rsa *BallotServerAgent) Start() {
// création du multiplexer
mux := http.NewServeMux()
mux.HandleFunc("/calculator", rsa.doCalc)
mux.HandleFunc("/reqcount", rsa.doReqcount)
mux.HandleFunc("/new_ballot", rsa.createBallot)
mux.HandleFunc("/vote", rsa.doReqcount)
mux.HandleFunc("/result", rsa.doReqcount)
rsa.ballots = make(map[rad.Ballot]BallotInfo)
// création du serveur http
s := &http.Server{
......
package ballotagent
import (
"encoding/json"
"fmt"
"net/http"
rad "gitlab.utc.fr/gvandevi/ia04binome2a"
cs "gitlab.utc.fr/gvandevi/ia04binome2a/comsoc"
)
type BallotInfo struct {
profile cs.Profile
isOpen bool
results rad.ResultResponse
}
func (rsa *BallotServerAgent) createBallot(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 = fmt.Sprintf("scrutin%d", len(rsa.ballots)+1)
rsa.ballots[resp] = BallotInfo{
profile: make(cs.Profile, 0),
isOpen: true,
results: rad.ResultResponse{}}
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)
}
package voteragent
import (
"bytes"
"encoding/json"
"fmt"
"log"
"net/http"
rad "gitlab.utc.fr/gvandevi/ia04binome2a"
)
type RestClientAgent struct {
id string
url string
......@@ -22,49 +12,49 @@ func NewRestClientAgent(id string, url string, op string, arg1 int, arg2 int) *R
return &RestClientAgent{id, url, op, arg1, arg2}
}
func (rca *RestClientAgent) treatResponse(r *http.Response) int {
buf := new(bytes.Buffer)
buf.ReadFrom(r.Body)
var resp rad.Response
json.Unmarshal(buf.Bytes(), &resp)
return resp.Result
}
func (rca *RestClientAgent) doRequest() (res int, err error) {
req := rad.Request{
Operator: rca.operator,
Args: [2]int{rca.arg1, rca.arg2},
}
// sérialisation de la requête
url := rca.url + "/calculator"
data, _ := json.Marshal(req)
// envoi de la requête
resp, err := http.Post(url, "application/json", bytes.NewBuffer(data))
// traitement de la réponse
if err != nil {
return
}
if resp.StatusCode != http.StatusOK {
err = fmt.Errorf("[%d] %s", resp.StatusCode, resp.Status)
return
}
res = rca.treatResponse(resp)
return
}
func (rca *RestClientAgent) Start() {
log.Printf("démarrage de %s", rca.id)
res, err := rca.doRequest()
if err != nil {
log.Fatal(rca.id, "error:", err.Error())
} else {
log.Printf("[%s] %d %s %d = %d\n", rca.id, rca.arg1, rca.operator, rca.arg2, res)
}
}
//func (rca *RestClientAgent) treatResponse(r *http.Response) int {
// buf := new(bytes.Buffer)
// buf.ReadFrom(r.Body)
//
// var resp rad.Response
// json.Unmarshal(buf.Bytes(), &resp)
//
// return resp.Result
//}
//
//func (rca *RestClientAgent) doRequest() (res int, err error) {
// req := rad.Request{
// Operator: rca.operator,
// Args: [2]int{rca.arg1, rca.arg2},
// }
//
// // sérialisation de la requête
// url := rca.url + "/calculator"
// data, _ := json.Marshal(req)
//
// // envoi de la requête
// resp, err := http.Post(url, "application/json", bytes.NewBuffer(data))
//
// // traitement de la réponse
// if err != nil {
// return
// }
// if resp.StatusCode != http.StatusOK {
// err = fmt.Errorf("[%d] %s", resp.StatusCode, resp.Status)
// return
// }
// res = rca.treatResponse(resp)
//
// return
//}
//func (rca *RestClientAgent) Start() {
// log.Printf("démarrage de %s", rca.id)
// res, err := rca.doRequest()
//
// if err != nil {
// log.Fatal(rca.id, "error:", err.Error())
// } else {
// log.Printf("[%s] %d %s %d = %d\n", rca.id, rca.arg1, rca.operator, rca.arg2, res)
// }
//}
......@@ -5,8 +5,8 @@ import (
"log"
"math/rand"
"gitlab.utc.fr/lagruesy/ia04/demos/restagentdemo/restclientagent"
"gitlab.utc.fr/lagruesy/ia04/demos/restagentdemo/restserveragent"
ba "gitlab.utc.fr/gvandevi/ia04binome2a/agt/ballotagent"
va "gitlab.utc.fr/gvandevi/ia04binome2a/agt/voteragent"
)
func main() {
......@@ -15,8 +15,8 @@ func main() {
const url2 = "http://localhost:8080"
ops := [...]string{"+", "-", "*"}
clAgts := make([]restclientagent.RestClientAgent, 0, n)
servAgt := restserveragent.NewRestServerAgent(url1)
clAgts := make([]va.RestClientAgent, 0, n)
servAgt := ba.NewBallotServerAgent(url1)
log.Println("démarrage du serveur...")
go servAgt.Start()
......@@ -27,13 +27,13 @@ func main() {
op := ops[rand.Intn(3)]
op1 := rand.Intn(100)
op2 := rand.Intn(100)
agt := restclientagent.NewRestClientAgent(id, url2, op, op1, op2)
agt := va.NewRestClientAgent(id, url2, op, op1, op2)
clAgts = append(clAgts, *agt)
}
for _, agt := range clAgts {
// attention, obligation de passer par cette lambda pour faire capturer la valeur de l'itération par la goroutine
func(agt restclientagent.RestClientAgent) {
func(agt va.RestClientAgent) {
go agt.Start()
}(agt)
}
......
......@@ -3,11 +3,11 @@ package main
import (
"fmt"
bas "gitlab.utc.fr/gvandevi/ia04binome2a/agt/ballotagent"
ba "gitlab.utc.fr/gvandevi/ia04binome2a/agt/ballotagent"
)
func main() {
server := bas.NewRestServerAgent(":8080")
server := ba.NewBallotServerAgent(":8080")
server.Start()
fmt.Scanln()
}
......@@ -3,11 +3,11 @@ package main
import (
"fmt"
vas "gitlab.utc.fr/gvandevi/ia04binome2a/agt/voteragent"
va "gitlab.utc.fr/gvandevi/ia04binome2a/agt/voteragent"
)
func main() {
ag := vas.NewRestClientAgent("id1", "http://localhost:8080", "+", 11, 1)
ag := va.NewRestClientAgent("id1", "http://localhost:8080", "+", 11, 1)
ag.Start()
fmt.Scanln()
}
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment