You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

226 lines
5.3 KiB

2 years ago
  1. package util
  2. import (
  3. "bytes"
  4. "crypto/tls"
  5. "encoding/json"
  6. "fmt"
  7. "io"
  8. "io/ioutil"
  9. "net/http"
  10. "time"
  11. )
  12. type RequestMethod string
  13. type ContentType string
  14. type RequestHeader map[string][]string
  15. const (
  16. GET RequestMethod = "GET"
  17. POST RequestMethod = "POST"
  18. PUT RequestMethod = "PUT"
  19. DELETE RequestMethod = "DELETE"
  20. )
  21. const (
  22. ContentTypePlain ContentType = "text/plain;charset=utf-8"
  23. ContentTypeHtml ContentType = "text/html;charset=utf-8"
  24. ContentTypeXml ContentType = "text/xml;charset=utf-8"
  25. ContentTypeJson ContentType = "application/json;charset=utf-8"
  26. ContentTypeForm ContentType = "application/x-www-form-urlencoded;charset=utf-8"
  27. ContentTypeFile ContentType = "multipart/form-data;charset=utf-8"
  28. )
  29. func Get(url string) ([]byte, error) {
  30. return Request(url, GET, ContentTypePlain, nil, nil)
  31. }
  32. func Post(url string, contentType ContentType, v interface{}) ([]byte, error) {
  33. return Request(url, POST, contentType, nil, v)
  34. }
  35. func Put(url string, contentType ContentType, v interface{}) ([]byte, error) {
  36. return Request(url, PUT, contentType, nil, v)
  37. }
  38. func Del(url string) ([]byte, error) {
  39. return Request(url, DELETE, ContentTypePlain, nil, nil)
  40. }
  41. func GetByHeader(url string, header RequestHeader) ([]byte, error) {
  42. return Request(url, GET, ContentTypePlain, header, nil)
  43. }
  44. func PostByHeader(url string, contentType ContentType, header RequestHeader, v interface{}) ([]byte, error) {
  45. return Request(url, POST, contentType, header, v)
  46. }
  47. func PutByHeader(url string, contentType ContentType, header RequestHeader, v interface{}) ([]byte, error) {
  48. return Request(url, PUT, contentType, header, v)
  49. }
  50. func DelByHeader(url string, header RequestHeader) ([]byte, error) {
  51. return Request(url, DELETE, ContentTypePlain, header, nil)
  52. }
  53. func GetJson(url string, v interface{}) ([]byte, error) {
  54. return Request(url, GET, ContentTypeJson, nil, v)
  55. }
  56. func PostJson(url string, v interface{}) ([]byte, error) {
  57. return Request(url, POST, ContentTypeJson, nil, v)
  58. }
  59. func PutJson(url string, v interface{}) ([]byte, error) {
  60. return Request(url, PUT, ContentTypeJson, nil, v)
  61. }
  62. func DelJson(url string, v interface{}) ([]byte, error) {
  63. return Request(url, DELETE, ContentTypeJson, nil, v)
  64. }
  65. func PostJsonByHeader(url string, header RequestHeader, v interface{}) ([]byte, error) {
  66. return Request(url, POST, ContentTypeJson, header, v)
  67. }
  68. func PutJsonByHeader(url string, header RequestHeader, v interface{}) ([]byte, error) {
  69. return Request(url, PUT, ContentTypeJson, header, v)
  70. }
  71. func Request(url string, method RequestMethod, contentType ContentType, header RequestHeader, v interface{}) ([]byte, error) {
  72. var body io.Reader
  73. var err error
  74. //PrintInfo("response URL:")
  75. //PrintInfo(url)
  76. switch contentType {
  77. case ContentTypePlain:
  78. //return nil, fmt.Errorf("unsupported content-type:%s", contentType)
  79. case ContentTypeHtml:
  80. return nil, fmt.Errorf("unsupported content-type:%s", contentType)
  81. case ContentTypeXml:
  82. return nil, fmt.Errorf("unsupported content-type:%s", contentType)
  83. case ContentTypeForm:
  84. return nil, fmt.Errorf("unsupported content-type:%s", contentType)
  85. case ContentTypeJson:
  86. body, err = toJson(v)
  87. case ContentTypeFile:
  88. return nil, fmt.Errorf("unsupported content-type:%s", contentType)
  89. default:
  90. return nil, fmt.Errorf("invalid content-type:%s", contentType)
  91. }
  92. if err != nil {
  93. return nil, err
  94. }
  95. tran := &http.Transport{
  96. //TLSClientConfig: loadTlsConfig(),
  97. }
  98. client := &http.Client{Transport: tran, Timeout: time.Second * 180}
  99. req, err := http.NewRequest(string(method), url, body)
  100. if err != nil {
  101. return nil, err
  102. }
  103. req.Header.Set("Connection", "keep-alive")
  104. if len(contentType) == 0 {
  105. contentType = ContentTypePlain
  106. }
  107. req.Header.Set("Content-Type", string(contentType))
  108. if len(header) > 0 {
  109. for k, vs := range header {
  110. req.Header.Set(k, vs[0])
  111. for i := 1; i < len(vs); i++ {
  112. req.Header.Add(k, vs[i])
  113. }
  114. }
  115. }
  116. rsp, err := client.Do(req)
  117. if err != nil {
  118. closeBody(rsp)
  119. return nil, err
  120. }
  121. return readRsp(rsp)
  122. }
  123. func loadTlsConfig() *tls.Config {
  124. pemFile, err := FindFile("cert/2990195__241210.com.pem")
  125. if err != nil {
  126. panic(err)
  127. }
  128. keyFile, err := FindFile("cert/2990195__241210.com.key")
  129. if err != nil {
  130. panic(err)
  131. }
  132. PrintInfo(pemFile)
  133. PrintInfo(keyFile)
  134. cert, err := tls.LoadX509KeyPair(pemFile, keyFile)
  135. if err != nil {
  136. panic(err)
  137. }
  138. /*caFile, err := util.FindFile("cert/ca.pem")
  139. if err != nil {
  140. log.Fatalf("load CA cert err: %v", err)
  141. }
  142. certPool := x509.NewCertPool()
  143. ca, err := ioutil.ReadFile(caFile)
  144. if err != nil {
  145. log.Fatalf("ioutil.ReadFile err: %v", err)
  146. }
  147. if ok := certPool.AppendCertsFromPEM(ca); !ok {
  148. log.Fatalf("certPool.AppendCertsFromPEM err")
  149. }*/
  150. tlsCfg := &tls.Config{
  151. Certificates: []tls.Certificate{cert},
  152. //ClientAuth: tls.RequireAndVerifyClientCert,
  153. //ClientCAs: certPool,
  154. InsecureSkipVerify: true,
  155. }
  156. return tlsCfg
  157. }
  158. func toJson(v interface{}) (*bytes.Buffer, error) {
  159. if v == nil {
  160. return nil, nil
  161. }
  162. b, err := json.Marshal(v)
  163. if err != nil {
  164. return nil, err
  165. }
  166. //PrintInfo("response data:")
  167. //PrintJSON(v)
  168. return bytes.NewBuffer(b), nil
  169. }
  170. func readRsp(resp *http.Response) ([]byte, error) {
  171. defer closeBody(resp)
  172. return ioutil.ReadAll(resp.Body)
  173. }
  174. func closeBody(resp *http.Response) {
  175. if resp != nil && resp.Body != nil {
  176. err := resp.Body.Close()
  177. if err != nil {
  178. PrintErr(err)
  179. }
  180. }
  181. }