代码拉取完成,页面将自动刷新
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
}
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。