-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapi.go
69 lines (54 loc) · 1.34 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
package pawntown_chess_results_module
import (
"fmt"
"io"
"net/http"
"net/url"
"strings"
)
type ChessResultsApiOptions struct {
BaseUrl string
}
type Api struct {
client *http.Client
baseUrl string
}
func New(options ChessResultsApiOptions) *Api {
return &Api{
client: &http.Client{},
baseUrl: options.BaseUrl,
}
}
func (api *Api) get(path string) (string, error) {
return api.req("GET", path, nil)
}
func (api *Api) post(path string, values url.Values) (string, error) {
return api.req("POST", path, values)
}
func (api *Api) req(method string, path string, values url.Values) (string, error) {
url := fmt.Sprintf("%s/%s", api.baseUrl, path)
var body io.Reader = nil
if values != nil {
body = strings.NewReader(values.Encode())
}
req, err := http.NewRequest(method, url, body)
if err != nil {
return "", err
}
req.Header.Set("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36")
if values != nil {
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
}
res, err := api.client.Do(req)
if err != nil {
return "", err
}
resBody, err := io.ReadAll(res.Body)
if err != nil {
return "", err
}
return string(resBody), nil
}
func (api *Api) Tournament(id string) (*Tournament, error) {
return newTournament(api, id)
}