http.go 6.2 KB

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