micro/resolver/http/http.go

80 lines
1.5 KiB
Go
Raw Permalink Normal View History

2019-07-28 22:00:09 +03:00
// Package http resolves names to network addresses using a http request
package http // import "go.unistack.org/micro/v4/resolver/http"
2019-07-28 14:14:40 +03:00
import (
"encoding/json"
"errors"
"io"
2019-07-28 14:14:40 +03:00
"net/http"
"net/url"
"go.unistack.org/micro/v4/resolver"
2019-07-28 14:14:40 +03:00
)
// nolint: golint,revive
// HTTPResolver is a HTTP network resolver
type HTTPResolver struct {
// Proto if not set, defaults to http
2019-07-28 14:14:40 +03:00
Proto string
// Path sets the path to lookup. Defaults to /network
Path string
// Host url to use for the query
Host string
}
// Response contains resolver.Record
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 *HTTPResolver) Resolve(name string) ([]*resolver.Record, error) {
proto := "http"
host := "localhost:8080"
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
}
if len(r.Host) > 0 {
host = r.Host
}
2019-07-28 14:14:40 +03:00
uri := &url.URL{
Scheme: proto,
Path: path,
Host: host,
2019-07-28 14:14:40 +03:00
}
q := uri.Query()
q.Set("name", name)
uri.RawQuery = q.Encode()
2019-07-28 14:14:40 +03:00
// nolint: noctx
2019-07-28 14:14:40 +03:00
rsp, err := http.Get(uri.String())
if err != nil {
return nil, err
}
defer rsp.Body.Close()
if rsp.StatusCode != 200 {
return nil, errors.New("non 200 response")
}
b, err := io.ReadAll(rsp.Body)
2019-07-28 14:14:40 +03:00
if err != nil {
return nil, err
}
// encoding format is assumed to be json
var response *Response
2019-07-28 14:14:40 +03:00
if err := json.Unmarshal(b, &response); err != nil {
2019-07-28 14:14:40 +03:00
return nil, err
}
return response.Nodes, nil
2019-07-28 14:14:40 +03:00
}