request.go 3.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172
  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. ResponseHeaderTimeout: time.Second * reqTimeOut,
  85. }
  86. if certPath != "" {
  87. cert, e := tls.LoadX509KeyPair(certPath, keyPath)
  88. if e != nil {
  89. t.TLSClientConfig = &tls.Config{InsecureSkipVerify: true}
  90. } else {
  91. pool := x509.NewCertPool()
  92. t.TLSClientConfig = &tls.Config{InsecureSkipVerify: true, Certificates: []tls.Certificate{cert}, RootCAs: pool}
  93. }
  94. }
  95. var (
  96. req *http.Request
  97. client = &http.Client{Transport: t}
  98. )
  99. req, err = http.NewRequest(method, uri, body)
  100. if err != nil {
  101. return
  102. }
  103. for k := range header {
  104. req.Header.Add(k, header[k])
  105. }
  106. res, err = client.Do(req)
  107. return
  108. }
  109. func readBody(res *http.Response) (msg HTTPMessage, err error) {
  110. var (
  111. body []byte
  112. reader io.Reader
  113. )
  114. encoding := res.Header.Get("Content-Encoding")
  115. switch encoding {
  116. case "gzip":
  117. reader, err = gzip.NewReader(res.Body)
  118. if err == nil {
  119. body, err = io.ReadAll(reader)
  120. }
  121. default:
  122. body, err = io.ReadAll(res.Body)
  123. }
  124. if err != nil {
  125. return
  126. }
  127. msg.StatusCode = res.StatusCode
  128. msg.Header = res.Header
  129. msg.Body = body
  130. return
  131. }
  132. // Post HTTP request POST
  133. func Post(uri, certPath, keyPath string, header map[string]string, data io.Reader) (msg HTTPMessage, err error) {
  134. var res *http.Response
  135. if res, err = newRequest("POST", uri, certPath, keyPath, header, data); err != nil {
  136. return
  137. }
  138. defer res.Body.Close()
  139. msg, err = readBody(res)
  140. return
  141. }
  142. // Get HTTP request GET
  143. func Get(uri, certPath, keyPath string, header map[string]string) (msg HTTPMessage, err error) {
  144. var res *http.Response
  145. if res, err = newRequest("GET", uri, certPath, keyPath, header, nil); err != nil {
  146. return
  147. }
  148. defer res.Body.Close()
  149. msg, err = readBody(res)
  150. return
  151. }