-
Notifications
You must be signed in to change notification settings - Fork 20
/
api.go
189 lines (165 loc) · 3.89 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
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
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
package biligo
import (
"bytes"
"encoding/json"
"fmt"
"io"
"io/ioutil"
"log"
"math/rand"
"mime/multipart"
"net/http"
"net/url"
"os"
"strings"
"time"
)
type baseClient struct {
debug bool
client *http.Client
ua string
logger *log.Logger
}
type baseSetting struct {
// 自定义http client
//
// 默认为 http.http.DefaultClient
Client *http.Client
// Debug模式 true将输出请求信息 false不输出
//
// 默认false
DebugMode bool
// 自定义UserAgent
//
// 默认Chrome随机Agent
UserAgent string
// Logger 的输出前缀,区分Client
Prefix string
}
func newBaseClient(setting *baseSetting) *baseClient {
client := setting.Client
if client == nil {
client = http.DefaultClient
}
ua := setting.UserAgent
if ua == "" {
rand.Seed(time.Now().UnixNano())
ua = userAgent[rand.Intn(len(userAgent))]
}
return &baseClient{
debug: setting.DebugMode,
client: client,
ua: ua,
logger: log.New(os.Stdout, setting.Prefix, log.LstdFlags),
}
}
// request v为携带的参数,用于debug输出
func (h *baseClient) request(req *http.Request, v interface{}) ([]byte, error) {
resp, err := h.client.Do(req)
if err != nil {
return nil, err
}
resp.Close = true
defer resp.Body.Close()
raw, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, err
}
if h.debug {
h.logger.Printf("%s %s %+v", req.Method, req.URL, v)
h.logger.Printf("%s", string(raw))
}
return raw, nil
}
func (h *baseClient) raw(base, endpoint, method string, payload map[string]string, dAfter func(d *url.Values), reqAfter func(r *http.Request)) ([]byte, error) {
var (
req *http.Request
err error
)
data := url.Values{}
for k, v := range payload {
data.Add(k, v)
}
// 侵入处理values
if dAfter != nil {
dAfter(&data)
}
link := base + endpoint
switch method {
case http.MethodGet:
if req, err = http.NewRequest(method, link, nil); err != nil {
return nil, err
}
req.URL.RawQuery = data.Encode()
case http.MethodPost:
if req, err = http.NewRequest(method, link, strings.NewReader(data.Encode())); err != nil {
return nil, err
}
}
req.Header.Add("Origin", "https://www.bilibili.com")
req.Header.Add("Referer", "https://www.bilibili.com")
req.Header.Add("Content-type", "application/x-www-form-urlencoded")
req.Header.Add("User-Agent", h.ua)
// 侵入处理req
if reqAfter != nil {
reqAfter(req)
}
return h.request(req, payload)
}
func (h *baseClient) parse(raw []byte) (*Response, error) {
var result = &Response{}
if err := json.Unmarshal(raw, &result); err != nil {
return nil, err
}
if result.Code != 0 {
return nil, fmt.Errorf("(%d) %s", result.Code, result.Message)
}
return result, nil
}
func (h *baseClient) upload(base, endpoint string, payload map[string]string, files []*FileUpload, mAfter func(m *multipart.Writer) error, reqAfter func(r *http.Request)) ([]byte, error) {
var (
req *http.Request
err error
)
link := base + endpoint
body := new(bytes.Buffer)
mp := multipart.NewWriter(body)
for _, f := range files {
var ff io.Writer
if ff, err = mp.CreateFormFile(f.Field, f.Name); err != nil {
return nil, err
}
if _, err = io.Copy(ff, f.File); err != nil {
return nil, err
}
}
for k, v := range payload {
if err = mp.WriteField(k, v); err != nil {
return nil, err
}
}
// 侵入处理field
if mAfter != nil {
if err = mAfter(mp); err != nil {
return nil, err
}
}
// 为mp添加结束符
if err = mp.Close(); err != nil {
return nil, err
}
// 只支持POST
if req, err = http.NewRequest(http.MethodPost, link, body); err != nil {
return nil, err
}
req.Header.Add("Origin", "https://www.bilibili.com")
req.Header.Add("Referer", "https://www.bilibili.com")
req.Header.Add("Content-type", mp.FormDataContentType())
req.Header.Add("User-Agent", h.ua)
// 侵入处理req
if reqAfter != nil {
reqAfter(req)
}
// 文件不输出,否则全是乱码
return h.request(req, payload)
}