Best K6 code snippet using http.file
fileServer.go
Source:fileServer.go
...30 }31 return32}33// æ¥åä¸ä¸ªpost请æ±ï¼å°ä¸»ä½ä¸çæ件ä¿åä¸æ¥ï¼è¿åä¸ä¸ªä¸è½½é¾æ¥,æ¯æ¬¡ä»
æ¯æä¸ä¼ å个æ件34// Exampleï¼curl -F 'file=@default.conf' http://localhost:80/static/upload35func staticUploadHandler(w http.ResponseWriter, r *http.Request) {36 if r.Method != http.MethodPost {37 logs.Warn("UploadFile() receive bad request: %v", r)38 fmt.Fprint(w, "demo: curl -F 'file=@default.conf' http://localhost:80/upload")39 return40 }41 var err error42 defer func() {43 if err != nil {44 fmt.Fprintf(w, "Error happen: %v", err)45 }46 }()47 r.ParseForm()48 logs.Info("%+v", r)49 err = r.ParseMultipartForm(5 << 20)50 if err != nil {51 logs.Error(err)52 return53 }54 // æç»ä¸ä¼ å¤ä¸ªæ件ç请æ±55 if size := len(r.MultipartForm.File); size != 1 {56 err = fmt.Errorf("Reject because size of multipartForm is %d", size)57 logs.Warn(err)58 return59 }60 for _, files := range r.MultipartForm.File {61 // 解æ表å62 if size := len(files); size != 1 {63 err = fmt.Errorf("Reject because size of fileHeader is %d", len(files))64 return65 }66 header := files[0]67 logs.Info("name=%s size=%d", header.Filename, header.Size)68 var file multipart.File69 file, err = header.Open()70 if err != nil {71 logs.Error("open upload file fail: %v", err)72 return73 }74 defer file.Close()75 // ä¿åæ件å°æ¬å°ï¼åååå为éæºï¼é¿åº¦ä¸º876 var cur *os.File77 randName := tb.GetRandomString(8)78 filePath := fmt.Sprintf("%s%s.tmp", config.ServerConfig.StaticPath, randName)79 cur, err = os.Create(filePath)80 if err != nil {81 logs.Error("create file fail: %v", err)82 return83 }84 defer cur.Close()85 var size int6486 size, err = io.Copy(cur, file)87 if err != nil {88 return89 }90 // è®°å½ä¸ä¼ è®°å½å°mongo91 err = model.InsertUploadRecord(header.Filename, randName, size)92 if err != nil {93 logs.Error("save upload file record fail: err=%v", err)94 break95 }96 downloadUrl := fmt.Sprintf("%s/static/download/%s", config.ServerConfig.ServerURL, randName)97 previewUrl := fmt.Sprintf("%s/static/preview/%s.tmp", config.ServerConfig.ServerURL, randName)98 fmt.Fprintf(w,99 "\n Save file success: size=%d name=%s\n browser_download_url: %s\n browser_preview_url: %s\n command_download_url: wget --no-check-certificate --content-disposition %s \n",100 size, header.Filename, downloadUrl, previewUrl, downloadUrl)101 }102 return103}104// 以弹çªä¸è½½æ¹å¼è¿åstaticUploadHandlerä¸ä¼ çæ件105// Example: wget --no-check-certificate http://localhost:80/download/abcdefgddd106func staticDownloadHandler(w http.ResponseWriter, r *http.Request) {107 var err error108 if r.Method != http.MethodGet {109 w.WriteHeader(http.StatusMethodNotAllowed)110 logs.Warn("DownloadFile reeceive a bad request: %v", r)111 return112 }113 url := strings.Trim(fmt.Sprint(r.URL), "/") // å件ç å¿
é¡»æ£å¥½ä¸º10个å°ååæ¯114 if !regexp.MustCompile("^static/download/[a-z]{8}$").MatchString(url) {115 w.WriteHeader(http.StatusBadRequest)116 logs.Warn("unexpect url: %s", r.URL)117 return118 }119 code := url[16:] // å件ç 120 filePath := fmt.Sprintf("%s%s.tmp", config.ServerConfig.StaticPath, code)121 if !tb.CheckFileExist(filePath) {122 logs.Info("file not exist: path=%s", filePath)123 fmt.Fprintf(w, "file not exist")124 return125 }126 var record model.FileUpload127 record, err = model.GetUploadRecord(code)128 if err != nil {129 logs.Info("record not found: path=%s err=%v", filePath, err)130 fmt.Fprintf(w, "file record not found: %v", err)131 }132 err = tb.ServerFile(w, filePath, record.FileName, record.Size)133 if err != nil {134 logs.Error("ServerFile fail: %v", err)135 fmt.Fprintf(w, "Error happen: %v", err)136 return137 }138 logs.Info("Server file success: %+v", record)139}140// 以é¢è§æ¹å¼è¿åStaticPathç®å½ä¸çå¾ççèµæº141// url format: /static/preview/${fileName}142func staticPreViewHandler(w http.ResponseWriter, r *http.Request) {143 var err error144 if r.Method != http.MethodGet {145 w.WriteHeader(http.StatusMethodNotAllowed)146 logs.Warn("DownloadFile reeceive a bad request: %v", r)147 return148 }149 uri := strings.Trim(fmt.Sprint(r.URL), "/")150 uri, _ = url.QueryUnescape(uri)151 fileName := strings.TrimPrefix(uri, "static/preview/")152 filePath := config.ServerConfig.StaticPath + fileName153 logs.Info("get static path: %s", filePath)154 fileInfo, err := os.Stat(filePath)155 if err != nil {156 logs.Info("stat file fail: error=%v filePath=%s", err, filePath)157 w.WriteHeader(http.StatusNotFound)158 return159 }160 if fileInfo.IsDir() {161 logs.Warn("filePath is a floder: path=%s", filePath)162 w.WriteHeader(http.StatusNotFound)163 return164 }165 http.ServeFile(w, r, filePath)166 return167}...
upload.go
Source:upload.go
...8)9var (10 MaxUploadFileLength = 16e311)12// Upload allows uploading go file, builds it as a plugin and returns url path that runs it.13func Upload(rw http.ResponseWriter, r *http.Request) {14 if r.ContentLength > int64(MaxUploadFileLength) {15 http.Error(rw, "max upload file length exceeded", http.StatusBadRequest)16 return17 }18 name, ok := tryGetName(rw, r)19 if !ok {20 return21 }22 dir, goFile, soFile, ok := tryGetDir(rw, name)23 if !ok {24 return25 }26 if !tryMakeDirAll(rw, dir) {27 return28 }29 if !tryUpload(rw, r, goFile) {30 return31 }32 if !tryBuild(rw, goFile) {33 return34 }35 main, ok := tryLookup(rw, soFile)36 if !ok {37 return38 }39 pluginsMutex.Lock()40 defer pluginsMutex.Unlock()41 plugins[name] = main42}43func tryGetName(rw http.ResponseWriter, r *http.Request) (name string, ok bool) {44 name = r.URL.Path[len("/upload"):]45 if name == "" {46 http.Error(rw, "usage /upload/example", http.StatusBadRequest)47 return "", false48 }49 return name, true50}51func tryGetDir(rw http.ResponseWriter, name string) (dir, goFile, soFile string, ok bool) {52 wd, err := os.Getwd()53 if err != nil {54 log.Printf("unable to get working directory: %v", err)55 rw.WriteHeader(http.StatusInternalServerError)56 return "", "", "", false57 }58 s := path.Join(wd, name)59 dir = path.Dir(s)60 goFile = s + ".go"61 soFile = s + ".so"62 ok = true63 return64}65func tryMakeDirAll(rw http.ResponseWriter, dir string) bool {66 err := os.MkdirAll(dir, 0755)67 if err != nil {68 log.Printf("unable to create directory %q: %v", dir, err)69 rw.WriteHeader(http.StatusInternalServerError)70 return false71 }72 return true73}74func tryUpload(rw http.ResponseWriter, r *http.Request, goFile string) bool {75 f, err := os.Create(goFile)76 if err != nil {77 log.Printf("unable to create file %q: %v", goFile, err)78 rw.WriteHeader(http.StatusInternalServerError)79 return false80 }81 written, err := io.CopyN(f, r.Body, int64(MaxUploadFileLength))82 if err != nil && err != io.EOF {83 log.Printf("unable to copy request body: %v", err)84 // TODO BadRequest or InternalServerError85 http.Error(rw, "unable to upload file", http.StatusInternalServerError)86 return false87 }88 log.Printf("file %q (%d) uploaded", goFile, written)89 return true90}91func tryChdir(rw http.ResponseWriter, dir string) bool {92 // TODO there should be no need for changing working directory93 cur, err := os.Getwd()94 if err != nil {95 log.Printf("unable to get working directory: %v", err)96 rw.WriteHeader(http.StatusInternalServerError)97 return false98 }99 if cur != dir {100 err = os.Chdir(dir)101 }102 if err != nil {...
httpfs.go
Source:httpfs.go
1// Copyright 2013 The Go Authors. All rights reserved.2// Use of this source code is governed by a BSD-style3// license that can be found in the LICENSE file.4// Package httpfs implements http.FileSystem using a godoc vfs.FileSystem.5package httpfs // import "golang.org/x/tools/godoc/vfs/httpfs"6import (7 "fmt"8 "io"9 "net/http"10 "os"11 "golang.org/x/tools/godoc/vfs"12)13func New(fs vfs.FileSystem) http.FileSystem {14 return &httpFS{fs}15}16type httpFS struct {17 fs vfs.FileSystem18}19func (h *httpFS) Open(name string) (http.File, error) {20 fi, err := h.fs.Stat(name)21 if err != nil {22 return nil, err23 }24 if fi.IsDir() {25 return &httpDir{h.fs, name, nil}, nil26 }27 f, err := h.fs.Open(name)28 if err != nil {29 return nil, err30 }31 return &httpFile{h.fs, f, name}, nil32}33// httpDir implements http.File for a directory in a FileSystem.34type httpDir struct {35 fs vfs.FileSystem36 name string37 pending []os.FileInfo38}39func (h *httpDir) Close() error { return nil }40func (h *httpDir) Stat() (os.FileInfo, error) { return h.fs.Stat(h.name) }41func (h *httpDir) Read([]byte) (int, error) {42 return 0, fmt.Errorf("cannot Read from directory %s", h.name)43}44func (h *httpDir) Seek(offset int64, whence int) (int64, error) {45 if offset == 0 && whence == 0 {46 h.pending = nil47 return 0, nil48 }49 return 0, fmt.Errorf("unsupported Seek in directory %s", h.name)50}51func (h *httpDir) Readdir(count int) ([]os.FileInfo, error) {52 if h.pending == nil {53 d, err := h.fs.ReadDir(h.name)54 if err != nil {55 return nil, err56 }57 if d == nil {58 d = []os.FileInfo{} // not nil59 }60 h.pending = d61 }62 if len(h.pending) == 0 && count > 0 {63 return nil, io.EOF64 }65 if count <= 0 || count > len(h.pending) {66 count = len(h.pending)67 }68 d := h.pending[:count]69 h.pending = h.pending[count:]70 return d, nil71}72// httpFile implements http.File for a file (not directory) in a FileSystem.73type httpFile struct {74 fs vfs.FileSystem75 vfs.ReadSeekCloser76 name string77}78func (h *httpFile) Stat() (os.FileInfo, error) { return h.fs.Stat(h.name) }79func (h *httpFile) Readdir(int) ([]os.FileInfo, error) {80 return nil, fmt.Errorf("cannot Readdir from file %s", h.name)81}...
file
Using AI Code Generation
1import (2func main() {3 http.HandleFunc("/", index)4 http.Handle("/favicon.ico", http.NotFoundHandler())5 http.ListenAndServe(":8080", nil)6}7func index(w http.ResponseWriter, req *http.Request) {8 fmt.Println(req.Method)9 if req.Method == http.MethodPost {10 f, h, err := req.FormFile("q")11 if err != nil {12 http.Error(w, err.Error(), 500)13 }14 defer f.Close()15 fmt.Println("\tfile:", f, "
file
Using AI Code Generation
1import (2func main() {3 page, _ := ioutil.ReadAll(res.Body)4 res.Body.Close()5 fmt.Printf("%s", page)6}7import (8func main() {9 io.Copy(os.Stdout, res.Body)10 if err := res.Body.Close(); err != nil {11 panic(err)12 }13}14import (15func main() {16 io.Copy(os.Stdout, res.Body)17 if err := res.Body.Close(); err != nil {18 panic(err)19 }20}
file
Using AI Code Generation
1import (2func main() {3 if err != nil {4 fmt.Println("Error: ", err)5 }6 defer resp.Body.Close()7 body, err := ioutil.ReadAll(resp.Body)8 if err != nil {9 fmt.Println("Error: ", err)10 }11 fmt.Println(string(body))12}
file
Using AI Code Generation
1import (2func main() {3 newFile, err := os.Create("newfile.txt")4 if err != nil {5 log.Fatal(err)6 }7 if err != nil {8 log.Fatal(err)9 }10 if response.StatusCode != http.StatusOK {11 log.Fatalf("bad status: %s", response.Status)12 }13 _, err = io.Copy(newFile, response.Body)14 if err != nil {15 log.Fatal(err)16 }17}
file
Using AI Code Generation
1import (2func main() {3 if err != nil {4 fmt.Println(err)5 }6 defer resp.Body.Close()7 body, err := ioutil.ReadAll(resp.Body)8 if err != nil {9 fmt.Println(err)10 }11 fmt.Println(string(body))12}13import (14func main() {15 if err != nil {16 fmt.Println(err)17 }18 defer resp.Body.Close()19 body, err := ioutil.ReadAll(resp.Body)20 if err != nil {21 fmt.Println(err)22 }23 fmt.Println(string(body))24}25import (26func main() {27 if err != nil {28 fmt.Println(err)29 }30 defer resp.Body.Close()31 body, err := ioutil.ReadAll(resp.Body)32 if err != nil {33 fmt.Println(err)34 }35 fmt.Println(string(body))36}37import (38func main() {39 if err != nil {40 fmt.Println(err)41 }42 defer resp.Body.Close()43 body, err := ioutil.ReadAll(resp.Body)44 if err != nil {45 fmt.Println(err)46 }47 fmt.Println(string(body))48}49import (50func main() {51 if err != nil {52 fmt.Println(err)53 }54 defer resp.Body.Close()55 body, err := ioutil.ReadAll(resp.Body)56 if err != nil {57 fmt.Println(err)58 }59 fmt.Println(string(body))60}61import (
file
Using AI Code Generation
1import (2func main() {3 f, err := os.Open("newfile.txt")4 if err != nil {5 log.Fatal(err)6 }7 defer f.Close()8 if err != nil {9 log.Fatal(err)10 }11 defer resp.Body.Close()12 n, err := io.Copy(f, resp.Body)13 if err != nil {14 log.Fatal(err)15 }16 log.Println("Copied", n, "bytes")17}18import (19func main() {20 if err != nil {21 log.Fatal(err)22 }23 defer resp.Body.Close()24 f, err := os.Create("newfile.txt")25 if err != nil {26 log.Fatal(err)27 }28 defer f.Close()29 n, err := io.Copy(f, resp.Body)30 if err != nil {31 log.Fatal(err)32 }33 log.Println("Copied", n, "bytes")34}35import (36func main() {37 if err != nil {38 log.Fatal(err)39 }40 defer resp.Body.Close()41 f, err := os.Create("newfile.txt")42 if err != nil {43 log.Fatal(err)44 }45 defer f.Close()46 n, err := io.Copy(f, resp.Body)47 if err != nil {48 log.Fatal(err)49 }50 log.Println("Copied", n, "bytes")51}52import (53func main() {54 f, err := os.Open("newfile.txt")55 if err != nil {56 log.Fatal(err)57 }
file
Using AI Code Generation
1import (2func main() {3 if err != nil {4 fmt.Println(err)5 }6 defer resp.Body.Close()7 file, err := os.Create("1.png")8 if err != nil {9 fmt.Println(err)10 }11 defer file.Close()12 _, err = io.Copy(file, resp.Body)13 if err != nil {14 fmt.Println(err)15 }16}17Download File Using http.Get() Method18import (19func main() {20 if err != nil {21 fmt.Println(err)22 }23 defer resp.Body.Close()
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.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!