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"
|
|
|
|
"io/ioutil"
|
|
|
|
"net/http"
|
|
|
|
"net/url"
|
|
|
|
|
|
|
|
"github.com/micro/go-micro/network/resolver"
|
|
|
|
)
|
|
|
|
|
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-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-07-28 14:14:40 +03:00
|
|
|
proto := "http"
|
|
|
|
path := "/network"
|
|
|
|
|
|
|
|
if len(r.Proto) > 0 {
|
|
|
|
proto = r.Proto
|
|
|
|
}
|
|
|
|
|
|
|
|
if len(r.Path) > 0 {
|
|
|
|
path = r.Path
|
|
|
|
}
|
|
|
|
|
|
|
|
uri := &url.URL{
|
|
|
|
Scheme: proto,
|
|
|
|
Path: path,
|
2019-07-28 22:00:09 +03:00
|
|
|
Host: name,
|
2019-07-28 14:14:40 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
rsp, err := http.Get(uri.String())
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
defer rsp.Body.Close()
|
|
|
|
|
|
|
|
b, err := ioutil.ReadAll(rsp.Body)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
// encoding format is assumed to be json
|
|
|
|
var records []*resolver.Record
|
|
|
|
|
|
|
|
if err := json.Unmarshal(b, &records); err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
return records, nil
|
|
|
|
}
|