edgexCall.go 9.0 KB

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