request.go 3.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171
  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. // HTTPMessage HTTP response
  38. type HTTPMessage struct {
  39. StatusCode int
  40. Body []byte
  41. Header http.Header
  42. }
  43. // JSON Body to JSON
  44. func (m HTTPMessage) JSON(dest interface{}) (err error) {
  45. if m.StatusCode != http.StatusOK {
  46. err = errors.New(`StatusCode not 200`)
  47. return
  48. }
  49. err = json.Unmarshal(m.Body, &dest)
  50. return
  51. }
  52. // XML Body to XML
  53. func (m HTTPMessage) XML(dest interface{}) (err error) {
  54. if m.StatusCode != http.StatusOK {
  55. err = errors.New(`StatusCode not 200`)
  56. return
  57. }
  58. err = xml.Unmarshal(m.Body, &dest)
  59. return
  60. }
  61. // JSONQuery Body to JSONQuery
  62. func (m HTTPMessage) JSONQuery() (jq *JSONQuery, err error) {
  63. if m.StatusCode != http.StatusOK {
  64. err = errors.New(`StatusCode not 200`)
  65. return
  66. }
  67. jq, err = NewJSONQuery(m.Body)
  68. return
  69. }
  70. func newRequest(method, uri, certPath, keyPath string, header map[string]string, body io.Reader) (res *http.Response, err error) {
  71. t := &http.Transport{
  72. Dial: func(netw, addr string) (net.Conn, error) {
  73. conn, err := net.DialTimeout(netw, addr, time.Second*RequestTimeOut)
  74. if err != nil {
  75. return nil, err
  76. }
  77. conn.SetDeadline(time.Now().Add(time.Second * reqTimeOut))
  78. return conn, nil
  79. },
  80. ResponseHeaderTimeout: time.Second * reqTimeOut,
  81. }
  82. if certPath != "" {
  83. cert, e := tls.LoadX509KeyPair(certPath, keyPath)
  84. if e != nil {
  85. t.TLSClientConfig = &tls.Config{InsecureSkipVerify: true}
  86. } else {
  87. pool := x509.NewCertPool()
  88. t.TLSClientConfig = &tls.Config{InsecureSkipVerify: true, Certificates: []tls.Certificate{cert}, RootCAs: pool}
  89. }
  90. }
  91. client := &http.Client{Transport: t}
  92. var (
  93. req *http.Request
  94. )
  95. if body != nil {
  96. req, err = http.NewRequest(method, uri, body)
  97. } else {
  98. req, err = http.NewRequest(method, uri, nil)
  99. }
  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 = ioutil.ReadAll(reader)
  120. }
  121. default:
  122. body, err = ioutil.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. }