request.go 3.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138
  1. package myth
  2. import (
  3. "compress/gzip"
  4. "crypto/tls"
  5. "crypto/x509"
  6. "io"
  7. "io/ioutil"
  8. "net"
  9. "net/http"
  10. "time"
  11. )
  12. const (
  13. // ReqContentTypeURL application/x-www-form-urlencoded
  14. ReqContentTypeURL = `application/x-www-form-urlencoded; charset=utf-8`
  15. // ReqContentTypeJSON application/json
  16. ReqContentTypeJSON = `application/json; charset=utf-8`
  17. // ReqContentTypeXML application/xml
  18. ReqContentTypeXML = `application/xml; charset=utf-8`
  19. // ReqContentTypeMultipart multipart/form-data
  20. ReqContentTypeMultipart = `multipart/form-data`
  21. // RequestTimeOut http request timeout (second)
  22. RequestTimeOut = 30
  23. )
  24. var (
  25. reqTimeOut = time.Duration(RequestTimeOut)
  26. )
  27. // GetRealIP get real IP from Request
  28. func GetRealIP(req *http.Request) (ip string) {
  29. if ips := req.Header["X-Real-Ip"]; ips != nil {
  30. ip = ips[0]
  31. }
  32. return
  33. }
  34. // HTTPMessage HTTP response
  35. type HTTPMessage struct {
  36. StatusCode int
  37. Body []byte
  38. Header http.Header
  39. }
  40. func newRequest(method, uri, certPath, keyPath string, header map[string]string, body io.Reader) (res *http.Response, err error) {
  41. t := &http.Transport{
  42. Dial: func(netw, addr string) (net.Conn, error) {
  43. conn, err := net.DialTimeout(netw, addr, time.Second*RequestTimeOut)
  44. if err != nil {
  45. return nil, err
  46. }
  47. conn.SetDeadline(time.Now().Add(time.Second * reqTimeOut))
  48. return conn, nil
  49. },
  50. ResponseHeaderTimeout: time.Second * reqTimeOut,
  51. }
  52. if certPath != "" {
  53. cert, e := tls.LoadX509KeyPair(certPath, keyPath)
  54. if e != nil {
  55. t.TLSClientConfig = &tls.Config{InsecureSkipVerify: true}
  56. } else {
  57. pool := x509.NewCertPool()
  58. t.TLSClientConfig = &tls.Config{InsecureSkipVerify: true, Certificates: []tls.Certificate{cert}, RootCAs: pool}
  59. }
  60. }
  61. client := &http.Client{Transport: t}
  62. var (
  63. req *http.Request
  64. )
  65. if body != nil {
  66. req, err = http.NewRequest(method, uri, body)
  67. } else {
  68. req, err = http.NewRequest(method, uri, nil)
  69. }
  70. if err != nil {
  71. return
  72. }
  73. for k := range header {
  74. req.Header.Add(k, header[k])
  75. }
  76. res, err = client.Do(req)
  77. return
  78. }
  79. func readBody(res *http.Response) (msg HTTPMessage, err error) {
  80. var (
  81. body []byte
  82. reader io.Reader
  83. )
  84. encoding := res.Header.Get("Content-Encoding")
  85. switch encoding {
  86. case "gzip":
  87. reader, err = gzip.NewReader(res.Body)
  88. if err == nil {
  89. body, err = ioutil.ReadAll(reader)
  90. }
  91. default:
  92. body, err = ioutil.ReadAll(res.Body)
  93. }
  94. if err != nil {
  95. return
  96. }
  97. msg.StatusCode = res.StatusCode
  98. msg.Header = res.Header
  99. msg.Body = body
  100. return
  101. }
  102. // Post HTTP request POST
  103. func Post(uri, certPath, keyPath string, header map[string]string, data io.Reader) (msg HTTPMessage, err error) {
  104. var res *http.Response
  105. if res, err = newRequest("POST", uri, certPath, keyPath, header, data); err != nil {
  106. return
  107. }
  108. defer res.Body.Close()
  109. msg, err = readBody(res)
  110. return
  111. }
  112. // Get HTTP request GET
  113. func Get(uri, certPath, keyPath string, header map[string]string) (msg HTTPMessage, err error) {
  114. var res *http.Response
  115. if res, err = newRequest("GET", uri, certPath, keyPath, header, nil); err != nil {
  116. return
  117. }
  118. defer res.Body.Close()
  119. msg, err = readBody(res)
  120. return
  121. }