/
client.go
92 lines (84 loc) · 2.09 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
package fhj
import (
"encoding/json"
"errors"
"net/http"
"strings"
"github.com/levigross/grequests"
)
type Client struct {
endPoint string
apiKey string
}
func New(endPoint, apiKey string) *Client {
return &Client{
endPoint: strings.TrimRight(endPoint, "/"),
apiKey: apiKey,
}
}
func (c Client) ServiceInfo() (*RawResp, *StatusData, error) {
respJSON, err := c.req(http.MethodGet, "/service-info", nil)
if err != nil {
return respJSON, nil, err
}
status := &StatusData{}
if err := json.Unmarshal(respJSON.Data, status); err != nil {
return respJSON, nil, err
}
return respJSON, status, nil
}
const (
ConverterSimplified = "Simplified"
ConverterTraditional = "Traditional"
ConverterChina = "China"
ConverterHongkong = "Hongkong"
ConverterTaiwan = "Taiwan"
ConverterPinyin = "Pinyin"
ConverterMars = "Mars"
ConverterWikiSimplified = "WikiSimplified"
ConverterWikiTraditional = "WikiTraditional"
)
func (c Client) Convert(converter, text string, extraOptions map[string]string) (*RawResp, *ConvertData, error) {
data := map[string]string{
"text": text,
"converter": converter,
}
for k, v := range extraOptions {
data[k] = v
}
respJSON, err := c.req(http.MethodPost, "/convert", &grequests.RequestOptions{
Data: data,
})
if err != nil {
return respJSON, nil, err
}
respData := &ConvertData{}
if err := json.Unmarshal(respJSON.Data, respData); err != nil {
return respJSON, nil, err
}
return respJSON, respData, nil
}
func (c Client) req(verb, url string, opt *grequests.RequestOptions) (*RawResp, error) {
if opt == nil {
opt = &grequests.RequestOptions{}
}
if opt.Params == nil {
opt.Params = make(map[string]string)
}
opt.Params["apiKey"] = c.apiKey
resp, err := grequests.Req(verb, c.endPoint+url, opt)
if err != nil {
return nil, err
}
if !resp.Ok {
return nil, errors.New(http.StatusText(resp.StatusCode))
}
respJSON := &RawResp{}
if err := resp.JSON(respJSON); err != nil {
return nil, err
}
if respJSON.Code != 0 {
return respJSON, errors.New(respJSON.Msg)
}
return respJSON, nil
}