http.go 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237
  1. // Copyright 2021-2023 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. case string:
  46. body = bytes.NewBufferString(t)
  47. default:
  48. vj, err := json.Marshal(v)
  49. if err != nil {
  50. return nil, fmt.Errorf("invalid content: %v", v)
  51. }
  52. body = bytes.NewBuffer(vj)
  53. }
  54. req, err = http.NewRequest(method, u, body)
  55. if err != nil {
  56. return nil, fmt.Errorf("fail to create request: %v", err)
  57. }
  58. req.Header.Set("Content-Type", BodyTypeMap[bodyType])
  59. case "form":
  60. form := url.Values{}
  61. im, err := convertToMap(v, sendSingle)
  62. if err != nil {
  63. return nil, err
  64. }
  65. for key, value := range im {
  66. var vstr string
  67. switch value.(type) {
  68. case []interface{}, map[string]interface{}:
  69. if temp, err := json.Marshal(value); err != nil {
  70. return nil, fmt.Errorf("fail to parse from value: %v", err)
  71. } else {
  72. vstr = string(temp)
  73. }
  74. default:
  75. vstr = fmt.Sprintf("%v", value)
  76. }
  77. form.Set(key, vstr)
  78. }
  79. body := io.NopCloser(strings.NewReader(form.Encode()))
  80. req, err = http.NewRequest(method, u, body)
  81. if err != nil {
  82. return nil, fmt.Errorf("fail to create request: %v", err)
  83. }
  84. req.Header.Set("Content-Type", "application/x-www-form-urlencoded;param=value")
  85. default:
  86. return nil, fmt.Errorf("unsupported body type %s", bodyType)
  87. }
  88. if len(headers) > 0 {
  89. for k, v := range headers {
  90. req.Header.Set(k, v)
  91. }
  92. }
  93. logger.Debugf("do request: %#v", req)
  94. return client.Do(req)
  95. }
  96. func convertToMap(v interface{}, sendSingle bool) (map[string]interface{}, error) {
  97. switch t := v.(type) {
  98. case []byte:
  99. r := make(map[string]interface{})
  100. if err := json.Unmarshal(t, &r); err != nil {
  101. if sendSingle {
  102. return nil, fmt.Errorf("fail to decode content: %v", err)
  103. } else {
  104. r["result"] = string(t)
  105. }
  106. }
  107. return r, nil
  108. case map[string]interface{}:
  109. return t, nil
  110. case []map[string]interface{}:
  111. r := make(map[string]interface{})
  112. if sendSingle {
  113. return nil, fmt.Errorf("invalid content: %v", t)
  114. } else {
  115. j, err := json.Marshal(t)
  116. if err != nil {
  117. return nil, err
  118. }
  119. r["result"] = string(j)
  120. }
  121. return r, nil
  122. default:
  123. return nil, fmt.Errorf("invalid content: %v", v)
  124. }
  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. // ReadFile Need to close the return reader
  147. func ReadFile(uri string) (io.ReadCloser, error) {
  148. conf.Log.Infof("Start to download file %s\n", uri)
  149. u, err := url.ParseRequestURI(uri)
  150. if err != nil {
  151. return nil, err
  152. }
  153. var src io.ReadCloser
  154. switch u.Scheme {
  155. case "file":
  156. // deal with windows path
  157. if strings.Index(u.Path, ":") == 2 {
  158. u.Path = u.Path[1:]
  159. }
  160. conf.Log.Debugf(u.Path)
  161. sourceFileStat, err := os.Stat(u.Path)
  162. if err != nil {
  163. return nil, err
  164. }
  165. if !sourceFileStat.Mode().IsRegular() {
  166. return nil, fmt.Errorf("%s is not a regular file", u.Path)
  167. }
  168. srcFile, err := os.Open(u.Path)
  169. if err != nil {
  170. return nil, err
  171. }
  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 nil, err
  185. }
  186. if resp.StatusCode != http.StatusOK {
  187. return nil, fmt.Errorf("cannot download the file with status: %s", resp.Status)
  188. }
  189. src = resp.Body
  190. default:
  191. return nil, fmt.Errorf("unsupported url scheme %s", u.Scheme)
  192. }
  193. return src, nil
  194. }
  195. func DownloadFile(filepath string, uri string) error {
  196. src, err := ReadFile(uri)
  197. if err != nil {
  198. return err
  199. }
  200. defer src.Close()
  201. // Create the file
  202. out, err := os.Create(filepath)
  203. if err != nil {
  204. return err
  205. }
  206. defer out.Close()
  207. // Write the body to file
  208. _, err = io.Copy(out, src)
  209. return err
  210. }
  211. func IsHttpUrl(str string) error {
  212. url, err := url.ParseRequestURI(str)
  213. if err != nil {
  214. return err
  215. }
  216. if url.Scheme != "http" && url.Scheme != "https" {
  217. return fmt.Errorf("Invalid scheme %s", url.Scheme)
  218. }
  219. if url.Host == "" {
  220. return fmt.Errorf("Invalid url, host not found")
  221. }
  222. return nil
  223. }