github.com/annwntech/go-micro/v2@v2.9.5/network/resolver/http/http.go (about) 1 // Package http resolves names to network addresses using a http request 2 package http 3 4 import ( 5 "encoding/json" 6 "errors" 7 "io/ioutil" 8 "net/http" 9 "net/url" 10 11 "github.com/annwntech/go-micro/v2/network/resolver" 12 ) 13 14 // Resolver is a HTTP network resolver 15 type Resolver struct { 16 // If not set, defaults to http 17 Proto string 18 19 // Path sets the path to lookup. Defaults to /network 20 Path string 21 22 // Host url to use for the query 23 Host string 24 } 25 26 type Response struct { 27 Nodes []*resolver.Record `json:"nodes,omitempty"` 28 } 29 30 // Resolve assumes ID is a domain which can be converted to a http://name/network request 31 func (r *Resolver) Resolve(name string) ([]*resolver.Record, error) { 32 proto := "https" 33 host := "go.micro.mu" 34 path := "/network/nodes" 35 36 if len(r.Proto) > 0 { 37 proto = r.Proto 38 } 39 40 if len(r.Path) > 0 { 41 path = r.Path 42 } 43 44 if len(r.Host) > 0 { 45 host = r.Host 46 } 47 48 uri := &url.URL{ 49 Scheme: proto, 50 Path: path, 51 Host: host, 52 } 53 q := uri.Query() 54 q.Set("name", name) 55 uri.RawQuery = q.Encode() 56 57 rsp, err := http.Get(uri.String()) 58 if err != nil { 59 return nil, err 60 } 61 defer rsp.Body.Close() 62 if rsp.StatusCode != 200 { 63 return nil, errors.New("non 200 response") 64 } 65 b, err := ioutil.ReadAll(rsp.Body) 66 if err != nil { 67 return nil, err 68 } 69 70 // encoding format is assumed to be json 71 var response *Response 72 73 if err := json.Unmarshal(b, &response); err != nil { 74 return nil, err 75 } 76 77 return response.Nodes, nil 78 }