-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathdev.go
102 lines (78 loc) · 1.56 KB
/
dev.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
100
101
102
package dev
import (
"bytes"
"context"
"encoding/json"
"errors"
"io"
"net/http"
"net/url"
"os"
"github.com/joho/godotenv"
)
const (
BASE_URL = "https://dev.to/api"
)
type Client struct {
Client *http.Client
BaseUrl *url.URL
Token string
}
func NewClient(token string) (*Client, error) {
u, err := url.Parse(BASE_URL)
if err != nil {
return nil, err
}
if token == "" {
return nil, errors.New("invalid token")
}
c := &Client{
Client: http.DefaultClient,
BaseUrl: u,
Token: token,
}
return c, nil
}
func NewTestClient() (*Client, error) {
if err := godotenv.Load(); err != nil {
return nil, err
}
token := os.Getenv("DEV_API_KEY")
return NewClient(token)
}
func (c *Client) NewRequest(ctx context.Context, method, path string, payload interface{}) (*http.Request, error) {
var buf io.Reader
url := c.BaseUrl.String() + path
if payload != nil {
b, err := json.Marshal(&payload)
if err != nil {
return nil, err
}
buf = bytes.NewBuffer(b)
}
return http.NewRequestWithContext(ctx, method, url, buf)
}
func (c *Client) SendHttpRequest(r *http.Request, v interface{}) error {
r.Header.Set("Content-Type", "application/json")
r.Header.Set("api-key", c.Token)
resp, err := c.Client.Do(r)
if err != nil {
return err
}
defer resp.Body.Close()
if resp.StatusCode < 200 || resp.StatusCode > 299 {
err := extractDevError(resp)
return err
}
if v == nil {
return nil
}
b, err := io.ReadAll(resp.Body)
if err != nil {
return err
}
if err := json.Unmarshal(b, v); err != nil {
return err
}
return nil
}