This repository has been archived by the owner on Nov 5, 2024. It is now read-only.
-
-
Notifications
You must be signed in to change notification settings - Fork 6
/
api.go
83 lines (66 loc) · 1.65 KB
/
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
package pi
import (
"bytes"
"encoding/json"
"fmt"
"io"
"io/ioutil"
"net/http"
"os"
)
func generateRequest(method string, path string, paramStruct interface{}) (*http.Request, error) {
apibase := os.Getenv("PIXELA_API_BASE")
if apibase == "" {
apibase = "pixe.la"
}
var reqBody io.Reader
if paramStruct != nil {
buffer := &bytes.Buffer{}
encoder := json.NewEncoder(buffer)
encoder.SetEscapeHTML(false)
err := encoder.Encode(paramStruct)
if err != nil {
return nil, fmt.Errorf("Failed to marshal options to json : %s", err)
}
b := buffer.Bytes()
b = bytes.TrimRight(b, "\n")
reqBody = bytes.NewBuffer(b)
}
req, err := http.NewRequest(
method,
fmt.Sprintf("https://%s/%s", apibase, path),
reqBody,
)
if err == nil {
req.Header.Set("Content-Type", "application/json")
}
return req, err
}
func generateRequestWithToken(method string, path string, paramStruct interface{}) (*http.Request, error) {
token := os.Getenv("PIXELA_USER_TOKEN")
if token == "" {
return nil, fmt.Errorf("token is not set. please specify your token by PIXELA_USER_TOKEN environment variable")
}
req, err := generateRequest(method, path, paramStruct)
if err == nil {
req.Header.Set("X-USER-TOKEN", token)
}
return req, err
}
func doRequest(req *http.Request) error {
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
return fmt.Errorf("Failed to request api : %s", err)
}
b, err := ioutil.ReadAll(resp.Body)
if err != nil {
return fmt.Errorf("Failed to get response body : %s", err)
}
defer resp.Body.Close()
if resp.StatusCode > 299 {
return fmt.Errorf("%s", string(b))
}
fmt.Println(string(b))
return nil
}