http.go 7.4 KB

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