http.go 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268
  1. package util
  2. import (
  3. "bytes"
  4. "context"
  5. "crypto/tls"
  6. "encoding/json"
  7. "encoding/pem"
  8. "encoding/xml"
  9. "fmt"
  10. "io"
  11. "io/ioutil"
  12. "log"
  13. "mime/multipart"
  14. "net/http"
  15. "os"
  16. "golang.org/x/crypto/pkcs12"
  17. )
  18. // HTTPGet get 请求
  19. func HTTPGet(uri string) ([]byte, error) {
  20. return HTTPGetContext(context.Background(), uri)
  21. }
  22. // HTTPGetContext get 请求
  23. func HTTPGetContext(ctx context.Context, uri string) ([]byte, error) {
  24. request, err := http.NewRequestWithContext(ctx, http.MethodGet, uri, nil)
  25. if err != nil {
  26. return nil, err
  27. }
  28. response, err := http.DefaultClient.Do(request)
  29. if err != nil {
  30. return nil, err
  31. }
  32. defer response.Body.Close()
  33. if response.StatusCode != http.StatusOK {
  34. return nil, fmt.Errorf("http get error : uri=%v , statusCode=%v", uri, response.StatusCode)
  35. }
  36. return ioutil.ReadAll(response.Body)
  37. }
  38. // HTTPPost post 请求
  39. func HTTPPost(uri string, data string) ([]byte, error) {
  40. return HTTPPostContext(context.Background(), uri, data)
  41. }
  42. // HTTPPostContext post 请求
  43. func HTTPPostContext(ctx context.Context, uri string, data string) ([]byte, error) {
  44. body := bytes.NewBuffer([]byte(data))
  45. request, err := http.NewRequestWithContext(ctx, http.MethodPost, uri, body)
  46. if err != nil {
  47. return nil, err
  48. }
  49. response, err := http.DefaultClient.Do(request)
  50. if err != nil {
  51. return nil, err
  52. }
  53. defer response.Body.Close()
  54. if response.StatusCode != http.StatusOK {
  55. return nil, fmt.Errorf("http get error : uri=%v , statusCode=%v", uri, response.StatusCode)
  56. }
  57. return ioutil.ReadAll(response.Body)
  58. }
  59. // PostJSON post json 数据请求
  60. func PostJSON(uri string, obj interface{}) ([]byte, error) {
  61. jsonBuf := new(bytes.Buffer)
  62. enc := json.NewEncoder(jsonBuf)
  63. enc.SetEscapeHTML(false)
  64. err := enc.Encode(obj)
  65. if err != nil {
  66. return nil, err
  67. }
  68. response, err := http.Post(uri, "application/json;charset=utf-8", jsonBuf)
  69. if err != nil {
  70. return nil, err
  71. }
  72. defer response.Body.Close()
  73. if response.StatusCode != http.StatusOK {
  74. return nil, fmt.Errorf("http get error : uri=%v , statusCode=%v", uri, response.StatusCode)
  75. }
  76. return ioutil.ReadAll(response.Body)
  77. }
  78. // PostJSONWithRespContentType post json数据请求,且返回数据类型
  79. func PostJSONWithRespContentType(uri string, obj interface{}) ([]byte, string, error) {
  80. jsonBuf := new(bytes.Buffer)
  81. enc := json.NewEncoder(jsonBuf)
  82. enc.SetEscapeHTML(false)
  83. err := enc.Encode(obj)
  84. if err != nil {
  85. return nil, "", err
  86. }
  87. response, err := http.Post(uri, "application/json;charset=utf-8", jsonBuf)
  88. if err != nil {
  89. return nil, "", err
  90. }
  91. defer response.Body.Close()
  92. if response.StatusCode != http.StatusOK {
  93. return nil, "", fmt.Errorf("http get error : uri=%v , statusCode=%v", uri, response.StatusCode)
  94. }
  95. responseData, err := ioutil.ReadAll(response.Body)
  96. contentType := response.Header.Get("Content-Type")
  97. return responseData, contentType, err
  98. }
  99. // PostFile 上传文件
  100. func PostFile(fieldName, filename, uri string) ([]byte, error) {
  101. fields := []MultipartFormField{
  102. {
  103. IsFile: true,
  104. Fieldname: fieldName,
  105. Filename: filename,
  106. },
  107. }
  108. return PostMultipartForm(fields, uri)
  109. }
  110. // MultipartFormField 保存文件或其他字段信息
  111. type MultipartFormField struct {
  112. IsFile bool
  113. Fieldname string
  114. Value []byte
  115. Filename string
  116. }
  117. // PostMultipartForm 上传文件或其他多个字段
  118. func PostMultipartForm(fields []MultipartFormField, uri string) (respBody []byte, err error) {
  119. bodyBuf := &bytes.Buffer{}
  120. bodyWriter := multipart.NewWriter(bodyBuf)
  121. for _, field := range fields {
  122. if field.IsFile {
  123. fileWriter, e := bodyWriter.CreateFormFile(field.Fieldname, field.Filename)
  124. if e != nil {
  125. err = fmt.Errorf("error writing to buffer , err=%v", e)
  126. return
  127. }
  128. fh, e := os.Open(field.Filename)
  129. if e != nil {
  130. err = fmt.Errorf("error opening file , err=%v", e)
  131. return
  132. }
  133. defer fh.Close()
  134. if _, err = io.Copy(fileWriter, fh); err != nil {
  135. return
  136. }
  137. } else {
  138. partWriter, e := bodyWriter.CreateFormField(field.Fieldname)
  139. if e != nil {
  140. err = e
  141. return
  142. }
  143. valueReader := bytes.NewReader(field.Value)
  144. if _, err = io.Copy(partWriter, valueReader); err != nil {
  145. return
  146. }
  147. }
  148. }
  149. contentType := bodyWriter.FormDataContentType()
  150. bodyWriter.Close()
  151. resp, e := http.Post(uri, contentType, bodyBuf)
  152. if e != nil {
  153. err = e
  154. return
  155. }
  156. defer resp.Body.Close()
  157. if resp.StatusCode != http.StatusOK {
  158. return nil, err
  159. }
  160. respBody, err = ioutil.ReadAll(resp.Body)
  161. return
  162. }
  163. // PostXML perform a HTTP/POST request with XML body
  164. func PostXML(uri string, obj interface{}) ([]byte, error) {
  165. xmlData, err := xml.Marshal(obj)
  166. if err != nil {
  167. return nil, err
  168. }
  169. body := bytes.NewBuffer(xmlData)
  170. response, err := http.Post(uri, "application/xml;charset=utf-8", body)
  171. if err != nil {
  172. return nil, err
  173. }
  174. defer response.Body.Close()
  175. if response.StatusCode != http.StatusOK {
  176. return nil, fmt.Errorf("http code error : uri=%v , statusCode=%v", uri, response.StatusCode)
  177. }
  178. return ioutil.ReadAll(response.Body)
  179. }
  180. // httpWithTLS CA证书
  181. func httpWithTLS(rootCa, key string) (*http.Client, error) {
  182. var client *http.Client
  183. certData, err := ioutil.ReadFile(rootCa)
  184. if err != nil {
  185. return nil, fmt.Errorf("unable to find cert path=%s, error=%v", rootCa, err)
  186. }
  187. cert := pkcs12ToPem(certData, key)
  188. config := &tls.Config{
  189. Certificates: []tls.Certificate{cert},
  190. }
  191. tr := &http.Transport{
  192. TLSClientConfig: config,
  193. DisableCompression: true,
  194. }
  195. client = &http.Client{Transport: tr}
  196. return client, nil
  197. }
  198. // pkcs12ToPem 将Pkcs12转成Pem
  199. func pkcs12ToPem(p12 []byte, password string) tls.Certificate {
  200. blocks, err := pkcs12.ToPEM(p12, password)
  201. defer func() {
  202. if x := recover(); x != nil {
  203. log.Print(x)
  204. }
  205. }()
  206. if err != nil {
  207. panic(err)
  208. }
  209. var pemData []byte
  210. for _, b := range blocks {
  211. pemData = append(pemData, pem.EncodeToMemory(b)...)
  212. }
  213. cert, err := tls.X509KeyPair(pemData, pemData)
  214. if err != nil {
  215. panic(err)
  216. }
  217. return cert
  218. }
  219. // PostXMLWithTLS perform a HTTP/POST request with XML body and TLS
  220. func PostXMLWithTLS(uri string, obj interface{}, ca, key string) ([]byte, error) {
  221. xmlData, err := xml.Marshal(obj)
  222. if err != nil {
  223. return nil, err
  224. }
  225. body := bytes.NewBuffer(xmlData)
  226. client, err := httpWithTLS(ca, key)
  227. if err != nil {
  228. return nil, err
  229. }
  230. response, err := client.Post(uri, "application/xml;charset=utf-8", body)
  231. if err != nil {
  232. return nil, err
  233. }
  234. defer response.Body.Close()
  235. if response.StatusCode != http.StatusOK {
  236. return nil, fmt.Errorf("http code error : uri=%v , statusCode=%v", uri, response.StatusCode)
  237. }
  238. return ioutil.ReadAll(response.Body)
  239. }