-
Notifications
You must be signed in to change notification settings - Fork 5
/
utils.go
51 lines (46 loc) · 1.12 KB
/
utils.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
package fy
import (
"context"
"fmt"
"io"
"io/ioutil"
"net/http"
"unicode"
)
// IsChinese determines whether the param is Chinese.
func IsChinese(str string) bool {
for _, r := range str {
if unicode.Is(unicode.Scripts["Han"], r) {
return true
}
}
return false
}
func sendRequest(ctx context.Context, method, urlStr string, body io.Reader, f func(*http.Request) error) (*http.Response, []byte, error) {
req, err := http.NewRequest(method, urlStr, body)
if err != nil {
return nil, nil, fmt.Errorf("http.NewRequest error: %v", err)
}
req = req.WithContext(ctx)
if f != nil {
if err := f(req); err != nil {
return nil, nil, fmt.Errorf("f error: %v", err)
}
}
resp, err := http.DefaultClient.Do(req)
if err != nil {
return nil, nil, fmt.Errorf("http request error: %v", err)
}
defer resp.Body.Close()
respBody, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, nil, fmt.Errorf("ioutil.ReadAll error: %v", err)
}
return resp, respBody, nil
}
func addCookies(req *http.Request, cookies []*http.Cookie) *http.Request {
for _, cookie := range cookies {
req.AddCookie(cookie)
}
return req
}