http.go 4.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181
  1. package httpx
  2. import (
  3. "bytes"
  4. "crypto/tls"
  5. "encoding/json"
  6. "fmt"
  7. "github.com/lf-edge/ekuiper/internal/conf"
  8. "github.com/lf-edge/ekuiper/pkg/api"
  9. "io"
  10. "io/ioutil"
  11. "net/http"
  12. "net/url"
  13. "os"
  14. "strings"
  15. "time"
  16. )
  17. var BodyTypeMap = map[string]string{"none": "", "text": "text/plain", "json": "application/json", "html": "text/html", "xml": "application/xml", "javascript": "application/javascript", "form": ""}
  18. 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) {
  19. var req *http.Request
  20. var err error
  21. switch bodyType {
  22. case "none":
  23. req, err = http.NewRequest(method, u, nil)
  24. if err != nil {
  25. return nil, fmt.Errorf("fail to create request: %v", err)
  26. }
  27. case "json", "text", "javascript", "html", "xml":
  28. var body = &(bytes.Buffer{})
  29. switch t := v.(type) {
  30. case []byte:
  31. body = bytes.NewBuffer(t)
  32. default:
  33. return nil, fmt.Errorf("invalid content: %v", v)
  34. }
  35. req, err = http.NewRequest(method, u, body)
  36. if err != nil {
  37. return nil, fmt.Errorf("fail to create request: %v", err)
  38. }
  39. req.Header.Set("Content-Type", BodyTypeMap[bodyType])
  40. case "form":
  41. form := url.Values{}
  42. im, err := convertToMap(v, sendSingle)
  43. if err != nil {
  44. return nil, err
  45. }
  46. for key, value := range im {
  47. var vstr string
  48. switch value.(type) {
  49. case []interface{}, map[string]interface{}:
  50. if temp, err := json.Marshal(value); err != nil {
  51. return nil, fmt.Errorf("fail to parse from value: %v", err)
  52. } else {
  53. vstr = string(temp)
  54. }
  55. default:
  56. vstr = fmt.Sprintf("%v", value)
  57. }
  58. form.Set(key, vstr)
  59. }
  60. body := ioutil.NopCloser(strings.NewReader(form.Encode()))
  61. req, err = http.NewRequest(method, u, body)
  62. if err != nil {
  63. return nil, fmt.Errorf("fail to create request: %v", err)
  64. }
  65. req.Header.Set("Content-Type", "application/x-www-form-urlencoded;param=value")
  66. default:
  67. return nil, fmt.Errorf("unsupported body type %s", bodyType)
  68. }
  69. if len(headers) > 0 {
  70. for k, v := range headers {
  71. req.Header.Set(k, v)
  72. }
  73. }
  74. logger.Debugf("do request: %#v", req)
  75. return client.Do(req)
  76. }
  77. func convertToMap(v interface{}, sendSingle bool) (map[string]interface{}, error) {
  78. switch t := v.(type) {
  79. case []byte:
  80. r := make(map[string]interface{})
  81. if err := json.Unmarshal(t, &r); err != nil {
  82. if sendSingle {
  83. return nil, fmt.Errorf("fail to decode content: %v", err)
  84. } else {
  85. r["result"] = string(t)
  86. }
  87. }
  88. return r, nil
  89. default:
  90. return nil, fmt.Errorf("invalid content: %v", v)
  91. }
  92. return nil, fmt.Errorf("invalid content: %v", v)
  93. }
  94. func IsValidUrl(uri string) bool {
  95. pu, err := url.ParseRequestURI(uri)
  96. if err != nil {
  97. return false
  98. }
  99. switch pu.Scheme {
  100. case "http", "https":
  101. u, err := url.Parse(uri)
  102. if err != nil || u.Scheme == "" || u.Host == "" {
  103. return false
  104. }
  105. case "file":
  106. if pu.Host != "" || pu.Path == "" {
  107. return false
  108. }
  109. default:
  110. return false
  111. }
  112. return true
  113. }
  114. func DownloadFile(filepath string, uri string) error {
  115. conf.Log.Infof("Start to download file %s\n", uri)
  116. u, err := url.ParseRequestURI(uri)
  117. if err != nil {
  118. return err
  119. }
  120. var src io.Reader
  121. switch u.Scheme {
  122. case "file":
  123. // deal with windows path
  124. if strings.Index(u.Path, ":") == 2 {
  125. u.Path = u.Path[1:]
  126. }
  127. conf.Log.Debugf(u.Path)
  128. sourceFileStat, err := os.Stat(u.Path)
  129. if err != nil {
  130. return err
  131. }
  132. if !sourceFileStat.Mode().IsRegular() {
  133. return fmt.Errorf("%s is not a regular file", u.Path)
  134. }
  135. srcFile, err := os.Open(u.Path)
  136. if err != nil {
  137. return err
  138. }
  139. defer srcFile.Close()
  140. src = srcFile
  141. case "http", "https":
  142. // Get the data
  143. timeout := time.Duration(5 * time.Minute)
  144. client := &http.Client{
  145. Timeout: timeout,
  146. Transport: &http.Transport{
  147. TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
  148. },
  149. }
  150. resp, err := client.Get(uri)
  151. if err != nil {
  152. return err
  153. }
  154. if resp.StatusCode != http.StatusOK {
  155. return fmt.Errorf("cannot download the file with status: %s", resp.Status)
  156. }
  157. defer resp.Body.Close()
  158. src = resp.Body
  159. default:
  160. return fmt.Errorf("unsupported url scheme %s", u.Scheme)
  161. }
  162. // Create the file
  163. out, err := os.Create(filepath)
  164. if err != nil {
  165. return err
  166. }
  167. defer out.Close()
  168. // Write the body to file
  169. _, err = io.Copy(out, src)
  170. return err
  171. }