go-dvote/net/http.go
net/http.goRaw
1package net
2
3import (
4 "io"
5 "fmt"
6 "net/http"
7 "encoding/json"
8 "strings"
9
10 "github.com/vocdoni/dvote-relay/batch"
11 "github.com/vocdoni/dvote-relay/types"
12)
13
14type HttpHandle struct {
15 port string
16 path string
17}
18
19func (h HttpHandle) Init(c string) error {
20 //split c to port and path
21 cs := strings.Split(c, "/")
22 h.port = cs[0]
23 h.path = cs[1]
24 return nil
25
26}
27
28func parse(rw http.ResponseWriter, request *http.Request) {
29 decoder := json.NewDecoder(request.Body)
30
31 var e types.Envelope
32 var b types.Ballot
33
34 err := decoder.Decode(&e)
35 if err != nil {
36 panic(err)
37 }
38
39 err = json.Unmarshal(e.Ballot, &b)
40 if err != nil {
41 panic(err)
42 }
43
44
45 //check PoW
46 //check key
47 //decrypt
48 //check franchise
49 //construct packet
50
51 //this should should be randomized, or actually taken from input
52 //b.PID = "1"
53 //b.Nullifier = []byte{1,2,3}
54 //b.Vote = []byte{4,5,6}
55 //b.Franchise = []byte{7,8,9}
56
57 err = batch.Add(b)
58 if err != nil {
59 panic(err)
60 }
61
62 j, err := json.Marshal(e)
63 if err != nil {
64 panic(err)
65 }
66 io.WriteString(rw, string(j))
67}
68
69func (h HttpHandle) Listen() error {
70 http.HandleFunc(h.path, parse)
71 //add waitgroup
72 func() {
73 fmt.Println("serving on " + h.port)
74 err := http.ListenAndServe(":" + h.port, nil)
75 if err != nil {
76 return
77 }
78 }()
79 return nil
80}
81