-
Notifications
You must be signed in to change notification settings - Fork 0
/
psping.go
49 lines (40 loc) · 1.2 KB
/
psping.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
// Package api provides API for chestnut.
package api
import (
"context"
"net/http"
"github.com/go-playground/validator/v10"
"github.com/labstack/echo/v4"
"github.com/lixvyang/chestnut/p2p"
)
type PSPingParam struct {
PeerId string `from:"peer_id" json:"peer_id" validate:"required,max=53,min=53"`
}
type PingResult struct {
Result [10]int64 `json:"pingresult"`
}
func (h *Handler) PSPingPeer(node *p2p.Node) echo.HandlerFunc {
return func(c echo.Context) (err error) {
output := make(map[string]interface{})
params := new(PSPingParam)
validate := validator.New()
if err = c.Bind(params); err != nil {
output[ERROR_INFO] = err.Error()
return c.JSON(http.StatusBadRequest, output)
}
if err = validate.Struct(params); err != nil {
output[ERROR_INFO] = err.Error()
return c.JSON(http.StatusBadRequest, output)
}
ctx, cancel := context.WithCancel(context.Background())
psping := p2p.NewPSPingService(ctx, node.Pubsub, node.Host.ID())
result, err := psping.PingReq(params.PeerId)
defer cancel()
if err != nil {
output[ERROR_INFO] = err.Error()
return c.JSON(http.StatusBadRequest, output)
} else {
return c.JSON(http.StatusOK, &PingResult{result})
}
}
}