request.go 3.8 KB

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