1 Star 0 Fork 0

曾广宇/mxx-core-v2

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
http_request_util.go 2.05 KB
一键复制 编辑 原始数据 按行查看 历史
曾广宇 提交于 2023-04-03 05:32 . 修正mod名称
package mutil
import (
"bytes"
"gitee.com/dennis-mxx/mxx-core-v2/mlogger"
"io"
"net/http"
"strings"
)
const JsonHeader = "application/json;charset=utf-8"
const FormHeader = "application/x-www-form-urlencoded;charset=utf-8"
const GET = "GET"
const POST = "POST"
const EmptyJson = "{}"
type HttpRequest struct {
Url string
Data map[string]any
Body string
UrlData map[string]string
Method string
Header map[string]string
}
type Response struct {
}
func (domain *HttpRequest) PostForm() (*http.Response, *bytes.Buffer, error) {
domain.SetHeader(HeaderNames.ContentType, FormHeader)
if domain.Data != nil {
domain.Body = Strings.EncodeForm(domain.Data)
}
return domain.doExec()
}
func (domain *HttpRequest) PostJson() (*http.Response, *bytes.Buffer, error) {
domain.SetHeader(HeaderNames.ContentType, JsonHeader)
if domain.Data != nil {
if str, err := JSONTOString(domain.Data); err != nil {
return nil, nil, err
} else {
domain.Body = str
}
} else if domain.Body == "" {
domain.Body = EmptyJson
}
return domain.doExec()
}
func (domain *HttpRequest) GetUrl() (*http.Response, *bytes.Buffer, error) {
domain.SetHeader(HeaderNames.ContentType, FormHeader)
return domain.doExec()
}
func (domain *HttpRequest) doExec() (*http.Response, *bytes.Buffer, error) {
defer mlogger.FormatException()
var reader io.Reader
if strings.EqualFold(POST, domain.Method) {
reader = strings.NewReader(domain.Body)
}
if domain.UrlData != nil {
domain.Url = Strings.FormUrl(domain.Url, domain.UrlData)
}
request, err := http.NewRequest(domain.Method, domain.Url, reader)
if err != nil {
return nil, nil, err
}
for key, value := range domain.Header {
request.Header.Add(key, value)
}
response, err := http.DefaultClient.Do(request)
if err == nil {
buffer, err := ReadBuffer(response.Body)
return response, buffer, err
}
return response, nil, err
}
func (domain *HttpRequest) SetHeader(headerName string, headerValue string) {
if domain.Header == nil {
domain.Header = map[string]string{}
}
domain.Header[headerName] = headerValue
}
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/dennis-mxx/mxx-core-v2.git
git@gitee.com:dennis-mxx/mxx-core-v2.git
dennis-mxx
mxx-core-v2
mxx-core-v2
v0.2.3

搜索帮助

0d507c66 1850385 C8b1a773 1850385