2020-05-21 20:36:49 +00:00
|
|
|
package tunnelstore
|
|
|
|
|
|
|
|
import (
|
|
|
|
"bytes"
|
|
|
|
"encoding/json"
|
|
|
|
"fmt"
|
|
|
|
"io"
|
|
|
|
"net/http"
|
2020-08-05 10:49:53 +00:00
|
|
|
"net/url"
|
|
|
|
"path"
|
2020-05-21 20:36:49 +00:00
|
|
|
"strings"
|
|
|
|
"time"
|
|
|
|
|
2020-06-11 23:44:39 +00:00
|
|
|
"github.com/google/uuid"
|
2020-05-21 20:36:49 +00:00
|
|
|
"github.com/pkg/errors"
|
2020-11-25 06:55:13 +00:00
|
|
|
"github.com/rs/zerolog"
|
2020-05-21 20:36:49 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
const (
|
|
|
|
defaultTimeout = 15 * time.Second
|
|
|
|
jsonContentType = "application/json"
|
|
|
|
)
|
|
|
|
|
|
|
|
var (
|
|
|
|
ErrTunnelNameConflict = errors.New("tunnel with name already exists")
|
|
|
|
ErrUnauthorized = errors.New("unauthorized")
|
|
|
|
ErrBadRequest = errors.New("incorrect request parameters")
|
|
|
|
ErrNotFound = errors.New("not found")
|
2020-09-22 21:28:05 +00:00
|
|
|
ErrAPINoSuccess = errors.New("API call failed")
|
2020-05-21 20:36:49 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
type Tunnel struct {
|
2020-07-06 08:01:48 +00:00
|
|
|
ID uuid.UUID `json:"id"`
|
2020-06-11 23:44:39 +00:00
|
|
|
Name string `json:"name"`
|
|
|
|
CreatedAt time.Time `json:"created_at"`
|
2020-06-16 22:55:33 +00:00
|
|
|
DeletedAt time.Time `json:"deleted_at"`
|
2020-06-11 23:44:39 +00:00
|
|
|
Connections []Connection `json:"connections"`
|
|
|
|
}
|
|
|
|
|
|
|
|
type Connection struct {
|
2020-08-05 20:43:56 +00:00
|
|
|
ColoName string `json:"colo_name"`
|
2020-09-22 21:28:05 +00:00
|
|
|
ID uuid.UUID `json:"id"`
|
2020-08-05 20:43:56 +00:00
|
|
|
IsPendingReconnect bool `json:"is_pending_reconnect"`
|
2020-05-21 20:36:49 +00:00
|
|
|
}
|
|
|
|
|
2020-09-17 20:19:47 +00:00
|
|
|
type Change = string
|
|
|
|
|
|
|
|
const (
|
|
|
|
ChangeNew = "new"
|
|
|
|
ChangeUpdated = "updated"
|
|
|
|
ChangeUnchanged = "unchanged"
|
|
|
|
)
|
|
|
|
|
2020-07-06 08:01:48 +00:00
|
|
|
// Route represents a record type that can route to a tunnel
|
|
|
|
type Route interface {
|
|
|
|
json.Marshaler
|
|
|
|
RecordType() string
|
2020-09-17 20:19:47 +00:00
|
|
|
UnmarshalResult(body io.Reader) (RouteResult, error)
|
|
|
|
}
|
|
|
|
|
|
|
|
type RouteResult interface {
|
2020-07-30 14:33:10 +00:00
|
|
|
// SuccessSummary explains what will route to this tunnel when it's provisioned successfully
|
|
|
|
SuccessSummary() string
|
2020-07-06 08:01:48 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
type DNSRoute struct {
|
|
|
|
userHostname string
|
|
|
|
}
|
|
|
|
|
2020-09-17 20:19:47 +00:00
|
|
|
type DNSRouteResult struct {
|
|
|
|
route *DNSRoute
|
|
|
|
CName Change `json:"cname"`
|
|
|
|
}
|
|
|
|
|
2020-07-06 08:01:48 +00:00
|
|
|
func NewDNSRoute(userHostname string) Route {
|
|
|
|
return &DNSRoute{
|
|
|
|
userHostname: userHostname,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func (dr *DNSRoute) MarshalJSON() ([]byte, error) {
|
|
|
|
s := struct {
|
|
|
|
Type string `json:"type"`
|
|
|
|
UserHostname string `json:"user_hostname"`
|
|
|
|
}{
|
|
|
|
Type: dr.RecordType(),
|
|
|
|
UserHostname: dr.userHostname,
|
|
|
|
}
|
|
|
|
return json.Marshal(&s)
|
|
|
|
}
|
|
|
|
|
2020-09-17 20:19:47 +00:00
|
|
|
func (dr *DNSRoute) UnmarshalResult(body io.Reader) (RouteResult, error) {
|
|
|
|
var result DNSRouteResult
|
2020-09-22 21:28:05 +00:00
|
|
|
err := parseResponse(body, &result)
|
2020-09-17 20:19:47 +00:00
|
|
|
result.route = dr
|
2020-09-22 21:28:05 +00:00
|
|
|
return &result, err
|
2020-09-17 20:19:47 +00:00
|
|
|
}
|
|
|
|
|
2020-07-06 08:01:48 +00:00
|
|
|
func (dr *DNSRoute) RecordType() string {
|
|
|
|
return "dns"
|
|
|
|
}
|
|
|
|
|
2020-09-17 20:19:47 +00:00
|
|
|
func (res *DNSRouteResult) SuccessSummary() string {
|
|
|
|
var msgFmt string
|
|
|
|
switch res.CName {
|
|
|
|
case ChangeNew:
|
|
|
|
msgFmt = "Added CNAME %s which will route to this tunnel"
|
|
|
|
case ChangeUpdated: // this is not currently returned by tunnelsore
|
|
|
|
msgFmt = "%s updated to route to your tunnel"
|
|
|
|
case ChangeUnchanged:
|
|
|
|
msgFmt = "%s is already configured to route to your tunnel"
|
|
|
|
}
|
|
|
|
return fmt.Sprintf(msgFmt, res.route.userHostname)
|
2020-07-30 14:33:10 +00:00
|
|
|
}
|
|
|
|
|
2020-07-06 08:01:48 +00:00
|
|
|
type LBRoute struct {
|
|
|
|
lbName string
|
|
|
|
lbPool string
|
|
|
|
}
|
|
|
|
|
2020-09-17 20:19:47 +00:00
|
|
|
type LBRouteResult struct {
|
|
|
|
route *LBRoute
|
|
|
|
LoadBalancer Change `json:"load_balancer"`
|
|
|
|
Pool Change `json:"pool"`
|
|
|
|
}
|
|
|
|
|
2020-07-06 08:01:48 +00:00
|
|
|
func NewLBRoute(lbName, lbPool string) Route {
|
|
|
|
return &LBRoute{
|
|
|
|
lbName: lbName,
|
|
|
|
lbPool: lbPool,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func (lr *LBRoute) MarshalJSON() ([]byte, error) {
|
|
|
|
s := struct {
|
|
|
|
Type string `json:"type"`
|
|
|
|
LBName string `json:"lb_name"`
|
|
|
|
LBPool string `json:"lb_pool"`
|
|
|
|
}{
|
|
|
|
Type: lr.RecordType(),
|
|
|
|
LBName: lr.lbName,
|
|
|
|
LBPool: lr.lbPool,
|
|
|
|
}
|
|
|
|
return json.Marshal(&s)
|
|
|
|
}
|
|
|
|
|
|
|
|
func (lr *LBRoute) RecordType() string {
|
|
|
|
return "lb"
|
|
|
|
}
|
|
|
|
|
2020-09-17 20:19:47 +00:00
|
|
|
func (lr *LBRoute) UnmarshalResult(body io.Reader) (RouteResult, error) {
|
|
|
|
var result LBRouteResult
|
2020-09-22 21:28:05 +00:00
|
|
|
err := parseResponse(body, &result)
|
2020-09-17 20:19:47 +00:00
|
|
|
result.route = lr
|
2020-09-22 21:28:05 +00:00
|
|
|
return &result, err
|
2020-09-17 20:19:47 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
func (res *LBRouteResult) SuccessSummary() string {
|
|
|
|
var msg string
|
|
|
|
switch res.LoadBalancer + "," + res.Pool {
|
|
|
|
case "new,new":
|
|
|
|
msg = "Created load balancer %s and added a new pool %s with this tunnel as an origin"
|
|
|
|
case "new,updated":
|
|
|
|
msg = "Created load balancer %s with an existing pool %s which was updated to use this tunnel as an origin"
|
|
|
|
case "new,unchanged":
|
|
|
|
msg = "Created load balancer %s with an existing pool %s which already has this tunnel as an origin"
|
|
|
|
case "updated,new":
|
|
|
|
msg = "Added new pool %[2]s with this tunnel as an origin to load balancer %[1]s"
|
|
|
|
case "updated,updated":
|
|
|
|
msg = "Updated pool %[2]s to use this tunnel as an origin and added it to load balancer %[1]s"
|
|
|
|
case "updated,unchanged":
|
|
|
|
msg = "Added pool %[2]s, which already has this tunnel as an origin, to load balancer %[1]s"
|
|
|
|
case "unchanged,updated":
|
|
|
|
msg = "Added this tunnel as an origin in pool %[2]s which is already used by load balancer %[1]s"
|
|
|
|
case "unchanged,unchanged":
|
|
|
|
msg = "Load balancer %s already uses pool %s which has this tunnel as an origin"
|
|
|
|
case "unchanged,new":
|
|
|
|
// this state is not possible
|
|
|
|
fallthrough
|
|
|
|
default:
|
|
|
|
msg = "Something went wrong: failed to modify load balancer %s with pool %s; please check traffic manager configuration in the dashboard"
|
|
|
|
}
|
|
|
|
|
|
|
|
return fmt.Sprintf(msg, res.route.lbName, res.route.lbPool)
|
2020-07-30 14:33:10 +00:00
|
|
|
}
|
|
|
|
|
2020-05-21 20:36:49 +00:00
|
|
|
type Client interface {
|
2020-06-15 18:33:41 +00:00
|
|
|
CreateTunnel(name string, tunnelSecret []byte) (*Tunnel, error)
|
2020-07-06 08:01:48 +00:00
|
|
|
GetTunnel(tunnelID uuid.UUID) (*Tunnel, error)
|
|
|
|
DeleteTunnel(tunnelID uuid.UUID) error
|
2020-08-07 12:29:53 +00:00
|
|
|
ListTunnels(filter *Filter) ([]*Tunnel, error)
|
2020-07-06 08:01:48 +00:00
|
|
|
CleanupConnections(tunnelID uuid.UUID) error
|
2020-09-17 20:19:47 +00:00
|
|
|
RouteTunnel(tunnelID uuid.UUID, route Route) (RouteResult, error)
|
2020-05-21 20:36:49 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
type RESTClient struct {
|
2020-07-06 08:01:48 +00:00
|
|
|
baseEndpoints *baseEndpoints
|
|
|
|
authToken string
|
2020-09-09 09:34:26 +00:00
|
|
|
userAgent string
|
2020-07-06 08:01:48 +00:00
|
|
|
client http.Client
|
2020-11-25 06:55:13 +00:00
|
|
|
log *zerolog.Logger
|
2020-07-06 08:01:48 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
type baseEndpoints struct {
|
2020-08-05 10:49:53 +00:00
|
|
|
accountLevel url.URL
|
|
|
|
zoneLevel url.URL
|
2020-05-21 20:36:49 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
var _ Client = (*RESTClient)(nil)
|
|
|
|
|
2020-11-25 06:55:13 +00:00
|
|
|
func NewRESTClient(baseURL, accountTag, zoneTag, authToken, userAgent string, log *zerolog.Logger) (*RESTClient, error) {
|
2020-05-21 20:36:49 +00:00
|
|
|
if strings.HasSuffix(baseURL, "/") {
|
|
|
|
baseURL = baseURL[:len(baseURL)-1]
|
|
|
|
}
|
2020-08-05 10:49:53 +00:00
|
|
|
accountLevelEndpoint, err := url.Parse(fmt.Sprintf("%s/accounts/%s/tunnels", baseURL, accountTag))
|
|
|
|
if err != nil {
|
|
|
|
return nil, errors.Wrap(err, "failed to create account level endpoint")
|
|
|
|
}
|
|
|
|
zoneLevelEndpoint, err := url.Parse(fmt.Sprintf("%s/zones/%s/tunnels", baseURL, zoneTag))
|
|
|
|
if err != nil {
|
|
|
|
return nil, errors.Wrap(err, "failed to create account level endpoint")
|
|
|
|
}
|
2020-05-21 20:36:49 +00:00
|
|
|
return &RESTClient{
|
2020-07-06 08:01:48 +00:00
|
|
|
baseEndpoints: &baseEndpoints{
|
2020-08-05 10:49:53 +00:00
|
|
|
accountLevel: *accountLevelEndpoint,
|
|
|
|
zoneLevel: *zoneLevelEndpoint,
|
2020-07-06 08:01:48 +00:00
|
|
|
},
|
2020-05-21 20:36:49 +00:00
|
|
|
authToken: authToken,
|
2020-09-09 09:34:26 +00:00
|
|
|
userAgent: userAgent,
|
2020-05-21 20:36:49 +00:00
|
|
|
client: http.Client{
|
|
|
|
Transport: &http.Transport{
|
|
|
|
TLSHandshakeTimeout: defaultTimeout,
|
|
|
|
ResponseHeaderTimeout: defaultTimeout,
|
|
|
|
},
|
|
|
|
Timeout: defaultTimeout,
|
|
|
|
},
|
2020-11-25 06:55:13 +00:00
|
|
|
log: log,
|
2020-08-05 10:49:53 +00:00
|
|
|
}, nil
|
2020-05-21 20:36:49 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
type newTunnel struct {
|
2020-06-15 18:33:41 +00:00
|
|
|
Name string `json:"name"`
|
|
|
|
TunnelSecret []byte `json:"tunnel_secret"`
|
2020-05-21 20:36:49 +00:00
|
|
|
}
|
|
|
|
|
2020-06-15 18:33:41 +00:00
|
|
|
func (r *RESTClient) CreateTunnel(name string, tunnelSecret []byte) (*Tunnel, error) {
|
2020-05-21 20:36:49 +00:00
|
|
|
if name == "" {
|
|
|
|
return nil, errors.New("tunnel name required")
|
|
|
|
}
|
2020-08-18 21:54:05 +00:00
|
|
|
if _, err := uuid.Parse(name); err == nil {
|
|
|
|
return nil, errors.New("you cannot use UUIDs as tunnel names")
|
|
|
|
}
|
2020-07-21 21:15:48 +00:00
|
|
|
body := &newTunnel{
|
2020-06-15 18:33:41 +00:00
|
|
|
Name: name,
|
|
|
|
TunnelSecret: tunnelSecret,
|
2020-05-21 20:36:49 +00:00
|
|
|
}
|
|
|
|
|
2020-07-21 21:15:48 +00:00
|
|
|
resp, err := r.sendRequest("POST", r.baseEndpoints.accountLevel, body)
|
2020-05-21 20:36:49 +00:00
|
|
|
if err != nil {
|
|
|
|
return nil, errors.Wrap(err, "REST request failed")
|
|
|
|
}
|
|
|
|
defer resp.Body.Close()
|
|
|
|
|
|
|
|
switch resp.StatusCode {
|
|
|
|
case http.StatusOK:
|
|
|
|
return unmarshalTunnel(resp.Body)
|
|
|
|
case http.StatusConflict:
|
|
|
|
return nil, ErrTunnelNameConflict
|
|
|
|
}
|
|
|
|
|
2020-07-21 21:15:48 +00:00
|
|
|
return nil, r.statusCodeToError("create tunnel", resp)
|
2020-05-21 20:36:49 +00:00
|
|
|
}
|
|
|
|
|
2020-07-06 08:01:48 +00:00
|
|
|
func (r *RESTClient) GetTunnel(tunnelID uuid.UUID) (*Tunnel, error) {
|
2020-08-05 10:49:53 +00:00
|
|
|
endpoint := r.baseEndpoints.accountLevel
|
|
|
|
endpoint.Path = path.Join(endpoint.Path, fmt.Sprintf("%v", tunnelID))
|
2020-07-06 08:01:48 +00:00
|
|
|
resp, err := r.sendRequest("GET", endpoint, nil)
|
2020-05-21 20:36:49 +00:00
|
|
|
if err != nil {
|
|
|
|
return nil, errors.Wrap(err, "REST request failed")
|
|
|
|
}
|
|
|
|
defer resp.Body.Close()
|
|
|
|
|
|
|
|
if resp.StatusCode == http.StatusOK {
|
|
|
|
return unmarshalTunnel(resp.Body)
|
|
|
|
}
|
|
|
|
|
2020-07-21 21:15:48 +00:00
|
|
|
return nil, r.statusCodeToError("get tunnel", resp)
|
2020-05-21 20:36:49 +00:00
|
|
|
}
|
|
|
|
|
2020-07-06 08:01:48 +00:00
|
|
|
func (r *RESTClient) DeleteTunnel(tunnelID uuid.UUID) error {
|
2020-08-05 10:49:53 +00:00
|
|
|
endpoint := r.baseEndpoints.accountLevel
|
|
|
|
endpoint.Path = path.Join(endpoint.Path, fmt.Sprintf("%v", tunnelID))
|
2020-07-06 08:01:48 +00:00
|
|
|
resp, err := r.sendRequest("DELETE", endpoint, nil)
|
2020-05-21 20:36:49 +00:00
|
|
|
if err != nil {
|
|
|
|
return errors.Wrap(err, "REST request failed")
|
|
|
|
}
|
|
|
|
defer resp.Body.Close()
|
|
|
|
|
2020-07-21 21:15:48 +00:00
|
|
|
return r.statusCodeToError("delete tunnel", resp)
|
2020-05-21 20:36:49 +00:00
|
|
|
}
|
|
|
|
|
2020-08-07 12:29:53 +00:00
|
|
|
func (r *RESTClient) ListTunnels(filter *Filter) ([]*Tunnel, error) {
|
2020-08-05 10:49:53 +00:00
|
|
|
endpoint := r.baseEndpoints.accountLevel
|
|
|
|
endpoint.RawQuery = filter.encode()
|
|
|
|
resp, err := r.sendRequest("GET", endpoint, nil)
|
2020-05-21 20:36:49 +00:00
|
|
|
if err != nil {
|
|
|
|
return nil, errors.Wrap(err, "REST request failed")
|
|
|
|
}
|
|
|
|
defer resp.Body.Close()
|
|
|
|
|
|
|
|
if resp.StatusCode == http.StatusOK {
|
2020-09-22 21:28:05 +00:00
|
|
|
return parseListTunnels(resp.Body)
|
2020-05-21 20:36:49 +00:00
|
|
|
}
|
|
|
|
|
2020-07-21 21:15:48 +00:00
|
|
|
return nil, r.statusCodeToError("list tunnels", resp)
|
2020-07-03 08:55:11 +00:00
|
|
|
}
|
|
|
|
|
2020-09-22 21:28:05 +00:00
|
|
|
func parseListTunnels(body io.ReadCloser) ([]*Tunnel, error) {
|
|
|
|
var tunnels []*Tunnel
|
|
|
|
err := parseResponse(body, &tunnels)
|
|
|
|
return tunnels, err
|
|
|
|
}
|
|
|
|
|
2020-07-06 08:01:48 +00:00
|
|
|
func (r *RESTClient) CleanupConnections(tunnelID uuid.UUID) error {
|
2020-08-05 10:49:53 +00:00
|
|
|
endpoint := r.baseEndpoints.accountLevel
|
|
|
|
endpoint.Path = path.Join(endpoint.Path, fmt.Sprintf("%v/connections", tunnelID))
|
2020-07-06 08:01:48 +00:00
|
|
|
resp, err := r.sendRequest("DELETE", endpoint, nil)
|
2020-07-03 08:55:11 +00:00
|
|
|
if err != nil {
|
|
|
|
return errors.Wrap(err, "REST request failed")
|
|
|
|
}
|
|
|
|
defer resp.Body.Close()
|
|
|
|
|
2020-07-21 21:15:48 +00:00
|
|
|
return r.statusCodeToError("cleanup connections", resp)
|
2020-05-21 20:36:49 +00:00
|
|
|
}
|
|
|
|
|
2020-09-17 20:19:47 +00:00
|
|
|
func (r *RESTClient) RouteTunnel(tunnelID uuid.UUID, route Route) (RouteResult, error) {
|
2020-08-05 10:49:53 +00:00
|
|
|
endpoint := r.baseEndpoints.zoneLevel
|
|
|
|
endpoint.Path = path.Join(endpoint.Path, fmt.Sprintf("%v/routes", tunnelID))
|
2020-07-21 21:15:48 +00:00
|
|
|
resp, err := r.sendRequest("PUT", endpoint, route)
|
2020-07-06 08:01:48 +00:00
|
|
|
if err != nil {
|
2020-09-17 20:19:47 +00:00
|
|
|
return nil, errors.Wrap(err, "REST request failed")
|
2020-05-21 20:36:49 +00:00
|
|
|
}
|
2020-07-06 08:01:48 +00:00
|
|
|
defer resp.Body.Close()
|
|
|
|
|
2020-09-17 20:19:47 +00:00
|
|
|
if resp.StatusCode == http.StatusOK {
|
|
|
|
return route.UnmarshalResult(resp.Body)
|
|
|
|
}
|
|
|
|
|
|
|
|
return nil, r.statusCodeToError("add route", resp)
|
2020-05-21 20:36:49 +00:00
|
|
|
}
|
|
|
|
|
2020-08-05 10:49:53 +00:00
|
|
|
func (r *RESTClient) sendRequest(method string, url url.URL, body interface{}) (*http.Response, error) {
|
2020-07-21 21:15:48 +00:00
|
|
|
var bodyReader io.Reader
|
|
|
|
if body != nil {
|
|
|
|
if bodyBytes, err := json.Marshal(body); err != nil {
|
|
|
|
return nil, errors.Wrap(err, "failed to serialize json body")
|
|
|
|
} else {
|
|
|
|
bodyReader = bytes.NewBuffer(bodyBytes)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-08-05 10:49:53 +00:00
|
|
|
req, err := http.NewRequest(method, url.String(), bodyReader)
|
2020-05-21 20:36:49 +00:00
|
|
|
if err != nil {
|
|
|
|
return nil, errors.Wrapf(err, "can't create %s request", method)
|
|
|
|
}
|
2020-09-09 09:34:26 +00:00
|
|
|
req.Header.Set("User-Agent", r.userAgent)
|
2020-07-21 21:15:48 +00:00
|
|
|
if bodyReader != nil {
|
2020-05-21 20:36:49 +00:00
|
|
|
req.Header.Set("Content-Type", jsonContentType)
|
|
|
|
}
|
|
|
|
req.Header.Add("X-Auth-User-Service-Key", r.authToken)
|
2020-09-22 21:28:05 +00:00
|
|
|
req.Header.Add("Accept", "application/json;version=1")
|
2020-05-21 20:36:49 +00:00
|
|
|
return r.client.Do(req)
|
|
|
|
}
|
|
|
|
|
2020-09-22 21:28:05 +00:00
|
|
|
func parseResponse(reader io.Reader, data interface{}) error {
|
|
|
|
// Schema for Tunnelstore responses in the v1 API.
|
|
|
|
// Roughly, it's a wrapper around a particular result that adds failures/errors/etc
|
2020-10-02 13:40:23 +00:00
|
|
|
var result response
|
2020-09-22 21:28:05 +00:00
|
|
|
// First, parse the wrapper and check the API call succeeded
|
|
|
|
if err := json.NewDecoder(reader).Decode(&result); err != nil {
|
|
|
|
return errors.Wrap(err, "failed to decode response")
|
|
|
|
}
|
2020-10-02 13:40:23 +00:00
|
|
|
if err := result.checkErrors(); err != nil {
|
2020-09-22 21:28:05 +00:00
|
|
|
return err
|
|
|
|
}
|
|
|
|
if !result.Success {
|
|
|
|
return ErrAPINoSuccess
|
|
|
|
}
|
|
|
|
// At this point we know the API call succeeded, so, parse out the inner
|
|
|
|
// result into the datatype provided as a parameter.
|
|
|
|
return json.Unmarshal(result.Result, &data)
|
|
|
|
}
|
|
|
|
|
2020-05-21 20:36:49 +00:00
|
|
|
func unmarshalTunnel(reader io.Reader) (*Tunnel, error) {
|
|
|
|
var tunnel Tunnel
|
2020-09-22 21:28:05 +00:00
|
|
|
err := parseResponse(reader, &tunnel)
|
|
|
|
return &tunnel, err
|
|
|
|
}
|
|
|
|
|
2020-10-02 13:40:23 +00:00
|
|
|
type response struct {
|
|
|
|
Success bool `json:"success,omitempty"`
|
|
|
|
Errors []apiErr `json:"errors,omitempty"`
|
|
|
|
Messages []string `json:"messages,omitempty"`
|
|
|
|
Result json.RawMessage `json:"result,omitempty"`
|
|
|
|
}
|
|
|
|
|
|
|
|
func (r *response) checkErrors() error {
|
|
|
|
if len(r.Errors) == 0 {
|
2020-09-22 21:28:05 +00:00
|
|
|
return nil
|
|
|
|
}
|
2020-10-02 13:40:23 +00:00
|
|
|
if len(r.Errors) == 1 {
|
|
|
|
return r.Errors[0]
|
2020-05-21 20:36:49 +00:00
|
|
|
}
|
2020-10-02 13:40:23 +00:00
|
|
|
var messages string
|
|
|
|
for _, e := range r.Errors {
|
|
|
|
messages += fmt.Sprintf("%s; ", e)
|
|
|
|
}
|
|
|
|
return fmt.Errorf("API errors: %s", messages)
|
|
|
|
}
|
|
|
|
|
|
|
|
type apiErr struct {
|
|
|
|
Code json.Number `json:"code,omitempty"`
|
|
|
|
Message string `json:"message,omitempty"`
|
|
|
|
}
|
|
|
|
|
|
|
|
func (e apiErr) Error() string {
|
|
|
|
return fmt.Sprintf("code: %v, reason: %s", e.Code, e.Message)
|
2020-05-21 20:36:49 +00:00
|
|
|
}
|
|
|
|
|
2020-07-21 21:15:48 +00:00
|
|
|
func (r *RESTClient) statusCodeToError(op string, resp *http.Response) error {
|
2020-09-11 22:12:00 +00:00
|
|
|
if resp.Header.Get("Content-Type") == "application/json" {
|
2020-10-02 13:40:23 +00:00
|
|
|
var errorsResp response
|
|
|
|
if json.NewDecoder(resp.Body).Decode(&errorsResp) == nil {
|
|
|
|
if err := errorsResp.checkErrors(); err != nil {
|
|
|
|
return errors.Errorf("Failed to %s: %s", op, err)
|
|
|
|
}
|
2020-09-11 22:12:00 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-05-21 20:36:49 +00:00
|
|
|
switch resp.StatusCode {
|
|
|
|
case http.StatusOK:
|
|
|
|
return nil
|
|
|
|
case http.StatusBadRequest:
|
|
|
|
return ErrBadRequest
|
|
|
|
case http.StatusUnauthorized, http.StatusForbidden:
|
|
|
|
return ErrUnauthorized
|
|
|
|
case http.StatusNotFound:
|
|
|
|
return ErrNotFound
|
|
|
|
}
|
2020-07-03 08:55:11 +00:00
|
|
|
return errors.Errorf("API call to %s failed with status %d: %s", op,
|
2020-05-21 20:36:49 +00:00
|
|
|
resp.StatusCode, http.StatusText(resp.StatusCode))
|
|
|
|
}
|