@@ -20,22 +20,29 @@ import (
2020 "errors"
2121 "fmt"
2222 "io"
23+ "mime/multipart"
2324 "net/http"
2425 "net/url"
2526 "os"
27+ "strconv"
2628 "strings"
2729 "time"
2830
2931 "github.com/lf-edge/ekuiper/contract/v2/api"
3032 "github.com/pingcap/failpoint"
3133
3234 "github.com/lf-edge/ekuiper/v2/internal/conf"
35+ "github.com/lf-edge/ekuiper/v2/pkg/timex"
3336)
3437
3538var BodyTypeMap = map [string ]string {"none" : "" , "text" : "text/plain" , "json" : "application/json" , "html" : "text/html" , "xml" : "application/xml" , "javascript" : "application/javascript" , "form" : "application/x-www-form-urlencoded;param=value" }
3639
3740// Send v must be a []byte or map
3841func Send (logger api.Logger , client * http.Client , bodyType string , method string , u string , headers map [string ]string , v any ) (* http.Response , error ) {
42+ return SendWithFormData (logger , client , bodyType , method , u , headers , nil , "" , v )
43+ }
44+
45+ func SendWithFormData (logger api.Logger , client * http.Client , bodyType string , method string , u string , headers map [string ]string , formData map [string ]string , formFieldName string , v any ) (* http.Response , error ) {
3946 var req * http.Request
4047 var err error
4148 switch bodyType {
@@ -69,6 +76,41 @@ func Send(logger api.Logger, client *http.Client, bodyType string, method string
6976 if req .Header .Get ("Content-Type" ) == "" {
7077 req .Header .Set ("Content-Type" , BodyTypeMap [bodyType ])
7178 }
79+ case "formdata" :
80+ var requestBody bytes.Buffer
81+ writer := multipart .NewWriter (& requestBody )
82+ fileField , err := writer .CreateFormFile (formFieldName , strconv .FormatInt (timex .GetNowInMilli (), 10 ))
83+ if err != nil {
84+ return nil , fmt .Errorf ("fail to create file field: %v" , err )
85+ }
86+ var payload io.Reader
87+ switch t := v .(type ) {
88+ case []byte :
89+ payload = bytes .NewBuffer (t )
90+ case string :
91+ payload = bytes .NewBufferString (t )
92+ default :
93+ return nil , fmt .Errorf ("http send only supports bytes but receive invalid content: %v" , v )
94+ }
95+ _ , err = io .Copy (fileField , payload )
96+ if err != nil {
97+ return nil , fmt .Errorf ("fail to copy payload to file field: %v" , err )
98+ }
99+ for k , v := range formData {
100+ err := writer .WriteField (k , v )
101+ if err != nil {
102+ logger .Errorf ("fail write form data field %s: %v" , k , err )
103+ }
104+ }
105+ err = writer .Close ()
106+ if err != nil {
107+ logger .Errorf ("fail to close writer: %v" , err )
108+ }
109+ req , err = http .NewRequest (method , u , & requestBody )
110+ if err != nil {
111+ return nil , fmt .Errorf ("fail to create request: %v" , err )
112+ }
113+ req .Header .Set ("Content-Type" , writer .FormDataContentType ())
72114 default :
73115 return nil , fmt .Errorf ("unsupported body type %s" , bodyType )
74116 }
0 commit comments