-
Notifications
You must be signed in to change notification settings - Fork 0
/
http.go
54 lines (42 loc) · 1.32 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
package main
import (
"errors"
"fmt"
"github.com/parnurzeal/gorequest"
)
// HTTP helper methods for sending authenticated requests to Brizo
// ---------------------------------------------------------------
// HTTPGet sends a GET request
func HTTPGet(path string) (string, error) {
request := gorequest.New().Get(buildURL(path))
requestHeaders(request)
response, body, errs := request.End()
return handleResponse(response, body, errs)
}
// HTTPPost sends a POST request
func HTTPPost(path string) (string, error) {
request := gorequest.New().Post(buildURL(path))
requestHeaders(request)
response, body, errs := request.End()
return handleResponse(response, body, errs)
}
func handleResponse(response gorequest.Response, body string, errs []error) (string, error) {
if response.StatusCode == 401 {
return "", errors.New("Unauthorized")
}
if len(errs) != 0 {
fmt.Println("Error from API")
return "", errs[0]
}
return body, nil
}
// requestHeaders configures default auth and content headers for a request
func requestHeaders(request *gorequest.SuperAgent) *gorequest.SuperAgent {
return request.
Set("Authorization", "Bearer "+Config.Token).
Set("Content-Type", "application/json")
}
// buildURL appends the provided path to the configured endpoint
func buildURL(path string) string {
return Config.Endpoint + path
}