-
Notifications
You must be signed in to change notification settings - Fork 0
/
rmtapi.go
47 lines (37 loc) · 1.15 KB
/
rmtapi.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
package main
import (
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
)
func rmtAPIRequest(url string, token string) (string, error) {
fmt.Println("Fetching remote", url)
req, err := http.NewRequest("GET", url, nil)
if err != nil {
return "", fmt.Errorf("couldn't create request. %v", err)
}
req.Header.Set("Accept", "application/json")
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Authorization", "Bearer "+token)
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
return "", fmt.Errorf("couldn't execute request with client. %v", err)
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return "", fmt.Errorf("error reading request. %v", err)
}
// Check if it's json containing an error
var jsonError map[string]interface{}
err = json.Unmarshal(body, &jsonError)
rmtErr, hasKey := jsonError["error"]
// If body doesn't contain json or no error
if err != nil || (err == nil && !hasKey) {
return string(body), nil
}
rmtErrDesc, _ := jsonError["error_description"]
return string(body), fmt.Errorf(fmt.Sprintf("remote error %v, description: %v", rmtErr, rmtErrDesc))
}