/
rest.go
65 lines (56 loc) · 1.51 KB
/
rest.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
package rest
import (
"bytes"
"fmt"
"net/http"
"net/url"
)
// Method holds the support HTTP methods
type Method string
// errorString is a trivial implementation of error.
type errorString struct {
s string
}
// Supported HTTP methods
const (
// Get GET HTTP method
Get Method = "GET"
// Post POST HTTP method
Post Method = "POST"
)
// RequestData holds the API relevant informations
type RequestData struct {
Method Method
BaseURL string
Headers map[string]string
QueryParams map[string]string
Body []byte
}
// AddHeaders adds the provided headers to the request
func AddHeaders(headers map[string]string, body []byte, request *http.Request) {
if len(body) > 0 {
request.Header.Set("Content-Type", "application/json")
}
for key, value := range headers {
request.Header.Set(key, value)
}
}
// AddQueryParams adds the query params to base URL
func AddQueryParams(baseURL string, queryParams map[string]string) string {
baseURL += "?"
params := url.Values{}
for key, value := range queryParams {
params.Add(key, value)
}
return baseURL + params.Encode()
}
// BuildRequest creates the request
func BuildRequest(requestData RequestData, request *http.Request) error {
req, err := http.NewRequest(string(requestData.Method), requestData.BaseURL, bytes.NewBuffer(requestData.Body))
if err != nil {
return fmt.Errorf("failed to create new request: %v", err)
}
AddHeaders(requestData.Headers, requestData.Body, req)
AddQueryParams(requestData.BaseURL, requestData.QueryParams)
return nil
}