github.com/ethersphere/bee/v2@v2.2.0/pkg/api/pingpong.go (about) 1 // Copyright 2020 The Swarm Authors. All rights reserved. 2 // Use of this source code is governed by a BSD-style 3 // license that can be found in the LICENSE file. 4 5 package api 6 7 import ( 8 "errors" 9 "net/http" 10 11 "github.com/ethersphere/bee/v2/pkg/jsonhttp" 12 "github.com/ethersphere/bee/v2/pkg/p2p" 13 "github.com/ethersphere/bee/v2/pkg/swarm" 14 "github.com/gorilla/mux" 15 ) 16 17 type pingpongResponse struct { 18 RTT string `json:"rtt"` 19 } 20 21 func (s *Service) pingpongHandler(w http.ResponseWriter, r *http.Request) { 22 logger := s.logger.WithName("post_pinpong").Build() 23 24 paths := struct { 25 Address swarm.Address `map:"address" validate:"required"` 26 }{} 27 if response := s.mapStructure(mux.Vars(r), &paths); response != nil { 28 response("invalid path params", logger, w) 29 return 30 } 31 32 ctx := r.Context() 33 span, logger, ctx := s.tracer.StartSpanFromContext(ctx, "pingpong-api", logger) 34 defer span.Finish() 35 36 rtt, err := s.pingpong.Ping(ctx, paths.Address, "ping") 37 if err != nil { 38 logger.Debug("pingpong: ping failed", "peer_address", paths.Address, "error", err) 39 if errors.Is(err, p2p.ErrPeerNotFound) { 40 jsonhttp.NotFound(w, "peer not found") 41 return 42 } 43 44 logger.Error(nil, "pingpong: ping failed", "peer_address", paths.Address) 45 jsonhttp.InternalServerError(w, "pingpong: ping failed") 46 return 47 } 48 49 logger.Info("pingpong: ping succeeded", "peer_address", paths.Address) 50 jsonhttp.OK(w, pingpongResponse{ 51 RTT: rtt.String(), 52 }) 53 }