-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.go
113 lines (101 loc) · 2.58 KB
/
main.go
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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
package main
import (
"bufio"
"crypto/sha1"
"encoding/hex"
"fmt"
"net/http"
"os"
"strconv"
kademlia "github.com/mm-uh/go-kademlia/src"
)
var Node *kademlia.LocalKademlia
func main() {
ip := os.Args[1]
portStr := os.Args[2]
port, err := strconv.Atoi(portStr)
if err != nil {
panic("Invalid port")
}
gateway := len(os.Args) == 3
ln := kademlia.NewLocalKademlia(ip, port, 5, 3)
Node = ln
exited := make(chan bool)
ln.RunServer(exited)
http.HandleFunc("/", EndpointHandler)
go http.ListenAndServe(fmt.Sprintf(":%d", port+1000), nil)
if !gateway {
ipForJoin := os.Args[3]
portForJoinStr := os.Args[4]
portForJoin, err := strconv.Atoi(portForJoinStr)
if err != nil {
panic("Invalid port for join")
}
rn := kademlia.NewRemoteKademliaWithoutKey(ipForJoin, portForJoin)
err = ln.JoinNetwork(rn)
if err != nil {
panic("Can't Join")
}
}
fmt.Println("Get or Save??")
scanner := bufio.NewScanner(os.Stdin)
for {
scanner.Scan()
switch scanner.Text() {
case "save":
{
fmt.Println("Insert Key")
scanner.Scan()
keyStr := scanner.Text()
key := kademlia.KeyNode{}
hash := sha1.Sum([]byte(keyStr))
key.GetFromString(hex.EncodeToString(hash[:]))
fmt.Println("Insert Value")
scanner.Scan()
val := scanner.Text()
//_, _ = ln.GetAndLock(ln.GetContactInformation(), &key)
err := ln.GetLock(ln.GetContactInformation(), &key)
if err != nil {
fmt.Println("COULD NOT UPDATE")
continue
}
ln.StoreOnNetwork(ln.GetContactInformation(), &key, val)
ln.LeaveLock(ln.GetContactInformation(), &key)
//ln.StoreAndUnlock(ln.GetContactInformation(), &key, val)
}
case "get":
{
fmt.Println("Insert Key")
scanner.Scan()
keyStr := scanner.Text()
key := kademlia.KeyNode{}
hash := sha1.Sum([]byte(keyStr))
key.GetFromString(hex.EncodeToString(hash[:]))
fmt.Println(key.String())
//val, err := ln.GetAndLock(ln.GetContactInformation(), &key)
//ln.StoreAndUnlock(ln.GetContactInformation(), &key, val)
//err := ln.GetLock(ln.GetContactInformation(), &key)
//if err != nil {
// fmt.Println("COULD NOT GET VALUE")
// continue
//}
val, err := ln.GetFromNetwork(ln.GetContactInformation(), &key)
if err != nil {
fmt.Println(err.Error())
} else {
fmt.Println(val)
}
//ln.LeaveLock(ln.GetContactInformation(), &key)
}
}
}
if s := <-exited; s {
// Handle Error in method
fmt.Println("We get an error listen server")
return
}
}
func EndpointHandler(w http.ResponseWriter, r *http.Request) {
data := Node.GetInfo()
fmt.Fprintf(w, "%s", data)
}