How to use requestContainsFile method of http Package

Best K6 code snippet using http.requestContainsFile

request.go

Source:request.go Github

copy

Full Screen

...129 //TODO: handle/warn about unsupported/nested values130 return fmt.Sprintf("%v", v)131 }132 handleObjectBody := func(data map[string]interface{}) error {133 if !requestContainsFile(data) {134 bodyQuery := make(url.Values, len(data))135 for k, v := range data {136 bodyQuery.Set(k, formatFormVal(v))137 }138 result.Body = bytes.NewBufferString(bodyQuery.Encode())139 result.Req.Header.Set("Content-Type", "application/x-www-form-urlencoded")140 return nil141 }142 // handling multipart request143 result.Body = &bytes.Buffer{}144 mpw := multipart.NewWriter(result.Body)145 // For parameters of type common.FileData, created with open(file, "b"),146 // we write the file boundary to the body buffer.147 // Otherwise parameters are treated as standard form field.148 for k, v := range data {149 switch ve := v.(type) {150 case FileData:151 // writing our own part to handle receiving152 // different content-type than the default application/octet-stream153 h := make(textproto.MIMEHeader)154 escapedFilename := escapeQuotes(ve.Filename)155 h.Set("Content-Disposition",156 fmt.Sprintf(`form-data; name="%s"; filename="%s"`,157 k, escapedFilename))158 h.Set("Content-Type", ve.ContentType)159 // this writer will be closed either by the next part or160 // the call to mpw.Close()161 fw, err := mpw.CreatePart(h)162 if err != nil {163 return err164 }165 if _, err := fw.Write(ve.Data); err != nil {166 return err167 }168 default:169 fw, err := mpw.CreateFormField(k)170 if err != nil {171 return err172 }173 if _, err := fw.Write([]byte(formatFormVal(v))); err != nil {174 return err175 }176 }177 }178 if err := mpw.Close(); err != nil {179 return err180 }181 result.Req.Header.Set("Content-Type", mpw.FormDataContentType())182 return nil183 }184 if body != nil {185 switch data := body.(type) {186 case map[string]goja.Value:187 //TODO: fix forms submission and serialization in k6/html before fixing this..188 newData := map[string]interface{}{}189 for k, v := range data {190 newData[k] = v.Export()191 }192 if err := handleObjectBody(newData); err != nil {193 return nil, err194 }195 case map[string]interface{}:196 if err := handleObjectBody(data); err != nil {197 return nil, err198 }199 case string:200 result.Body = bytes.NewBufferString(data)201 case []byte:202 result.Body = bytes.NewBuffer(data)203 default:204 return nil, fmt.Errorf("unknown request body type %T", body)205 }206 }207 if userAgent := state.Options.UserAgent; userAgent.String != "" {208 result.Req.Header.Set("User-Agent", userAgent.String)209 }210 if state.CookieJar != nil {211 result.ActiveJar = state.CookieJar212 }213 // TODO: ditch goja.Value, reflections and Object and use a simple go map and type assertions?214 if params != nil && !goja.IsUndefined(params) && !goja.IsNull(params) {215 params := params.ToObject(rt)216 for _, k := range params.Keys() {217 switch k {218 case "cookies":219 cookiesV := params.Get(k)220 if goja.IsUndefined(cookiesV) || goja.IsNull(cookiesV) {221 continue222 }223 cookies := cookiesV.ToObject(rt)224 if cookies == nil {225 continue226 }227 for _, key := range cookies.Keys() {228 cookieV := cookies.Get(key)229 if goja.IsUndefined(cookieV) || goja.IsNull(cookieV) {230 continue231 }232 switch cookieV.ExportType() {233 case reflect.TypeOf(map[string]interface{}{}):234 result.Cookies[key] = &httpext.HTTPRequestCookie{Name: key, Value: "", Replace: false}235 cookie := cookieV.ToObject(rt)236 for _, attr := range cookie.Keys() {237 switch strings.ToLower(attr) {238 case "replace":239 result.Cookies[key].Replace = cookie.Get(attr).ToBoolean()240 case "value":241 result.Cookies[key].Value = cookie.Get(attr).String()242 }243 }244 default:245 result.Cookies[key] = &httpext.HTTPRequestCookie{Name: key, Value: cookieV.String(), Replace: false}246 }247 }248 case "headers":249 headersV := params.Get(k)250 if goja.IsUndefined(headersV) || goja.IsNull(headersV) {251 continue252 }253 headers := headersV.ToObject(rt)254 if headers == nil {255 continue256 }257 for _, key := range headers.Keys() {258 str := headers.Get(key).String()259 switch strings.ToLower(key) {260 case "host":261 result.Req.Host = str262 default:263 result.Req.Header.Set(key, str)264 }265 }266 case "jar":267 jarV := params.Get(k)268 if goja.IsUndefined(jarV) || goja.IsNull(jarV) {269 continue270 }271 switch v := jarV.Export().(type) {272 case *HTTPCookieJar:273 result.ActiveJar = v.jar274 }275 case "compression":276 var algosString = strings.TrimSpace(params.Get(k).ToString().String())277 if algosString == "" {278 continue279 }280 var algos = strings.Split(algosString, ",")281 var err error282 result.Compressions = make([]httpext.CompressionType, len(algos))283 for index, algo := range algos {284 algo = strings.TrimSpace(algo)285 result.Compressions[index], err = httpext.CompressionTypeString(algo)286 if err != nil {287 return nil, fmt.Errorf("unknown compression algorithm %s, supported algorithms are %s",288 algo, httpext.CompressionTypeValues())289 }290 }291 case "redirects":292 result.Redirects = null.IntFrom(params.Get(k).ToInteger())293 case "tags":294 tagsV := params.Get(k)295 if goja.IsUndefined(tagsV) || goja.IsNull(tagsV) {296 continue297 }298 tagObj := tagsV.ToObject(rt)299 if tagObj == nil {300 continue301 }302 for _, key := range tagObj.Keys() {303 result.Tags[key] = tagObj.Get(key).String()304 }305 case "auth":306 result.Auth = params.Get(k).String()307 case "timeout":308 result.Timeout = time.Duration(params.Get(k).ToFloat() * float64(time.Millisecond))309 case "throw":310 result.Throw = params.Get(k).ToBoolean()311 case "responseType":312 responseType, err := httpext.ResponseTypeString(params.Get(k).String())313 if err != nil {314 return nil, err315 }316 result.ResponseType = responseType317 }318 }319 }320 if result.ActiveJar != nil {321 httpext.SetRequestCookies(result.Req, result.ActiveJar, result.Cookies)322 }323 return result, nil324}325// Batch makes multiple simultaneous HTTP requests. The provideds reqsV should be an array of request326// objects. Batch returns an array of responses and/or error327func (h *HTTP) Batch(ctx context.Context, reqsV goja.Value) (goja.Value, error) {328 state := lib.GetState(ctx)329 if state == nil {330 return nil, ErrBatchForbiddenInInitContext331 }332 rt := common.GetRuntime(ctx)333 reqs := reqsV.ToObject(rt)334 keys := reqs.Keys()335 parsedReqs := map[string]*httpext.ParsedHTTPRequest{}336 for _, key := range keys {337 parsedReq, err := h.parseBatchRequest(ctx, key, reqs.Get(key))338 if err != nil {339 return nil, err340 }341 parsedReqs[key] = parsedReq342 }343 var (344 // Return values; retval must be guarded by the mutex.345 mutex sync.Mutex346 retval = rt.NewObject()347 errs = make(chan error)348 // Concurrency limits.349 globalLimiter = NewSlotLimiter(int(state.Options.Batch.Int64))350 perHostLimiter = NewMultiSlotLimiter(int(state.Options.BatchPerHost.Int64))351 )352 for k, pr := range parsedReqs {353 go func(key string, parsedReq *httpext.ParsedHTTPRequest) {354 globalLimiter.Begin()355 defer globalLimiter.End()356 if hl := perHostLimiter.Slot(parsedReq.URL.GetURL().Host); hl != nil {357 hl.Begin()358 defer hl.End()359 }360 res, err := httpext.MakeRequest(ctx, parsedReq)361 if err != nil {362 errs <- err363 return364 }365 mutex.Lock()366 _ = retval.Set(key, responseFromHttpext(res))367 mutex.Unlock()368 errs <- nil369 }(k, pr)370 }371 var err error372 for range keys {373 if e := <-errs; e != nil {374 err = e375 }376 }377 return retval, err378}379func (h *HTTP) parseBatchRequest(ctx context.Context, key string, val goja.Value) (*httpext.ParsedHTTPRequest, error) {380 var (381 method = HTTP_METHOD_GET382 ok bool383 err error384 reqURL httpext.URL385 body interface{}386 params goja.Value387 rt = common.GetRuntime(ctx)388 )389 switch data := val.Export().(type) {390 case []interface{}:391 // Handling of ["GET", "http://example.com/"]392 dataLen := len(data)393 if dataLen < 2 {394 return nil, fmt.Errorf("invalid batch request '%#v'", data)395 }396 method, ok = data[0].(string)397 if !ok {398 return nil, fmt.Errorf("invalid method type '%#v'", data[0])399 }400 reqURL, err = ToURL(data[1])401 if err != nil {402 return nil, err403 }404 if dataLen > 2 {405 body = data[2]406 }407 if dataLen > 3 {408 params = rt.ToValue(data[3])409 }410 case map[string]interface{}:411 // Handling of {method: "GET", url: "http://test.loadimpact.com"}412 if murl, ok := data["url"]; !ok {413 return nil, fmt.Errorf("batch request %s doesn't have an url key", key)414 } else if reqURL, err = ToURL(murl); err != nil {415 return nil, err416 }417 body = data["body"] // It's fine if it's missing, the map lookup will return418 if newMethod, ok := data["method"]; ok {419 if method, ok = newMethod.(string); !ok {420 return nil, fmt.Errorf("invalid method type '%#v'", newMethod)421 }422 method = strings.ToUpper(method)423 if method == HTTP_METHOD_GET || method == HTTP_METHOD_HEAD {424 body = nil425 }426 }427 if p, ok := data["params"]; ok {428 params = rt.ToValue(p)429 }430 default:431 // Handling of "http://example.com/" or http.url`http://example.com/{$id}`432 reqURL, err = ToURL(data)433 if err != nil {434 return nil, err435 }436 }437 return h.parseRequest(ctx, method, reqURL, body, params)438}439func requestContainsFile(data map[string]interface{}) bool {440 for _, v := range data {441 switch v.(type) {442 case FileData:443 return true444 }445 }446 return false447}...

