builder.go 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. package rdhttp
  2. import (
  3. "cockData/server/log"
  4. "encoding/json"
  5. "github.com/valyala/fasthttp"
  6. "net/http"
  7. )
  8. type HttpUrlBuilder interface {
  9. GetParamsMap() (paramsMap map[string]string)
  10. GetApiUrl() string
  11. GetHeaders() (headers map[string]string)
  12. }
  13. func UpdateProxyAndGet(builder HttpUrlBuilder, jsonResp interface{}) (err error, body string) {
  14. proxy := GetProxy()
  15. if proxy.OutOfTime() { // 代理无效,进行更新
  16. err = proxy.Update()
  17. if err != nil {
  18. return
  19. }
  20. }
  21. err, body = SendHttpGet(builder, &jsonResp)
  22. return
  23. }
  24. func SendHttpGet(builder HttpUrlBuilder, jsonResp interface{}) (err error, body string) {
  25. finalUrl := GetQueryUrl(builder.GetApiUrl(), builder.GetParamsMap())
  26. resp, err := SendGetRequest(finalUrl, builder.GetHeaders())
  27. if err != nil {
  28. log.Warn("请求失败")
  29. return
  30. }
  31. defer func() {
  32. fasthttp.ReleaseResponse(resp)
  33. }()
  34. body = string(resp.Body())
  35. if resp.StatusCode() != http.StatusOK {
  36. log.Warnf("Http应答错误 %d", resp.StatusCode())
  37. return
  38. }
  39. err = json.Unmarshal(resp.Body(), &jsonResp)
  40. if err != nil {
  41. log.Warnf("Json 解析错误,应答包体 %s", string(resp.Body()))
  42. }
  43. return
  44. }
  45. func SendHttpPost(builder HttpUrlBuilder, params interface{}, jsonResp interface{}) (err error, body string) {
  46. finalUrl := GetQueryUrl(builder.GetApiUrl(), builder.GetParamsMap())
  47. reqBody, err := json.Marshal(params)
  48. if err != nil {
  49. log.Warn("Json处理失败")
  50. return
  51. }
  52. resp, err := SendPostRequest(finalUrl, builder.GetHeaders(), reqBody)
  53. defer func() {
  54. fasthttp.ReleaseResponse(resp)
  55. }()
  56. body = string(resp.Body())
  57. if resp.StatusCode() != http.StatusOK {
  58. log.Warnf("Http应答错误 %d", resp.StatusCode())
  59. return
  60. }
  61. err = json.Unmarshal(resp.Body(), &jsonResp)
  62. if err != nil {
  63. log.Warnf("Json 解析错误,应答包体 %s", string(resp.Body()))
  64. } else {
  65. log.Infof("服务器应答包体 %s", string(resp.Body()))
  66. }
  67. return
  68. }