-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhttp.go
More file actions
78 lines (66 loc) · 1.6 KB
/
http.go
File metadata and controls
78 lines (66 loc) · 1.6 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
package main
import (
"encoding/json"
"net/http"
)
// Env inject dependencies to http handler
type Env struct {
bc *Blockchain
hub *Hub
peerURL chan string
}
// peerJSON used in AddPeer for reading request body
type peerJSON struct {
Peer string `json:"peer"`
}
// mineJSON used in MineBlock for reading request body
type mineJSON struct {
Data string `json:"data"`
}
func (e *Env) GetBlocks(w http.ResponseWriter, r *http.Request) {
err := json.NewEncoder(w).Encode(e.bc.chain)
if err != nil {
http.Error(w, http.StatusText(500), 500)
}
}
func (e *Env) MineBlock(w http.ResponseWriter, r *http.Request) {
var mj mineJSON
decoder := json.NewDecoder(r.Body)
err := decoder.Decode(&mj)
if err != nil {
http.Error(w, http.StatusText(400), 400)
return
}
b := NextBlock(*e.bc.LatestBlock(), mj.Data)
err = e.bc.AddBlock(b)
if err != nil {
http.Error(w, http.StatusText(500), 500)
return
}
data, err := blocksMessageJSON([]Block{b}, QueryLatest)
if err != nil {
http.Error(w, http.StatusText(500), 500)
return
}
e.hub.broadcast <- data
}
func (e *Env) GetPeers(w http.ResponseWriter, r *http.Request) {
peers := make([]string, 0, len(e.hub.peers))
for c, _ := range e.hub.peers {
peers = append(peers, c.conn.RemoteAddr().String())
}
err := json.NewEncoder(w).Encode(peers)
if err != nil {
http.Error(w, http.StatusText(500), 500)
}
}
func (e *Env) AddPeer(w http.ResponseWriter, r *http.Request) {
var pj peerJSON
decoder := json.NewDecoder(r.Body)
err := decoder.Decode(&pj)
if err != nil {
http.Error(w, http.StatusText(400), 400)
return
}
e.peerURL <- pj.Peer
}