-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathmain.go
More file actions
118 lines (98 loc) · 2.24 KB
/
Copy pathmain.go
File metadata and controls
118 lines (98 loc) · 2.24 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
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
114
115
116
117
118
package main
import (
"crypto/subtle"
"encoding/json"
"log"
"net"
"sync"
"github.com/gorilla/mux"
"net/http"
)
type Peer struct {
PublicKey []byte
Endpoint string
IP *net.IP
}
type Store struct {
store map[string]Peer
mutex *sync.RWMutex
}
func (s *Store) write(key string, val Peer) {
s.mutex.Lock()
s.store[key] = val
s.mutex.Unlock()
}
func (s *Store) read() map[string]Peer {
s.mutex.RLock()
res := s.store
s.mutex.RUnlock()
return res
}
func joinHandler(s *Store) func(http.ResponseWriter, *http.Request) {
return func(w http.ResponseWriter, r *http.Request) {
sha := mux.Vars(r)["publickeysha"]
d := json.NewDecoder(r.Body)
peer := Peer{}
err := d.Decode(&peer)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
return
}
s.write(sha, peer)
w.WriteHeader(http.StatusCreated)
}
}
func getPeersHandler(s *Store) func(http.ResponseWriter, *http.Request) {
return func(w http.ResponseWriter, r *http.Request) {
result := s.read()
list := []Peer{}
for _, v := range result {
list = append(list, v)
}
resBody, err := json.Marshal(list)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
return
}
w.WriteHeader(http.StatusOK)
w.Write(resBody)
}
}
func basicAuthMiddleware(handler http.HandlerFunc, username, password string) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
user, pass, ok := r.BasicAuth()
if !ok || subtle.ConstantTimeCompare([]byte(user), []byte(username)) != 1 || subtle.ConstantTimeCompare([]byte(pass), []byte(password)) != 1 {
w.Header().Set("WWW-Authenticate", `Basic realm="Provide username and password"`)
w.WriteHeader(401)
w.Write([]byte("Unauthorized.\n"))
return
}
handler(w, r)
}
}
func main() {
// just an ephemeral store for this example
store := &Store{
mutex: &sync.RWMutex{},
store: map[string]Peer{},
}
username := "time"
password := "series"
r := mux.NewRouter()
r.HandleFunc(
"/{ifname}/{publickeysha}",
basicAuthMiddleware(
joinHandler(store),
username,
password,
),
).Methods("POST")
r.HandleFunc("/{ifname}",
basicAuthMiddleware(
getPeersHandler(store),
username,
password,
),
).Methods("GET")
log.Fatal(http.ListenAndServe("0.0.0.0:8080", r))
}