github.com/tickoalcantara12/micro/v3@v3.0.0-20221007104245-9d75b9bcbab9/service/network/resolver/http/http.go (about) 1 // Licensed under the Apache License, Version 2.0 (the "License"); 2 // you may not use this file except in compliance with the License. 3 // You may obtain a copy of the License at 4 // 5 // https://www.apache.org/licenses/LICENSE-2.0 6 // 7 // Unless required by applicable law or agreed to in writing, software 8 // distributed under the License is distributed on an "AS IS" BASIS, 9 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 10 // See the License for the specific language governing permissions and 11 // limitations under the License. 12 // 13 // Original source: github.com/micro/go-micro/v3/network/resolver/http/http.go 14 15 // Package http resolves names to network addresses using a http request 16 package http 17 18 import ( 19 "encoding/json" 20 "errors" 21 "io/ioutil" 22 "net/http" 23 "net/url" 24 25 "github.com/tickoalcantara12/micro/v3/service/network/resolver" 26 ) 27 28 // Resolver is a HTTP network resolver 29 type Resolver struct { 30 // If not set, defaults to http 31 Proto string 32 33 // Path sets the path to lookup. Defaults to /network 34 Path string 35 36 // Host url to use for the query 37 Host string 38 } 39 40 type Response struct { 41 Nodes []*resolver.Record `json:"nodes,omitempty"` 42 } 43 44 // Resolve assumes ID is a domain which can be converted to a http://name/network request 45 func (r *Resolver) Resolve(name string) ([]*resolver.Record, error) { 46 proto := "http" 47 host := "localhost:8080" 48 path := "/network/nodes" 49 50 if len(r.Proto) > 0 { 51 proto = r.Proto 52 } 53 54 if len(r.Path) > 0 { 55 path = r.Path 56 } 57 58 if len(r.Host) > 0 { 59 host = r.Host 60 } 61 62 uri := &url.URL{ 63 Scheme: proto, 64 Path: path, 65 Host: host, 66 } 67 q := uri.Query() 68 q.Set("name", name) 69 uri.RawQuery = q.Encode() 70 71 rsp, err := http.Get(uri.String()) 72 if err != nil { 73 return nil, err 74 } 75 defer rsp.Body.Close() 76 if rsp.StatusCode != 200 { 77 return nil, errors.New("non 200 response") 78 } 79 b, err := ioutil.ReadAll(rsp.Body) 80 if err != nil { 81 return nil, err 82 } 83 84 // encoding format is assumed to be json 85 var response *Response 86 87 if err := json.Unmarshal(b, &response); err != nil { 88 return nil, err 89 } 90 91 return response.Nodes, nil 92 }