-
Notifications
You must be signed in to change notification settings - Fork 0
/
yourls.go
70 lines (58 loc) · 1.39 KB
/
yourls.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
// Copyright: (c) 2022, Justin Béra (@just1not2) <me@just1not2.org>
// GNU General Public License v3.0+ (see LICENSE or https://www.gnu.org/licenses/gpl-3.0.txt)
package main
import (
"encoding/json"
"fmt"
"io"
"net/http"
"time"
)
type YourlsClient struct {
client *http.Client
url string
signature string
}
type StatBody struct {
Stats map[string]string `json:"stats"`
Message string `json:"message"`
Code float64 `json:"statusCode"`
}
func NewYourlsClient(url string, signature string, timeout time.Duration) *YourlsClient {
return &YourlsClient{
client: &http.Client{Timeout: timeout},
url: url,
signature: signature,
}
}
func (client *YourlsClient) Request(parameters map[string]string) (*StatBody, error) {
for parameter, value := range parameters {
client.url += fmt.Sprintf("&%s=%s", parameter, value)
}
req, err := http.NewRequest("GET", client.url, nil)
if err != nil {
return nil, err
}
// Sends the HTTP request
res, err := client.client.Do(req)
if err != nil {
return nil, err
}
defer res.Body.Close()
var body StatBody
// Sets the body into a JSON
decoder := json.NewDecoder(res.Body)
for {
err := decoder.Decode(&body)
if err == io.EOF {
break
}
if err != nil {
return nil, err
}
}
if body.Code != 200 {
return nil, fmt.Errorf("error %v: %s", body.Code, body.Message)
}
return &body, nil
}