2019-07-28 22:00:09 +03:00
|
|
|
// Package http resolves names to network addresses using a http request
|
2019-07-28 14:14:40 +03:00
|
|
|
package http
|
|
|
|
|
|
|
|
import (
|
|
|
|
"encoding/json"
|
2019-09-25 18:53:06 +03:00
|
|
|
"errors"
|
2019-07-28 14:14:40 +03:00
|
|
|
"io/ioutil"
|
|
|
|
"net/http"
|
|
|
|
"net/url"
|
|
|
|
|
2020-01-30 14:39:00 +03:00
|
|
|
"github.com/micro/go-micro/v2/network/resolver"
|
2019-07-28 14:14:40 +03:00
|
|
|
)
|
|
|
|
|
2019-08-20 14:48:51 +03:00
|
|
|
// Resolver is a HTTP network resolver
|
2019-07-28 14:14:40 +03:00
|
|
|
type Resolver struct {
|
|
|
|
// If not set, defaults to http
|
|
|
|
Proto string
|
|
|
|
|
|
|
|
// Path sets the path to lookup. Defaults to /network
|
|
|
|
Path string
|
2019-09-23 19:50:53 +03:00
|
|
|
|
|
|
|
// Host url to use for the query
|
|
|
|
Host string
|
|
|
|
}
|
|
|
|
|
|
|
|
type Response struct {
|
|
|
|
Nodes []*resolver.Record `json:"nodes,omitempty"`
|
2019-07-28 14:14:40 +03:00
|
|
|
}
|
|
|
|
|
2019-07-28 22:00:09 +03:00
|
|
|
// Resolve assumes ID is a domain which can be converted to a http://name/network request
|
|
|
|
func (r *Resolver) Resolve(name string) ([]*resolver.Record, error) {
|
2019-09-23 19:50:53 +03:00
|
|
|
proto := "https"
|
2020-04-19 19:03:25 +03:00
|
|
|
host := "go.micro.mu"
|
2020-04-18 23:00:00 +03:00
|
|
|
path := "/network/nodes"
|
2019-07-28 14:14:40 +03:00
|
|
|
|
|
|
|
if len(r.Proto) > 0 {
|
|
|
|
proto = r.Proto
|
|
|
|
}
|
|
|
|
|
|
|
|
if len(r.Path) > 0 {
|
|
|
|
path = r.Path
|
|
|
|
}
|
|
|
|
|
2019-09-23 19:50:53 +03:00
|
|
|
if len(r.Host) > 0 {
|
|
|
|
host = r.Host
|
|
|
|
}
|
|
|
|
|
2019-07-28 14:14:40 +03:00
|
|
|
uri := &url.URL{
|
|
|
|
Scheme: proto,
|
|
|
|
Path: path,
|
2019-09-23 19:50:53 +03:00
|
|
|
Host: host,
|
2019-07-28 14:14:40 +03:00
|
|
|
}
|
2019-09-23 19:50:53 +03:00
|
|
|
q := uri.Query()
|
|
|
|
q.Set("name", name)
|
|
|
|
uri.RawQuery = q.Encode()
|
2019-07-28 14:14:40 +03:00
|
|
|
|
|
|
|
rsp, err := http.Get(uri.String())
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
defer rsp.Body.Close()
|
2019-09-25 18:53:06 +03:00
|
|
|
if rsp.StatusCode != 200 {
|
|
|
|
return nil, errors.New("non 200 response")
|
|
|
|
}
|
2019-07-28 14:14:40 +03:00
|
|
|
b, err := ioutil.ReadAll(rsp.Body)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
// encoding format is assumed to be json
|
2019-09-23 19:50:53 +03:00
|
|
|
var response *Response
|
2019-07-28 14:14:40 +03:00
|
|
|
|
2019-09-23 19:50:53 +03:00
|
|
|
if err := json.Unmarshal(b, &response); err != nil {
|
2019-07-28 14:14:40 +03:00
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
2019-09-23 19:50:53 +03:00
|
|
|
return response.Nodes, nil
|
2019-07-28 14:14:40 +03:00
|
|
|
}
|