This repository has been archived by the owner on Oct 28, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathwigole.go
56 lines (53 loc) · 1.44 KB
/
wigole.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
// Package wigole is the wrapper for the WiGLE API.
package wigole
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"io/ioutil"
)
var (
// ErrAuth indicates the API call failed because of an HTTP authentication failure.
ErrAuth = errors.New("basic auth failure")
// ErrFail indicates the API call failed.
ErrFail = errors.New("failed API call")
// ErrTooMany indicates the API call failed because rate limiting.
ErrTooMany = fmt.Errorf("%w\nmessage: too many queries today", ErrFail)
basicAuthFailure = []byte("Basic auth failure")
)
// Do wraps building the URL, building the request body, doing the request, and parsing and unmarshaling the response.
func Do(apiPath string, b Builder, method string, response interface{}, user *User) error {
values, err := b.Url()
if err != nil {
return err
}
pBody, err := b.Body()
if err != nil {
return err
}
resp, err := user.Do(apiPath, pBody, method, values)
if err != nil {
return err
}
rBody, err := ioutil.ReadAll(resp.Body)
if err != nil {
return err
}
failResp := &failResp{}
if err = json.Unmarshal(rBody, failResp); err == nil {
if !failResp.Success && len(failResp.Message) != 0 {
if failResp.Message == ErrTooMany.Error() {
return ErrTooMany
}
return fmt.Errorf("%w\nmessage: %s", ErrFail, failResp.Message)
}
}
if err = json.Unmarshal(rBody, response); err != nil {
if bytes.Equal(rBody, basicAuthFailure) {
return ErrAuth
}
return err
}
return nil
}