Skip to content
Snippets Groups Projects
ballotagent.go 1.7 KiB
Newer Older
Balthazar Wilson's avatar
Balthazar Wilson committed
package ballotagent

import (
	"bytes"
	"encoding/json"
	"fmt"
	"log"
	"net/http"
	"sync"
	"time"

	rad "gitlab.utc.fr/gvandevi/ia04binome2a" // à remplacer par le nom du dossier actuel
type BallotServerAgent struct {
	sync.Mutex
	id       string
	reqCount int
	addr     string
	ballots  map[rad.Ballot]BallotInfo
func NewBallotServerAgent(addr string) *BallotServerAgent {
	return &BallotServerAgent{id: addr, addr: addr}
}

// Test de la méthode
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)
		return false
	}
	return true
}

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 *BallotServerAgent) 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 *BallotServerAgent) Start() {
	// création du multiplexer
	mux := http.NewServeMux()
	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{
		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())
}