github.com/ethersphere/bee/v2@v2.2.0/pkg/util/nbhdutil/neighborhoodsuggestion.go (about) 1 // Copyright 2024 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 nbhdutil 6 7 import ( 8 "encoding/json" 9 "fmt" 10 "io" 11 "net/http" 12 "net/url" 13 14 "github.com/ethersphere/bee/v2/pkg/swarm" 15 ) 16 17 type httpClient interface { 18 Get(url string) (*http.Response, error) 19 } 20 21 func FetchNeighborhood(client httpClient, suggester string) (string, error) { 22 if suggester == "" { 23 return "", nil 24 } 25 26 _, err := url.ParseRequestURI(suggester) 27 if err != nil { 28 return "", err 29 } 30 31 type suggestionRes struct { 32 Neighborhood string `json:"neighborhood"` 33 } 34 res, err := client.Get(suggester) 35 if err != nil { 36 return "", err 37 } 38 defer res.Body.Close() 39 var suggestion suggestionRes 40 d, err := io.ReadAll(res.Body) 41 if err != nil { 42 return "", err 43 } 44 err = json.Unmarshal(d, &suggestion) 45 if err != nil { 46 return "", err 47 } 48 _, err = swarm.ParseBitStrAddress(suggestion.Neighborhood) 49 if err != nil { 50 return "", fmt.Errorf("invalid neighborhood. %s", suggestion.Neighborhood) 51 } 52 return suggestion.Neighborhood, nil 53 }