http.go 4.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195
  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. 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. return nil, fmt.Errorf("invalid content: %v", v)
  47. }
  48. req, err = http.NewRequest(method, u, body)
  49. if err != nil {
  50. return nil, fmt.Errorf("fail to create request: %v", err)
  51. }
  52. req.Header.Set("Content-Type", BodyTypeMap[bodyType])
  53. case "form":
  54. form := url.Values{}
  55. im, err := convertToMap(v, sendSingle)
  56. if err != nil {
  57. return nil, err
  58. }
  59. for key, value := range im {
  60. var vstr string
  61. switch value.(type) {
  62. case []interface{}, map[string]interface{}:
  63. if temp, err := json.Marshal(value); err != nil {
  64. return nil, fmt.Errorf("fail to parse from value: %v", err)
  65. } else {
  66. vstr = string(temp)
  67. }
  68. default:
  69. vstr = fmt.Sprintf("%v", value)
  70. }
  71. form.Set(key, vstr)
  72. }
  73. body := ioutil.NopCloser(strings.NewReader(form.Encode()))
  74. req, err = http.NewRequest(method, u, body)
  75. if err != nil {
  76. return nil, fmt.Errorf("fail to create request: %v", err)
  77. }
  78. req.Header.Set("Content-Type", "application/x-www-form-urlencoded;param=value")
  79. default:
  80. return nil, fmt.Errorf("unsupported body type %s", bodyType)
  81. }
  82. if len(headers) > 0 {
  83. for k, v := range headers {
  84. req.Header.Set(k, v)
  85. }
  86. }
  87. logger.Debugf("do request: %#v", req)
  88. return client.Do(req)
  89. }
  90. func convertToMap(v interface{}, sendSingle bool) (map[string]interface{}, error) {
  91. switch t := v.(type) {
  92. case []byte:
  93. r := make(map[string]interface{})
  94. if err := json.Unmarshal(t, &r); err != nil {
  95. if sendSingle {
  96. return nil, fmt.Errorf("fail to decode content: %v", err)
  97. } else {
  98. r["result"] = string(t)
  99. }
  100. }
  101. return r, nil
  102. default:
  103. return nil, fmt.Errorf("invalid content: %v", v)
  104. }
  105. return nil, fmt.Errorf("invalid content: %v", v)
  106. }
  107. func IsValidUrl(uri string) bool {
  108. pu, err := url.ParseRequestURI(uri)
  109. if err != nil {
  110. return false
  111. }
  112. switch pu.Scheme {
  113. case "http", "https":
  114. u, err := url.Parse(uri)
  115. if err != nil || u.Scheme == "" || u.Host == "" {
  116. return false
  117. }
  118. case "file":
  119. if pu.Host != "" || pu.Path == "" {
  120. return false
  121. }
  122. default:
  123. return false
  124. }
  125. return true
  126. }
  127. func DownloadFile(filepath string, uri string) error {
  128. conf.Log.Infof("Start to download file %s\n", uri)
  129. u, err := url.ParseRequestURI(uri)
  130. if err != nil {
  131. return err
  132. }
  133. var src io.Reader
  134. switch u.Scheme {
  135. case "file":
  136. // deal with windows path
  137. if strings.Index(u.Path, ":") == 2 {
  138. u.Path = u.Path[1:]
  139. }
  140. conf.Log.Debugf(u.Path)
  141. sourceFileStat, err := os.Stat(u.Path)
  142. if err != nil {
  143. return err
  144. }
  145. if !sourceFileStat.Mode().IsRegular() {
  146. return fmt.Errorf("%s is not a regular file", u.Path)
  147. }
  148. srcFile, err := os.Open(u.Path)
  149. if err != nil {
  150. return err
  151. }
  152. defer srcFile.Close()
  153. src = srcFile
  154. case "http", "https":
  155. // Get the data
  156. timeout := time.Duration(5 * time.Minute)
  157. client := &http.Client{
  158. Timeout: timeout,
  159. Transport: &http.Transport{
  160. TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
  161. },
  162. }
  163. resp, err := client.Get(uri)
  164. if err != nil {
  165. return err
  166. }
  167. if resp.StatusCode != http.StatusOK {
  168. return fmt.Errorf("cannot download the file with status: %s", resp.Status)
  169. }
  170. defer resp.Body.Close()
  171. src = resp.Body
  172. default:
  173. return fmt.Errorf("unsupported url scheme %s", u.Scheme)
  174. }
  175. // Create the file
  176. out, err := os.Create(filepath)
  177. if err != nil {
  178. return err
  179. }
  180. defer out.Close()
  181. // Write the body to file
  182. _, err = io.Copy(out, src)
  183. return err
  184. }