Full Screen

Full Screen

requestContainsFile

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 if err != nil {4 fmt.Println(err)5 }6 request.Header.Add("Content-Type", "multipart/form-data; boundary=---------------------------9051914041544843365972754266")7 request.Header.Add("Content-Length", "0")8 request.Header.Add("Content-Disposition", "form-data; name=\"file\"; filename=\"file.txt\"")9 request.Header.Add("Content-Type", "text/plain")10 fmt.Println(requestContainsFile(request))11}12import (13func main() {14 if err != nil {15 fmt.Println(err)16 }17 request.Header.Add("Content-Type", "multipart/form-data; boundary=---------------------------9051914041544843365972754266")18 request.Header.Add("Content-Length", "0")19 request.Header.Add("Content-Disposition", "form-data; name=\"file\"; filename=\"file.txt\"")20 request.Header.Add("Content-Type", "text/plain")21 fmt.Println(requestContainsFile(request))22}23import (24func main() {25 if err != nil {26 fmt.Println(err)27 }28 request.Header.Add("Content-Type", "multipart/form-data; boundary=---------------------------9051914041544843365972754266")29 request.Header.Add("Content-Length", "0")30 request.Header.Add("Content-Disposition", "form-data; name=\"file\"; filename=\"file.txt\"")31 request.Header.Add("Content-Type", "text/plain")32 fmt.Println(requestContainsFile(request))33}34import (35func main() {

Full Screen

Full Screen

requestContainsFile

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 req.Header.Set("Content-Type", "multipart/form-data; boundary=---------------------------")4 fmt.Println(req.RequestContainsFile())5}6import (7func main() {8 req.Header.Set("Content-Type", "multipart/form-data; boundary=---------------------------")9 fmt.Println(req.RequestContainsFile())10}

Full Screen

Full Screen

requestContainsFile

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 file, err := os.Create("test.txt")4 if err != nil {5 fmt.Println(err)6 }7 defer file.Close()8 if err != nil {9 fmt.Println(err)10 }11 if reqContainsFile(req) {12 fmt.Println("Request contains a file")13 } else {14 fmt.Println("Request does not contain a file")15 }16}17func reqContainsFile(r *http.Request) bool {18 if r.Method != "POST" {19 }20 if r.Header.Get("Content-Type") != "multipart/form-data" {21 }22}23func (r *Request) FormValue(key string) string24import (25func main() {26 if err != nil {27 fmt.Println(err)28 }29 req.PostForm = url.Values{30 "name": {"John"},31 "age": {"25"},32 }33 name := req.FormValue("name")34 fmt.Println(name)35}

Full Screen

Full Screen

requestContainsFile

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 if err != nil {4 fmt.Println(err)5 os.Exit(1)6 }7 file, err := os.Open("test.txt")8 if err != nil {9 fmt.Println(err)10 os.Exit(1)11 }12 req.MultipartForm = &http.MultipartForm{13 File: map[string][]*http.FileHeader{14 "file": {15 {16 Header: make(http.Header),17 },18 },19 },20 }21 req.MultipartForm.File["file"][0].Header.Set("Content-Type", "text/plain")22 req.MultipartForm.File["file"][0].Header.Set("Content-Disposition", "form-data; name=\"file\"; filename=\"test.txt\"")23 req.MultipartForm.File["file"][0].Header.Set("Content-Transfer-Encoding", "binary")24 fileHeader := make([]byte, 512)25 file.Read(fileHeader)26 file.Seek(0, 0)27 req.MultipartForm.File["file"][0].Header.Set("Content-Type", http.DetectContentType(fileHeader))28 if requestContainsFile(req) {29 fmt.Println("Request contains a file")30 } else {31 fmt.Println("Request does not contain a file")32 }33}34func requestContainsFile(req *http.Request) bool {35 if req.MultipartForm != nil {36 for _, fheaders := range req.MultipartForm.File {37 for range fheaders {38 }39 }40 }41}

Full Screen

Full Screen

requestContainsFile

Using AI Code Generation

copy

Full Screen

1func main() {2 http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {3 if requestContainsFile(r) {4 fmt.Fprintf(w, "File uploaded successfully.")5 } else {6 fmt.Fprintf(w, "No file uploaded.")7 }8 })9 http.ListenAndServe(":8080", nil)10}11func main() {12 http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {13 if requestContainsFile(r) {14 fmt.Fprintf(w, "File uploaded successfully.")15 } else {16 fmt.Fprintf(w, "No file uploaded.")17 }18 })19 http.ListenAndServe(":8080", nil)20}21func main() {22 http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {23 if requestContainsFile(r) {24 fmt.Fprintf(w, "File uploaded successfully.")25 } else {26 fmt.Fprintf(w, "No file uploaded.")27 }28 })29 http.ListenAndServe(":8080", nil)30}31func main() {32 http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {33 if requestContainsFile(r) {34 fmt.Fprintf(w, "File uploaded successfully.")35 } else {36 fmt.Fprintf(w, "No file uploaded.")37 }38 })39 http.ListenAndServe(":8080", nil)40}41func main() {42 http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {43 if requestContainsFile(r) {44 fmt.Fprintf(w, "File uploaded successfully.")45 } else {46 fmt.Fprintf(w, "No file uploaded.")47 }48 })49 http.ListenAndServe(":8080", nil)50}51func main() {52 http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {53 if requestContainsFile(r) {54 fmt.Fprintf(w, "File uploaded successfully.")55 } else {56 fmt.Fprintf(w, "No file uploaded.")57 }58 })59 http.ListenAndServe(":8080", nil)60}

