request.go 3.9 KB

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