This repository has been archived by the owner on Mar 1, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
http.go
61 lines (50 loc) · 1.56 KB
/
http.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
package cav2
import (
"bytes"
"errors"
"io/ioutil"
"net/http"
"strings"
)
//GetHTTPResponse gets response from URL (Wraps GetAuthenicatedResponse)
func GetHTTPResponse(method, url string, b []byte) (*http.Response, error) {
return GetAuthenticatedReponse(method, OAuthToken, url, b)
}
//GetAuthenticatedReponse wraps an http client with an authenication token
func GetAuthenticatedReponse(method, token, url string, b []byte) (*http.Response, error) {
client := &http.Client{}
req, err := http.NewRequest(method, url, bytes.NewReader(b))
if err != nil {
return nil, err
}
if len(token) > 0 && strings.HasPrefix(url, APIEndpoint) {
req.Header.Add("AuthenticationToken", token)
}
req.Header.Add("Content-Type", "application/json")
resp, err := client.Do(req)
if resp.StatusCode != http.StatusOK {
return resp, errors.New(resp.Status)
}
return resp, err
}
//DoHTTPRequest does a basic http request
func DoHTTPRequest(url string) (*http.Response, error) {
client := &http.Client{}
req, err := http.NewRequest("GET", url, bytes.NewReader(EMPTY))
resp, err := client.Do(req)
if resp.StatusCode != http.StatusOK {
return resp, errors.New(resp.Status)
}
return resp, err
}
//ResponseToBytes Converts an http.Response to bytes
func ResponseToBytes(response *http.Response) []byte {
bodyBytes, _ := ioutil.ReadAll(response.Body)
return bodyBytes
}
//ResponseToString Converts an http.Response to a string
func ResponseToString(response *http.Response) string {
bodyBytes, _ := ioutil.ReadAll(response.Body)
bodyString := string(bodyBytes)
return bodyString
}