12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273 |
- package rdhttp
- import (
- "cockData/server/log"
- "encoding/json"
- "github.com/valyala/fasthttp"
- "net/http"
- )
- type HttpUrlBuilder interface {
- GetParamsMap() (paramsMap map[string]string)
- GetApiUrl() string
- GetHeaders() (headers map[string]string)
- }
- func UpdateProxyAndGet(builder HttpUrlBuilder, jsonResp interface{}) (err error, body string) {
- proxy := GetProxy()
- if proxy.OutOfTime() { // 代理无效,进行更新
- err = proxy.Update()
- if err != nil {
- return
- }
- }
- err, body = SendHttpGet(builder, &jsonResp)
- return
- }
- func SendHttpGet(builder HttpUrlBuilder, jsonResp interface{}) (err error, body string) {
- finalUrl := GetQueryUrl(builder.GetApiUrl(), builder.GetParamsMap())
- resp, err := SendGetRequest(finalUrl, builder.GetHeaders())
- if err != nil {
- log.Warn("请求失败")
- return
- }
- defer func() {
- fasthttp.ReleaseResponse(resp)
- }()
- body = string(resp.Body())
- if resp.StatusCode() != http.StatusOK {
- log.Warnf("Http应答错误 %d", resp.StatusCode())
- return
- }
- err = json.Unmarshal(resp.Body(), &jsonResp)
- if err != nil {
- log.Warnf("Json 解析错误,应答包体 %s", string(resp.Body()))
- }
- return
- }
- func SendHttpPost(builder HttpUrlBuilder, params interface{}, jsonResp interface{}) (err error, body string) {
- finalUrl := GetQueryUrl(builder.GetApiUrl(), builder.GetParamsMap())
- reqBody, err := json.Marshal(params)
- if err != nil {
- log.Warn("Json处理失败")
- return
- }
- resp, err := SendPostRequest(finalUrl, builder.GetHeaders(), reqBody)
- defer func() {
- fasthttp.ReleaseResponse(resp)
- }()
- body = string(resp.Body())
- if resp.StatusCode() != http.StatusOK {
- log.Warnf("Http应答错误 %d", resp.StatusCode())
- return
- }
- err = json.Unmarshal(resp.Body(), &jsonResp)
- if err != nil {
- log.Warnf("Json 解析错误,应答包体 %s", string(resp.Body()))
- } else {
- log.Infof("服务器应答包体 %s", string(resp.Body()))
- }
- return
- }
|