-
Notifications
You must be signed in to change notification settings - Fork 0
/
http.go
99 lines (75 loc) · 2.2 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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
package palworldapi
import (
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
)
const (
Endpoint = "/v1/api"
)
func (p *PalworldAPI) headers(r *http.Request) {
r.Header.Add("Content-Type", "application/json")
r.Header.Add("Authorization", p.basicAuth())
}
func (p *PalworldAPI) apiUrl(s string) string {
return "http://" + p.Host + Endpoint + s
}
func (p *PalworldAPI) request(method string, url string, body []byte) (*http.Response, error) {
req, err := http.NewRequest(method, url, bytes.NewBuffer(body))
if err != nil {
return nil, fmt.Errorf("error creating request: %w", err)
}
p.headers(req)
res, err := p.client.Do(req)
if err != nil {
return nil, fmt.Errorf("error executing request: %w", err)
}
if res.StatusCode != http.StatusOK {
if res.StatusCode == http.StatusUnauthorized {
return nil, fmt.Errorf("401: please set correct username and password - for more information read the api docs: https://tech.palworldgame.com/")
}
return nil, fmt.Errorf("http status code is %d", res.StatusCode)
}
return res, err
}
func readBody(res *http.Response) ([]byte, error) {
body, err := io.ReadAll(res.Body)
if err != nil {
return nil, fmt.Errorf("error reading response body: %w", err)
}
res.Body.Close()
return body, nil
}
// Executes a GET request to the REST API
// Response data will be written in the result param
func (p *PalworldAPI) get(path string, result interface{}) error {
res, err := p.request("GET", p.apiUrl(path), nil)
if err != nil {
return fmt.Errorf("GET request failed: %w", err)
}
body, err := readBody(res)
if err != nil {
return err
}
err = json.Unmarshal(body, result)
if err != nil {
return fmt.Errorf("error unmarshalling response: %w", err)
}
return nil
}
// Executes a POST request to the REST API
// Palworlds Server REST API doesn't provide relevant result data for POST requests other than the status code
func (p *PalworldAPI) post(path string, body interface{}) error {
jsonBody, err := json.Marshal(body)
if err != nil {
return fmt.Errorf("error marshalling body: %w", err)
}
res, err := p.request("POST", p.apiUrl(path), jsonBody)
if err != nil {
return fmt.Errorf("POST request failed: %w", err)
}
res.Body.Close()
return nil
}