49 lines
1.0 KiB
Go
49 lines
1.0 KiB
Go
package grequests
|
|
|
|
import (
|
|
"bytes"
|
|
"encoding/json"
|
|
"io"
|
|
"net/http"
|
|
"net/url"
|
|
"strings"
|
|
)
|
|
|
|
// Option 定义请求选项
|
|
type Option func(*http.Request)
|
|
|
|
// WithParams 设置 URL 查询参数
|
|
func WithParams(params map[string]string) Option {
|
|
return func(req *http.Request) {
|
|
q := req.URL.Query()
|
|
for k, v := range params {
|
|
q.Add(k, v)
|
|
}
|
|
req.URL.RawQuery = q.Encode()
|
|
}
|
|
}
|
|
|
|
// WithData 设置表单数据
|
|
func WithData(data map[string]string) Option {
|
|
return func(req *http.Request) {
|
|
form := url.Values{}
|
|
for k, v := range data {
|
|
form.Add(k, v)
|
|
}
|
|
req.Body = io.NopCloser(strings.NewReader(form.Encode()))
|
|
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
|
|
}
|
|
}
|
|
|
|
// WithJSON 设置 JSON 数据
|
|
func WithJSON(jsonData interface{}) Option {
|
|
return func(req *http.Request) {
|
|
jsonBytes, err := json.Marshal(jsonData)
|
|
if err != nil {
|
|
return // 在实际应用中应处理错误
|
|
}
|
|
req.Body = io.NopCloser(bytes.NewReader(jsonBytes))
|
|
req.Header.Set("Content-Type", "application/json")
|
|
}
|
|
}
|