-
Notifications
You must be signed in to change notification settings - Fork 15
/
connect_handler.go
57 lines (49 loc) 路 1.33 KB
/
connect_handler.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
package adminserver
import (
"fmt"
"net/http"
"github.com/libp2p/go-libp2p/core/peer"
ma "github.com/multiformats/go-multiaddr"
)
func (s *Server) connectHandler(w http.ResponseWriter, r *http.Request) {
if !methodOK(w, r, http.MethodPost) {
return
}
if !matchContentTypeJson(w, r) {
return
}
// Decode request
var req ConnectReq
if _, err := req.ReadFrom(r.Body); err != nil {
msg := fmt.Sprintf("failed to unmarshal request: %v", err)
log.Errorw(msg, err, err)
http.Error(w, msg, http.StatusBadRequest)
return
}
maddr, err := ma.NewMultiaddr(req.Maddr)
if err != nil {
msg := fmt.Sprintf("failed to parse multiaddr: %v", err)
log.Errorw(msg, "err", err)
http.Error(w, msg, http.StatusBadRequest)
return
}
addrInfo, err := peer.AddrInfoFromP2pAddr(maddr)
if err != nil {
msg := fmt.Sprintf("failed to create addrInfo from multiaddr: %v", err)
log.Errorw(msg, "err", err)
http.Error(w, msg, http.StatusBadRequest)
return
}
// Attempt connect.
err = s.h.Connect(r.Context(), *addrInfo)
if err != nil {
msg := fmt.Sprintf("failed to connect to peer: %v", err)
log.Errorw(msg, "err", err)
http.Error(w, msg, http.StatusInternalServerError)
return
}
// Respond success case.
log.Infow("Connected to peer successfully", "addrInfo", addrInfo)
var resp ConnectRes
respond(w, http.StatusOK, &resp)
}