blockchainIDsystem/peer/restRoutes.go
peer/restRoutes.goRaw
1package main
2
3import (
4 "encoding/json"
5 "fmt"
6 "net/http"
7
8 "github.com/fatih/color"
9 "github.com/gorilla/mux"
10)
11
12type Routes []Route
13
14var routes = Routes{
15 Route{
16 "Index",
17 "GET",
18 "/",
19 Index,
20 },
21 Route{
22 "GetPeers",
23 "GET",
24 "/peers",
25 GetPeers,
26 },
27 Route{
28 "PostUser",
29 "POST",
30 "/register",
31 PostUser,
32 },
33 Route{
34 "GenesisBlock",
35 "GET",
36 "/blocks/genesis",
37 GenesisBlock,
38 },
39 Route{
40 "NextBlock",
41 "GET",
42 "/blocks/next/{blockhash}",
43 NextBlock,
44 },
45 Route{
46 "LastBlock",
47 "GET",
48 "/blocks/last",
49 LastBlock,
50 },
51}
52
53type Address struct {
54 Address string `json:"address"` //the pubK of the user, to perform logins
55}
56
57func Index(w http.ResponseWriter, r *http.Request) {
58 fmt.Fprintln(w, runningPeer.ID)
59}
60func GetPeers(w http.ResponseWriter, r *http.Request) {
61 jResp, err := json.Marshal(outcomingPeersList)
62 check(err)
63 fmt.Fprintln(w, string(jResp))
64}
65func PostUser(w http.ResponseWriter, r *http.Request) {
66
67 decoder := json.NewDecoder(r.Body)
68 var address Address
69 err := decoder.Decode(&address)
70 if err != nil {
71 panic(err)
72 }
73 defer r.Body.Close()
74 fmt.Println(address)
75 color.Blue(address.Address)
76
77 //TODO add the verification of the address, to decide if it's accepted to create a new Block
78 block := blockchain.createBlock(address)
79 blockchain.addBlock(block)
80
81 go propagateBlock(block)
82
83 jResp, err := json.Marshal(blockchain)
84 check(err)
85 fmt.Fprintln(w, string(jResp))
86}
87
88func GenesisBlock(w http.ResponseWriter, r *http.Request) {
89 var genesis Block
90 if len(blockchain.Blocks) >= 0 {
91 genesis = blockchain.Blocks[0]
92 }
93
94 jResp, err := json.Marshal(genesis)
95 check(err)
96 fmt.Fprintln(w, string(jResp))
97}
98
99func NextBlock(w http.ResponseWriter, r *http.Request) {
100 vars := mux.Vars(r)
101 blockhash := vars["blockhash"]
102
103 currBlock, err := blockchain.getBlockByHash(blockhash)
104 check(err)
105 nextBlock, err := blockchain.getBlockByHash(currBlock.NextHash)
106 check(err)
107
108 jResp, err := json.Marshal(nextBlock)
109 check(err)
110 fmt.Fprintln(w, string(jResp))
111}
112
113func LastBlock(w http.ResponseWriter, r *http.Request) {
114 var genesis Block
115 if len(blockchain.Blocks) > 0 {
116 genesis = blockchain.Blocks[len(blockchain.Blocks)-1]
117 }
118
119 jResp, err := json.Marshal(genesis)
120 check(err)
121 fmt.Fprintln(w, string(jResp))
122}