-
Notifications
You must be signed in to change notification settings - Fork 21
/
Copy pathclient.go
95 lines (87 loc) · 1.93 KB
/
client.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
package kavenegar
import (
"encoding/json"
"fmt"
"net"
"net/http"
"net/url"
"strings"
)
const (
apiBaseURL = "https://api.kavenegar.com/"
apiVersion = "v1"
apiFormat = "json"
version = "0.1.0"
)
type Return struct {
Status int `json:"status"`
Message string `json:"message"`
}
type ReturnError struct {
*Return `json:"return"`
}
type Client struct {
BaseClient *http.Client
apikey string
BaseURL *url.URL
}
func NewClient(apikey string) *Client {
baseURL, _ := url.Parse(apiBaseURL)
c := &Client{
BaseClient: http.DefaultClient,
BaseURL: baseURL,
apikey: apikey,
}
return c
}
func (c *Client) EndPoint(parts ...string) *url.URL {
up := []string{apiVersion, c.apikey}
up = append(up, parts...)
u, _ := url.Parse(strings.Join(up, "/"))
u.Path = fmt.Sprintf("/%s.%s", u.Path, apiFormat)
return u
}
func (c *Client) Execute(urlStr string, b url.Values, v interface{}) error {
body := strings.NewReader(b.Encode())
ul, _ := url.Parse(urlStr)
u := c.BaseURL.ResolveReference(ul)
req, _ := http.NewRequest("POST", u.String(), body)
req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
req.Header.Add("Accept", "application/json")
req.Header.Add("Accept-Charset", "utf-8")
resp, err := c.BaseClient.Do(req)
if err != nil {
if err, ok := err.(net.Error); ok {
return err
}
if resp == nil {
return &HTTPError{
Status: http.StatusInternalServerError,
Message: "nil api response",
Err: err,
}
}
return &HTTPError{
Status: resp.StatusCode,
Message: resp.Status,
Err: err,
}
}
defer resp.Body.Close()
if 200 != resp.StatusCode {
re := new(ReturnError)
err = json.NewDecoder(resp.Body).Decode(&re)
if err != nil {
return &HTTPError{
Status: resp.StatusCode,
Message: resp.Status,
}
}
return &APIError{
Status: re.Return.Status,
Message: re.Return.Message,
}
}
_ = json.NewDecoder(resp.Body).Decode(&v)
return nil
}