http.go 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214
  1. // Copyright 2021 EMQ Technologies Co., Ltd.
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package httpx
  15. import (
  16. "bytes"
  17. "crypto/tls"
  18. "encoding/json"
  19. "fmt"
  20. "github.com/lf-edge/ekuiper/internal/conf"
  21. "github.com/lf-edge/ekuiper/pkg/api"
  22. "io"
  23. "io/ioutil"
  24. "net/http"
  25. "net/url"
  26. "os"
  27. "strings"
  28. "time"
  29. )
  30. var BodyTypeMap = map[string]string{"none": "", "text": "text/plain", "json": "application/json", "html": "text/html", "xml": "application/xml", "javascript": "application/javascript", "form": ""}
  31. // Send v must be a []byte or map
  32. func Send(logger api.Logger, client *http.Client, bodyType string, method string, u string, headers map[string]string, sendSingle bool, v interface{}) (*http.Response, error) {
  33. var req *http.Request
  34. var err error
  35. switch bodyType {
  36. case "none":
  37. req, err = http.NewRequest(method, u, nil)
  38. if err != nil {
  39. return nil, fmt.Errorf("fail to create request: %v", err)
  40. }
  41. case "json", "text", "javascript", "html", "xml":
  42. var body = &(bytes.Buffer{})
  43. switch t := v.(type) {
  44. case []byte:
  45. body = bytes.NewBuffer(t)
  46. default:
  47. vj, err := json.Marshal(v)
  48. if err != nil {
  49. return nil, fmt.Errorf("invalid content: %v", v)
  50. }
  51. body = bytes.NewBuffer(vj)
  52. }
  53. req, err = http.NewRequest(method, u, body)
  54. if err != nil {
  55. return nil, fmt.Errorf("fail to create request: %v", err)
  56. }
  57. req.Header.Set("Content-Type", BodyTypeMap[bodyType])
  58. case "form":
  59. form := url.Values{}
  60. im, err := convertToMap(v, sendSingle)
  61. if err != nil {
  62. return nil, err
  63. }
  64. for key, value := range im {
  65. var vstr string
  66. switch value.(type) {
  67. case []interface{}, map[string]interface{}:
  68. if temp, err := json.Marshal(value); err != nil {
  69. return nil, fmt.Errorf("fail to parse from value: %v", err)
  70. } else {
  71. vstr = string(temp)
  72. }
  73. default:
  74. vstr = fmt.Sprintf("%v", value)
  75. }
  76. form.Set(key, vstr)
  77. }
  78. body := ioutil.NopCloser(strings.NewReader(form.Encode()))
  79. req, err = http.NewRequest(method, u, body)
  80. if err != nil {
  81. return nil, fmt.Errorf("fail to create request: %v", err)
  82. }
  83. req.Header.Set("Content-Type", "application/x-www-form-urlencoded;param=value")
  84. default:
  85. return nil, fmt.Errorf("unsupported body type %s", bodyType)
  86. }
  87. if len(headers) > 0 {
  88. for k, v := range headers {
  89. req.Header.Set(k, v)
  90. }
  91. }
  92. logger.Debugf("do request: %#v", req)
  93. return client.Do(req)
  94. }
  95. func convertToMap(v interface{}, sendSingle bool) (map[string]interface{}, error) {
  96. switch t := v.(type) {
  97. case []byte:
  98. r := make(map[string]interface{})
  99. if err := json.Unmarshal(t, &r); err != nil {
  100. if sendSingle {
  101. return nil, fmt.Errorf("fail to decode content: %v", err)
  102. } else {
  103. r["result"] = string(t)
  104. }
  105. }
  106. return r, nil
  107. case map[string]interface{}:
  108. return t, nil
  109. case []map[string]interface{}:
  110. r := make(map[string]interface{})
  111. if sendSingle {
  112. return nil, fmt.Errorf("invalid content: %v", t)
  113. } else {
  114. j, err := json.Marshal(t)
  115. if err != nil {
  116. return nil, err
  117. }
  118. r["result"] = string(j)
  119. }
  120. return r, nil
  121. default:
  122. return nil, fmt.Errorf("invalid content: %v", v)
  123. }
  124. return nil, fmt.Errorf("invalid content: %v", v)
  125. }
  126. func IsValidUrl(uri string) bool {
  127. pu, err := url.ParseRequestURI(uri)
  128. if err != nil {
  129. return false
  130. }
  131. switch pu.Scheme {
  132. case "http", "https":
  133. u, err := url.Parse(uri)
  134. if err != nil || u.Scheme == "" || u.Host == "" {
  135. return false
  136. }
  137. case "file":
  138. if pu.Host != "" || pu.Path == "" {
  139. return false
  140. }
  141. default:
  142. return false
  143. }
  144. return true
  145. }
  146. func DownloadFile(filepath string, uri string) error {
  147. conf.Log.Infof("Start to download file %s\n", uri)
  148. u, err := url.ParseRequestURI(uri)
  149. if err != nil {
  150. return err
  151. }
  152. var src io.Reader
  153. switch u.Scheme {
  154. case "file":
  155. // deal with windows path
  156. if strings.Index(u.Path, ":") == 2 {
  157. u.Path = u.Path[1:]
  158. }
  159. conf.Log.Debugf(u.Path)
  160. sourceFileStat, err := os.Stat(u.Path)
  161. if err != nil {
  162. return err
  163. }
  164. if !sourceFileStat.Mode().IsRegular() {
  165. return fmt.Errorf("%s is not a regular file", u.Path)
  166. }
  167. srcFile, err := os.Open(u.Path)
  168. if err != nil {
  169. return err
  170. }
  171. defer srcFile.Close()
  172. src = srcFile
  173. case "http", "https":
  174. // Get the data
  175. timeout := time.Duration(5 * time.Minute)
  176. client := &http.Client{
  177. Timeout: timeout,
  178. Transport: &http.Transport{
  179. TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
  180. },
  181. }
  182. resp, err := client.Get(uri)
  183. if err != nil {
  184. return err
  185. }
  186. if resp.StatusCode != http.StatusOK {
  187. return fmt.Errorf("cannot download the file with status: %s", resp.Status)
  188. }
  189. defer resp.Body.Close()
  190. src = resp.Body
  191. default:
  192. return fmt.Errorf("unsupported url scheme %s", u.Scheme)
  193. }
  194. // Create the file
  195. out, err := os.Create(filepath)
  196. if err != nil {
  197. return err
  198. }
  199. defer out.Close()
  200. // Write the body to file
  201. _, err = io.Copy(out, src)
  202. return err
  203. }