http.go 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222
  1. // Copyright 2021-2022 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. "io"
  21. "net/http"
  22. "net/url"
  23. "os"
  24. "strings"
  25. "time"
  26. "github.com/lf-edge/ekuiper/internal/conf"
  27. "github.com/lf-edge/ekuiper/pkg/api"
  28. )
  29. var BodyTypeMap = map[string]string{"none": "", "text": "text/plain", "json": "application/json", "html": "text/html", "xml": "application/xml", "javascript": "application/javascript", "form": ""}
  30. // Send v must be a []byte or map
  31. 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) {
  32. var req *http.Request
  33. var err error
  34. switch bodyType {
  35. case "none":
  36. req, err = http.NewRequest(method, u, nil)
  37. if err != nil {
  38. return nil, fmt.Errorf("fail to create request: %v", err)
  39. }
  40. case "json", "text", "javascript", "html", "xml":
  41. var body = &(bytes.Buffer{})
  42. switch t := v.(type) {
  43. case []byte:
  44. body = bytes.NewBuffer(t)
  45. default:
  46. vj, err := json.Marshal(v)
  47. if err != nil {
  48. return nil, fmt.Errorf("invalid content: %v", v)
  49. }
  50. body = bytes.NewBuffer(vj)
  51. }
  52. req, err = http.NewRequest(method, u, body)
  53. if err != nil {
  54. return nil, fmt.Errorf("fail to create request: %v", err)
  55. }
  56. req.Header.Set("Content-Type", BodyTypeMap[bodyType])
  57. case "form":
  58. form := url.Values{}
  59. im, err := convertToMap(v, sendSingle)
  60. if err != nil {
  61. return nil, err
  62. }
  63. for key, value := range im {
  64. var vstr string
  65. switch value.(type) {
  66. case []interface{}, map[string]interface{}:
  67. if temp, err := json.Marshal(value); err != nil {
  68. return nil, fmt.Errorf("fail to parse from value: %v", err)
  69. } else {
  70. vstr = string(temp)
  71. }
  72. default:
  73. vstr = fmt.Sprintf("%v", value)
  74. }
  75. form.Set(key, vstr)
  76. }
  77. body := io.NopCloser(strings.NewReader(form.Encode()))
  78. req, err = http.NewRequest(method, u, body)
  79. if err != nil {
  80. return nil, fmt.Errorf("fail to create request: %v", err)
  81. }
  82. req.Header.Set("Content-Type", "application/x-www-form-urlencoded;param=value")
  83. default:
  84. return nil, fmt.Errorf("unsupported body type %s", bodyType)
  85. }
  86. if len(headers) > 0 {
  87. for k, v := range headers {
  88. req.Header.Set(k, v)
  89. }
  90. }
  91. logger.Debugf("do request: %#v", req)
  92. return client.Do(req)
  93. }
  94. func convertToMap(v interface{}, sendSingle bool) (map[string]interface{}, error) {
  95. switch t := v.(type) {
  96. case []byte:
  97. r := make(map[string]interface{})
  98. if err := json.Unmarshal(t, &r); err != nil {
  99. if sendSingle {
  100. return nil, fmt.Errorf("fail to decode content: %v", err)
  101. } else {
  102. r["result"] = string(t)
  103. }
  104. }
  105. return r, nil
  106. case map[string]interface{}:
  107. return t, nil
  108. case []map[string]interface{}:
  109. r := make(map[string]interface{})
  110. if sendSingle {
  111. return nil, fmt.Errorf("invalid content: %v", t)
  112. } else {
  113. j, err := json.Marshal(t)
  114. if err != nil {
  115. return nil, err
  116. }
  117. r["result"] = string(j)
  118. }
  119. return r, nil
  120. default:
  121. return nil, fmt.Errorf("invalid content: %v", v)
  122. }
  123. return nil, fmt.Errorf("invalid content: %v", v)
  124. }
  125. func IsValidUrl(uri string) bool {
  126. pu, err := url.ParseRequestURI(uri)
  127. if err != nil {
  128. return false
  129. }
  130. switch pu.Scheme {
  131. case "http", "https":
  132. u, err := url.Parse(uri)
  133. if err != nil || u.Scheme == "" || u.Host == "" {
  134. return false
  135. }
  136. case "file":
  137. if pu.Host != "" || pu.Path == "" {
  138. return false
  139. }
  140. default:
  141. return false
  142. }
  143. return true
  144. }
  145. // ReadFile Need to close the return reader
  146. func ReadFile(uri string) (io.ReadCloser, error) {
  147. conf.Log.Infof("Start to download file %s\n", uri)
  148. u, err := url.ParseRequestURI(uri)
  149. if err != nil {
  150. return nil, err
  151. }
  152. var src io.ReadCloser
  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 nil, err
  163. }
  164. if !sourceFileStat.Mode().IsRegular() {
  165. return nil, fmt.Errorf("%s is not a regular file", u.Path)
  166. }
  167. srcFile, err := os.Open(u.Path)
  168. if err != nil {
  169. return nil, err
  170. }
  171. src = srcFile
  172. case "http", "https":
  173. // Get the data
  174. timeout := time.Duration(5 * time.Minute)
  175. client := &http.Client{
  176. Timeout: timeout,
  177. Transport: &http.Transport{
  178. TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
  179. },
  180. }
  181. resp, err := client.Get(uri)
  182. if err != nil {
  183. return nil, err
  184. }
  185. if resp.StatusCode != http.StatusOK {
  186. return nil, fmt.Errorf("cannot download the file with status: %s", resp.Status)
  187. }
  188. src = resp.Body
  189. default:
  190. return nil, fmt.Errorf("unsupported url scheme %s", u.Scheme)
  191. }
  192. return src, nil
  193. }
  194. func DownloadFile(filepath string, uri string) error {
  195. src, err := ReadFile(uri)
  196. if err != nil {
  197. return err
  198. }
  199. defer src.Close()
  200. // Create the file
  201. out, err := os.Create(filepath)
  202. if err != nil {
  203. return err
  204. }
  205. defer out.Close()
  206. // Write the body to file
  207. _, err = io.Copy(out, src)
  208. return err
  209. }