-
-
Notifications
You must be signed in to change notification settings - Fork 179
/
remote_api.go
92 lines (73 loc) · 1.67 KB
/
remote_api.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
package core
import (
"fmt"
"io/ioutil"
"net/http"
"net/http/httputil"
"strings"
"github.com/dosco/graphjin/internal/jsn"
"github.com/mitchellh/mapstructure"
)
// RemoteAPI struct defines a remote API endpoint
type remoteAPI struct {
URL string
Debug bool
PassHeaders []string `mapstructure:"pass_headers"`
SetHeaders []struct {
Name string
Value string
} `mapstructure:"set_headers"`
}
func newRemoteAPI(v map[string]interface{}) (*remoteAPI, error) {
ra := &remoteAPI{}
if err := mapstructure.Decode(v, ra); err != nil {
return nil, err
}
return ra, nil
}
func (r *remoteAPI) Resolve(rr ResolverReq) ([]byte, error) {
uri := strings.ReplaceAll(r.URL, "$id", rr.ID)
req, err := http.NewRequest("GET", uri, nil)
if err != nil {
return nil, err
}
// if host, ok := hdr["Host"]; ok {
// req.Host = host[0]
// }
for _, v := range r.SetHeaders {
req.Header.Set(v.Name, v.Value)
}
// for _, v := range r.PassHeaders {
// req.Header.Set(v, hdr.Get(v))
// }
client := &http.Client{}
res, err := client.Do(req)
if err != nil {
return nil, fmt.Errorf("failed to connect to '%s': %v", uri, err)
}
defer res.Body.Close()
if r.Debug {
reqDump, err := httputil.DumpRequestOut(req, true)
if err != nil {
return nil, err
}
resDump, err := httputil.DumpResponse(res, true)
if err != nil {
return nil, err
}
rr.Log.Printf("DBG Remote Request:\n%s\n%s",
reqDump, resDump)
}
if res.StatusCode != 200 {
return nil,
fmt.Errorf("server responded with a %d", res.StatusCode)
}
b, err := ioutil.ReadAll(res.Body)
if err != nil {
return nil, err
}
if err := jsn.ValidateBytes(b); err != nil {
return nil, err
}
return b, nil
}