edgexCall.go 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327
  1. package tools
  2. import (
  3. "bytes"
  4. "encoding/json"
  5. "fmt"
  6. "io"
  7. "io/ioutil"
  8. "mime/multipart"
  9. "net"
  10. "net/http"
  11. "net/url"
  12. "os"
  13. "strconv"
  14. "strings"
  15. "time"
  16. )
  17. func Get(url string, authinfo ...string) (interface{}, error) {
  18. timeout := time.Duration(5 * time.Second)
  19. client := &http.Client{Timeout: timeout}
  20. req, reqerr := http.NewRequest("GET", url, nil)
  21. if reqerr != nil {
  22. fmt.Println(url)
  23. return nil, reqerr
  24. }
  25. if len(authinfo) > 0 && authinfo[0] != "" {
  26. req.Header.Set("Authorization", authinfo[0])
  27. }
  28. result, httperr := client.Do(req)
  29. //defer result.Body.Close()
  30. if httperr != nil {
  31. fmt.Println(url)
  32. return nil, httperr
  33. }
  34. body, err := ioutil.ReadAll(result.Body)
  35. if err != nil {
  36. return nil, err
  37. }
  38. result.Close = true
  39. return returnBody(body)
  40. }
  41. func Post(url string, data interface{}, authinfo ...string) (interface{}, error) {
  42. timeout := time.Duration(5 * time.Second)
  43. client := &http.Client{Timeout: timeout}
  44. req, reqerr := http.NewRequest("POST", url, strings.NewReader(data.(string)))
  45. if reqerr != nil {
  46. return nil, reqerr
  47. }
  48. if len(authinfo) > 0 && authinfo[0] != "" {
  49. req.Header.Set("Authorization", authinfo[0])
  50. //req.Header.Set("Content-Type", "application/json;charset=utf-8")
  51. }
  52. req.Header.Set("Content-Type", "application/x-www-form-urlencoded;charset=utf-8")
  53. result, httperr := client.Do(req)
  54. //defer result.Body.Close()
  55. if httperr != nil {
  56. fmt.Println(url)
  57. fmt.Println(data)
  58. return nil, httperr
  59. }
  60. body, err := ioutil.ReadAll(result.Body)
  61. if err != nil {
  62. return nil, err
  63. }
  64. result.Close = true
  65. return returnBody(body)
  66. }
  67. func PostJson(url string, data interface{}, authinfo ...string) (interface{}, error) {
  68. timeout := time.Duration(5 * time.Second)
  69. client := &http.Client{Timeout: timeout}
  70. req, reqerr := http.NewRequest("POST", url, strings.NewReader(data.(string)))
  71. if reqerr != nil {
  72. fmt.Println(url)
  73. fmt.Println(data)
  74. return nil, reqerr
  75. }
  76. if len(authinfo) > 0 && authinfo[0] != "" {
  77. req.Header.Set("Authorization", authinfo[0])
  78. //
  79. }
  80. req.Header.Set("Content-Type", "application/json;charset=utf-8")
  81. result, httperr := client.Do(req)
  82. //defer result.Body.Close()
  83. if httperr != nil {
  84. fmt.Println(url)
  85. fmt.Println(data)
  86. return nil, httperr
  87. }
  88. body, err := ioutil.ReadAll(result.Body)
  89. if err != nil {
  90. return nil, err
  91. }
  92. result.Close = true
  93. return returnBody(body)
  94. }
  95. func PostRaw(url string, data interface{}) (interface{}, error) {
  96. result, httperr := http.Post(url, "text/plain;charset=utf-8", strings.NewReader(data.(string)))
  97. if httperr != nil {
  98. fmt.Println(url)
  99. fmt.Println(data)
  100. return nil, httperr
  101. }
  102. body, err := ioutil.ReadAll(result.Body)
  103. if err != nil {
  104. return nil, err
  105. }
  106. result.Close = true
  107. return returnBody(body)
  108. }
  109. func PostForm(url string, data url.Values, authinfo ...string) (interface{}, error) {
  110. timeout := time.Duration(5 * time.Second)
  111. client := &http.Client{Timeout: timeout}
  112. req, reqerr := http.NewRequest("POST", url, strings.NewReader(data.Encode()))
  113. if reqerr != nil {
  114. fmt.Println(url)
  115. fmt.Println(data)
  116. return nil, reqerr
  117. }
  118. if len(authinfo) > 0 && authinfo[0] != "" {
  119. req.Header.Set("Authorization", authinfo[0])
  120. }
  121. req.Header.Set("Content-Type", "application/x-www-form-urlencoded;charset=utf-8")
  122. result, httperr := client.Do(req)
  123. //defer result.Body.Close()
  124. if httperr != nil {
  125. fmt.Println(url)
  126. fmt.Println(data)
  127. return nil, httperr
  128. }
  129. body, err := ioutil.ReadAll(result.Body)
  130. if err != nil {
  131. return nil, err
  132. }
  133. result.Close = true
  134. return returnBody(body)
  135. }
  136. func PostRawBasicAuth(url string, data interface{}, user string, pwd string) (interface{}, error) {
  137. client := http.Client{
  138. Transport: &http.Transport{
  139. Dial: func(netw, addr string) (net.Conn, error) {
  140. c, err := net.DialTimeout(netw, addr, time.Second*5)
  141. if err != nil {
  142. fmt.Println("dail timeout", err)
  143. return nil, err
  144. }
  145. return c, nil
  146. },
  147. MaxIdleConnsPerHost: 10,
  148. ResponseHeaderTimeout: time.Second * 5,
  149. },
  150. }
  151. req, _ := http.NewRequest("POST", url, strings.NewReader(data.(string)))
  152. req.SetBasicAuth(user, pwd)
  153. req.Header.Set("Content-Type", "text/plain;charset=utf-8")
  154. result, httperr := client.Do(req)
  155. //result, httperr := http.Post(url, "text/plain;charset=utf-8", strings.NewReader(data.(string)))
  156. if httperr != nil {
  157. fmt.Println(url)
  158. fmt.Println(data)
  159. return nil, httperr
  160. }
  161. body, err := ioutil.ReadAll(result.Body)
  162. if err != nil {
  163. return nil, err
  164. }
  165. result.Close = true
  166. return returnBody(body)
  167. }
  168. func Put(url string, data interface{}) (interface{}, error) {
  169. req, httperr := http.NewRequest("PUT", url, strings.NewReader(data.(string)))
  170. if httperr != nil {
  171. return nil, httperr
  172. }
  173. res, httperr := http.DefaultClient.Do(req)
  174. if httperr != nil {
  175. return nil, httperr
  176. }
  177. body, err := ioutil.ReadAll(res.Body)
  178. if err != nil {
  179. return nil, err
  180. }
  181. res.Close = true
  182. return returnBody(body)
  183. }
  184. func Delete(url string) (interface{}, error) {
  185. req, httperr := http.NewRequest("DELETE", url, nil)
  186. //req.Header.Add("Authorization", "5F6MJ3N2Tk9ruL_6XQpx-uxkkg:o56-nIwtgTzUX80YCNpbcjUL8iM=:eyJyZXNvdXJjZSI6IF9mbG93RGF0YVNvdXJjZTEiLCJleHBpcmVzIjoxNTM2NzU4ODE2LCJjb250ZW50TUQ1IjoiIiwiY29udGVudFR5cGUiOiIiLCJoZWFkZXJzIjoiIiwibWV0aG9kIjoiREVMRVRFIn0=")
  187. if httperr != nil {
  188. return nil, httperr
  189. }
  190. res, httperr := http.DefaultClient.Do(req)
  191. if httperr != nil {
  192. return nil, httperr
  193. }
  194. body, httperr := ioutil.ReadAll(res.Body)
  195. if httperr != nil {
  196. return nil, httperr
  197. }
  198. res.Close = true
  199. return returnBody(body)
  200. }
  201. func PostFile(targetUrl string, filename string, filed string) (interface{}, error) {
  202. bodyBuf := &bytes.Buffer{}
  203. bodyWriter := multipart.NewWriter(bodyBuf)
  204. //关键的一步操作
  205. fileWriter, err := bodyWriter.CreateFormFile(filed, filename)
  206. if err != nil {
  207. fmt.Println("error writing to buffer")
  208. return nil, err
  209. }
  210. //打开文件句柄操作
  211. fh, err := os.Open(filename)
  212. if err != nil {
  213. fmt.Println("error opening file")
  214. return nil, err
  215. }
  216. defer fh.Close()
  217. //iocopy
  218. _, err = io.Copy(fileWriter, fh)
  219. if err != nil {
  220. return nil, err
  221. }
  222. contentType := bodyWriter.FormDataContentType()
  223. bodyWriter.Close()
  224. resp, err := http.Post(targetUrl, contentType, bodyBuf)
  225. if err != nil {
  226. return nil, err
  227. }
  228. body, err := ioutil.ReadAll(resp.Body)
  229. if err != nil {
  230. return nil, err
  231. }
  232. resp.Close = true
  233. return returnBody(body)
  234. }
  235. func Soap11(url string, databody string) (interface{}, error) {
  236. reqBody := `<?xml version="1.0" encoding="utf-8"?><soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  237. xmlns:xsd="http://www.w3.org/2001/XMLSchema"
  238. xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
  239. <soap:Body>` + databody + `</soap:Body>
  240. </soap:Envelope>`
  241. res, err := http.Post(url, "text/xml; charset=UTF-8", strings.NewReader(reqBody))
  242. if nil != err {
  243. fmt.Println("http post err:", err)
  244. return nil, err
  245. }
  246. defer res.Body.Close()
  247. // return status
  248. if http.StatusOK != res.StatusCode {
  249. fmt.Println("WebService soap1.1 request fail, status: %s\n", res.StatusCode)
  250. return strconv.Itoa(http.StatusOK), nil
  251. }
  252. data, err := ioutil.ReadAll(res.Body)
  253. if nil != err {
  254. fmt.Println("ioutil ReadAll err:", err)
  255. return nil, err
  256. }
  257. return string(data), nil
  258. }
  259. func Soap12(url string, databody string) (interface{}, error) {
  260. reqBody := `<?xml version="1.0" encoding="utf-8"?><soap12:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  261. xmlns:xsd="http://www.w3.org/2001/XMLSchema"
  262. xmlns:soap12="http://www.w3.org/2003/05/soap-envelope">
  263. <soap12:Body>` + databody + `</soap12:Body>
  264. </soap12:Envelope>`
  265. res, err := http.Post(url, "application/soap+xml; charset=UTF-8", strings.NewReader(reqBody))
  266. if nil != err {
  267. fmt.Println("http post err:", err)
  268. return nil, err
  269. }
  270. defer res.Body.Close()
  271. // return status
  272. if http.StatusOK != res.StatusCode {
  273. fmt.Println("WebService soap1.1 request fail, status: %s\n", res.StatusCode)
  274. return strconv.Itoa(http.StatusOK), nil
  275. }
  276. data, err := ioutil.ReadAll(res.Body)
  277. if nil != err {
  278. fmt.Println("ioutil ReadAll err:", err)
  279. return nil, err
  280. }
  281. return string(data), nil
  282. }
  283. func returnBody(body []byte) (interface{}, error) {
  284. if len(body) == 0 {
  285. return "", nil
  286. }
  287. jsonStr := string(body)
  288. firstChar := jsonStr[0:1]
  289. if firstChar == "[" || firstChar == "{" {
  290. jsondata := make(map[string]interface{})
  291. newStr := `{"a":` + jsonStr + `}`
  292. err := json.Unmarshal([]byte(newStr), &jsondata)
  293. if err != nil {
  294. return jsonStr, err
  295. }
  296. return jsondata["a"], nil
  297. } else {
  298. return jsonStr, nil
  299. }
  300. }