/
requests.go
50 lines (36 loc) · 943 Bytes
/
requests.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
package plausible
import (
"encoding/json"
"fmt"
"github.com/valyala/fasthttp"
)
type apiError struct {
Error string `json:"error"`
}
func checkAPIResponseForErrors(resp *fasthttp.Response) ([]byte, error) {
body := resp.Body()
status := resp.StatusCode()
if status < 200 || status > 203 {
var errorJSON apiError
err := json.Unmarshal(body, &errorJSON)
if err != nil {
return body, fmt.Errorf("non-ok code received (%d) from the API", status)
}
return body, fmt.Errorf("api error with code %d: %s", status, errorJSON.Error)
}
return body, nil
}
func doRequest(client *fasthttp.Client, req *fasthttp.Request) ([]byte, error) {
resp := fasthttp.AcquireResponse()
defer fasthttp.ReleaseRequest(req)
defer fasthttp.ReleaseResponse(resp)
err := client.Do(req, resp)
if err != nil {
return nil, err
}
body, err := checkAPIResponseForErrors(resp)
if err != nil {
return nil, err
}
return body, nil
}