netutil.go 2.2 KB

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