Full Screen

Full Screen

requestContainsFile

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 if err != nil {4 fmt.Println(err)5 }6 file, err := req.FormFile("file")7 if err != nil {8 fmt.Println(err)9 }10 fmt.Println(req.MultipartForm.Value["file"])11 fmt.Println(req.MultipartForm.File["file"])12 fmt.Println(req.MultipartForm.File["file"][0].Filename)13 fmt.Println(req.MultipartForm.File["file"][0].Size)14 fmt.Println(req.MultipartForm.File["file"][0].Header)15 fmt.Println(req.MultipartForm.File["file"][0].Header.Get("Content-Type"))16 fmt.Println(req.MultipartForm.File["file"][0].Header.Get("Content-Disposition"))17 fmt.Println(req.MultipartForm.File["file"][0].Header.Get("Content-Length"))18 fmt.Println(req.MultipartForm.File["file"][0].Header.Get("Content-Transfer-Encoding"))19 fmt.Println(req.MultipartForm.File["file"][0].Header.Get("Content-Location"))20 fmt.Println(req.MultipartForm.File["file"][0].Header.Get("Content-Id"))21 fmt.Println(req.MultipartForm.File["file"][0].Header.Get("Content-Description"))22 fmt.Println(req.MultipartForm.File["file"][0].Header.Get("Content-Base"))23 fmt.Println(req.MultipartForm.File["file"][0].Header.Get("Content-MD5"))24 fmt.Println(req.MultipartForm.File["file"][0].Header.Get("Content-Range"))25 fmt.Println(req.MultipartForm.File["fil

Full Screen

Full Screen

requestContainsFile

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 if err != nil {4 fmt.Println(err)5 }6 req.MultipartForm = &http.MultipartForm{File: map[string][]*http.FileHeader{7 "file": {8 &http.FileHeader{9 },10 },11 }}12 if reqContainsFile(req) {13 fmt.Println("Request contains file")14 } else {15 fmt.Println("Request does not contain file")16 }17}18func reqContainsFile(req *http.Request) bool {19 if req.MultipartForm == nil {20 }21 if req.MultipartForm.File == nil {22 }23 if len(req.MultipartForm.File) == 0 {24 }25}

Full Screen

Full Screen

requestContainsFile

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 file.MultipartForm = new(http.MultipartForm)4 file.MultipartForm.File["file"] = []*http.FileHeader{5 &http.FileHeader{6 },7 }8 fmt.Printf("File: %t9", requestContainsFile(file))10 fmt.Printf("No file: %t11", requestContainsFile(noFile))12}13func requestContainsFile(r *http.Request) bool {14}

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful