-
Notifications
You must be signed in to change notification settings - Fork 3
/
post.go
executable file
·54 lines (45 loc) · 1.29 KB
/
post.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
package httpClientKit
import (
"github.com/richelieu-yang/chimera/v2/src/urlKit"
"github.com/richelieu-yang/chimera/v2/src/web/httpKit"
"io"
"net/http"
"strings"
)
func Post(url string, options ...Option) (int, []byte, error) {
resp, err := PostForResponse(url, options...)
if err != nil {
return 0, nil, err
}
defer resp.Body.Close()
data, err := io.ReadAll(resp.Body)
if err != nil {
return 0, nil, err
}
return resp.StatusCode, data, nil
}
// PostForResponse
/*
@return !!!: 第一个返回值如果不为nil的话,一般来说需要手动调用 "resp.Body.Close()"
*/
func PostForResponse(url string, options ...Option) (*http.Response, error) {
opts := loadOptions(options...)
// url
if err := httpKit.AssertHttpUrl(url); err != nil {
return nil, err
}
url = urlKit.AttachQueryParamsToUrl(url, opts.queryParams)
// payload
payload := strings.NewReader(urlKit.ToBodyString(opts.postParams))
// req
req, err := http.NewRequest("POST", url, payload)
if err != nil {
return nil, err
}
//req.Header.Set("Content-Type", "application/x-www-form-urlencoded; charset=utf-8")
req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
req.Header.Add("Content-Type", "charset=utf-8")
// client
client := newHttpClient(opts.timeout, opts.safe)
return client.Do(req)
}