Skip to content

Commit

Permalink
Output peers list in json
Browse files Browse the repository at this point in the history
  • Loading branch information
gammazero committed Nov 4, 2024
1 parent d8c1757 commit 9975a21
Showing 1 changed file with 20 additions and 12 deletions.
32 changes: 20 additions & 12 deletions handlers.go
Original file line number Diff line number Diff line change
Expand Up @@ -114,8 +114,7 @@ func purgePeerHandler(p2pHost host.Host) func(w http.ResponseWriter, r *http.Req
}
goLog.Infow("Purged connections", "count", purgeCount)

h := w.Header()
h.Set("Content-Type", "text/plain; charset=utf-8")
w.Header().Set("Content-Type", "text/plain; charset=utf-8")
fmt.Fprintln(w, "Peer connections purged:", purgeCount)
return

Check warning on line 119 in handlers.go

View check run for this annotation

Codecov / codecov/patch

handlers.go#L108-L119

Added lines #L108 - L119 were not covered by tests
}
Expand All @@ -134,8 +133,7 @@ func purgePeerHandler(p2pHost host.Host) func(w http.ResponseWriter, r *http.Req
}
goLog.Infow("Purged connection", "peer", peerID)

h := w.Header()
h.Set("Content-Type", "text/plain; charset=utf-8")
w.Header().Set("Content-Type", "text/plain; charset=utf-8")
fmt.Fprintln(w, "Purged connection to peer", peerID)

Check warning on line 137 in handlers.go

View check run for this annotation

Codecov / codecov/patch

handlers.go#L128-L137

Added lines #L128 - L137 were not covered by tests
}
}
Expand Down Expand Up @@ -183,18 +181,28 @@ func showPeersHandler(p2pHost host.Host) func(w http.ResponseWriter, r *http.Req
return func(w http.ResponseWriter, r *http.Request) {
defer r.Body.Close()

h := w.Header()
h.Set("Content-Type", "text/plain; charset=utf-8")
w.Header().Set("Content-Type", "application/json; charset=utf-8")

peers := p2pHost.Network().Peers()
if len(peers) == 0 {
fmt.Fprintln(w, "no connected peers")
return
body := struct {
Count int64
Peers []string
}{
Count: int64(len(peers)),
}

fmt.Fprintln(w, "Connected peers:", len(peers))
for _, peerID := range peers {
fmt.Fprintln(w, peerID.String())
if len(peers) != 0 {
peerStrs := make([]string, len(peers))
for i, peerID := range peers {
peerStrs[i] = peerID.String()
}
body.Peers = peerStrs

Check warning on line 199 in handlers.go

View check run for this annotation

Codecov / codecov/patch

handlers.go#L180-L199

Added lines #L180 - L199 were not covered by tests
}

enc := json.NewEncoder(w)
if err := enc.Encode(body); err != nil {
goLog.Errorw("cannot write response", "err", err)
http.Error(w, "", http.StatusInternalServerError)
}

Check warning on line 206 in handlers.go

View check run for this annotation

Codecov / codecov/patch

handlers.go#L202-L206

Added lines #L202 - L206 were not covered by tests
}
}
Expand Down

0 comments on commit 9975a21

Please sign in to comment.