netutil.go 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. package util
  2. import (
  3. "bytes"
  4. "io"
  5. "log"
  6. "net"
  7. "net/http"
  8. "net/url"
  9. "strings"
  10. "time"
  11. )
  12. const (
  13. ContentTypeJson = "application/json;charset=utf-8"
  14. ContentTypeForm = "application/x-www-form-urlencoded;charset=utf-8"
  15. )
  16. const (
  17. MaxIdleCons int = 100
  18. MaxIdleConsPerHost int = 100
  19. IdleConnTimeout int = 2048
  20. ConnectTimeOut int = 30
  21. KeepAlive int = 30
  22. )
  23. var (
  24. httpClient *http.Client
  25. )
  26. func init() {
  27. httpClient = createHttpClient()
  28. }
  29. func createHttpClient() *http.Client {
  30. client := &http.Client{
  31. Transport: &http.Transport{
  32. Proxy: http.ProxyFromEnvironment,
  33. DialContext: (&net.Dialer{
  34. Timeout: time.Duration(ConnectTimeOut) * time.Second, //TCP连接超时30s
  35. KeepAlive: time.Duration(KeepAlive) * time.Second, //TCP keepalive保活检测定时30s
  36. }).DialContext,
  37. MaxIdleConns: MaxIdleCons,
  38. MaxIdleConnsPerHost: MaxIdleConsPerHost,
  39. IdleConnTimeout: time.Duration(IdleConnTimeout) * time.Second, //闲置连接超时2048s
  40. ResponseHeaderTimeout: time.Second * 60,
  41. },
  42. }
  43. return client
  44. }
  45. func HttpPostJson(url string, json string) ([]byte, error) {
  46. return HttpPost(url, map[string]string{"Content-Type": ContentTypeJson}, bytes.NewReader([]byte(json)))
  47. }
  48. func HttpPostForm(url string, header map[string]string, formValues url.Values) ([]byte, error) {
  49. header["Content-Type"] = ContentTypeForm
  50. return HttpPost(url, header, strings.NewReader(formValues.Encode()))
  51. }
  52. func HttpPost(url string, header map[string]string, body io.Reader) ([]byte, error) {
  53. request, err := http.NewRequest("POST", url, body)
  54. if err != nil {
  55. return nil, err
  56. }
  57. for k, v := range header {
  58. request.Header.Add(k, v)
  59. }
  60. response, err := httpClient.Do(request) //前面预处理一些参数,状态,Do执行发送;处理返回结果;Do:发送请求,
  61. if err != nil {
  62. return nil, err
  63. }
  64. defer response.Body.Close()
  65. replay, err := io.ReadAll(response.Body)
  66. if err != nil {
  67. log.Println("read reply error:", err)
  68. return nil, err
  69. }
  70. return replay, nil
  71. }
  72. func RedingJsonDataFromRequestBody(request *http.Request) string {
  73. bs, err := io.ReadAll(request.Body)
  74. if err != nil {
  75. panic(err)
  76. }
  77. data := string(bs)
  78. log.Println("data:", data)
  79. return data
  80. }