-
Notifications
You must be signed in to change notification settings - Fork 3
/
methodPost.go
executable file
·59 lines (50 loc) · 1.43 KB
/
methodPost.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
package httpClientKit
import (
httpKit2 "github.com/richelieu-yang/chimera/v2/src/component/web/httpKit"
"github.com/richelieu-yang/chimera/v2/src/urlKit"
"io"
"net/http"
"strings"
)
// Post Deprecated: Use reqKit instead.
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 Deprecated: Use reqKit instead.
/*
!!!: 第2个返回值 == nil 的情况下,需要手动调用 resp.Body.Close() 来手动关闭 第1个返回值.
*/
func PostForResponse(url string, options ...Option) (*http.Response, error) {
opts := loadOptions(options...)
// url
if err := httpKit2.AssertHttpUrl(url); err != nil {
return nil, err
}
url, err := urlKit.PolyfillUrl(url, opts.queryParams)
if err != nil {
return nil, err
}
// payload
content := httpKit2.ToRequestBodyString(opts.postParams)
payload := strings.NewReader(content)
// 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 := opts.newHttpClient()
return client.Do(req)
}