-
Notifications
You must be signed in to change notification settings - Fork 329
/
web.go
93 lines (73 loc) · 1.66 KB
/
web.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
package main
import (
"fmt"
"log"
"net/http"
)
const (
// Address server listening address
Address = ":1312"
// UploadRoute key uploading path
UploadRoute = "/upload"
// RetrievalRoute
RetrievalRoute = "/retrieve"
)
// Pair private key and computer id
type Pair struct {
Id string
Key string
}
// Keys stored in memory
var Keys = []Pair{}
func main() {
http.HandleFunc(UploadRoute, handleUpload)
http.HandleFunc(RetrievalRoute, handleRetrieve)
fmt.Println("Listening on", Address)
log.Fatal(http.ListenAndServe(Address, nil))
}
func reject(w http.ResponseWriter, r *http.Request, reason string) {
fmt.Println("Rejecting ", r.RemoteAddr+":", reason)
w.WriteHeader(http.StatusNotFound)
fmt.Fprint(w, http.StatusText(http.StatusNotFound))
}
func handleUpload(w http.ResponseWriter, r *http.Request) {
id := r.PostFormValue("i")
key := r.PostFormValue("k")
if r.Method != "POST" {
reject(w, r, "HTTP method is not POST, got "+r.Method)
return
}
if id == "" {
reject(w, r, "id parameter i not set or empty")
return
}
if key == "" {
reject(w, r, "key parameter k is not set or empty")
}
for _, pair := range Keys {
if pair.Id == id {
reject(w, r, "key already exists")
return
}
}
pair := Pair{Id: id, Key: key}
Keys = append(Keys, pair)
}
func handleRetrieve(w http.ResponseWriter, r *http.Request) {
id := r.PostFormValue("i")
if r.Method != "POST" {
reject(w, r, "HTTP method is not POST, got "+r.Method)
return
}
if id == "" {
reject(w, r, "id parameter i is not set")
return
}
for _, pair := range Keys {
if pair.Id == id {
fmt.Fprint(w, pair.Key)
return
}
}
reject(w, r, "no key found for id "+id)
}