http PUT 请求在 golang 中上传 zip 文件
来源:stackoverflow
时间:2024-05-01 18:57:33 125浏览 收藏
本篇文章给大家分享《http PUT 请求在 golang 中上传 zip 文件》,覆盖了Golang的常见基础知识,其实一个语言的全部知识点一篇文章是不可能说完的,但希望通过这些问题,让读者对自己的掌握程度有一定的认识(B 数),从而弥补自己的不足,更好的掌握它。
问题内容
我的客户端代码基本上是尝试使用 http put 方法将 tar.gz 文件上传到服务器。然而服务器似乎不喜欢它并且总是向我发送 500 error 响应。以下是代码。我不确定出了什么问题。
func upLoadFileToServer (uploadFileName string) { tr := &http.Transport{ TLSClientConfig: &tls.Config{InsecureSkipVerify: true}, ExpectContinueTimeout : 30 * time.Second, } client := &http.Client{ Transport:tr, Timeout: 20 * time.Second} timeCurrent = time.Now() fileContents, err := ioutil.ReadFile(uploadFileName) if err != nil { log.Println("Failed to Read the File", uploadFileName, err) } PutReq, _ := http.NewRequest("PUT", "https://www.example.com/upload", strings.NewReader(string(fileContents))) PutReq.Header.Set("Content-Type", "application/zip") PutReq.ContentLength = int64(len(string(fileContents))) PutReq.Header.Set("Expect", "100-continue") PutReq.Header.Set("Accept", "*/*") PutReq.Header.Set("Date", timeCurrent.Format(time.RFC1123)) PutResp, err := client.Do(inventoryPutReq) }
有时我会注意到“connection reset by peer”错误。但大多数时候它是 500。我使用 postman 尝试完全相同的请求,它似乎工作正常。
解决方案
这是一个工作示例。
最有可能的情况是,服务器有点简单,并且按字面意思获取文件名。由于您没有在 uploadfilename
上使用 filepath.base
,因此它可能包含路径元素。只需在您的文件名上使用它即可进行测试。
重置可能是由于超时造成的。
package main import ( "bytes" "flag" "fmt" "io" "log" "mime/multipart" "net" "net/http" "os" "path/filepath" "sync" ) var ( targetPath string filename string port int handlerLog *log.Logger mainLog *log.Logger ) // This is automatically called after vars have been initialized and before main func init() { flag.StringVar(&targetPath, "target", "./tmp", "target directory for uploads") flag.StringVar(&filename, "file", "", "file to upload") flag.IntVar(&port, "port", 0, "port to listen on. When 0, a random port is assigned") handlerLog = log.New(os.Stdout, "[handler] ", log.LstdFlags) mainLog = log.New(os.Stdout, "[main ] ", log.LstdFlags) } // By returning a handler, we have an elegant way of initializing path. func uploadHandler(path string) http.Handler { // We make sure path is an existing directory when the handler takes over if s, err := os.Stat(path); err != nil { if os.IsNotExist(err) { handlerLog.Printf("Target '%s' does not exist. Creating it...", path) if cerr := os.MkdirAll(path, 0755); cerr != nil { handlerLog.Fatalf("Creating target: %s", err) } } else { handlerLog.Fatalf("Error accessing '%s': %s", path, err) } } else if !s.IsDir() { handlerLog.Fatalf("Target '%s' is not a directory", path) } // Do NOT use this handler in production!!! // It is lacking all sorts of safety measures. // However, it is enough to demonstrate. return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { handlerLog.Println("Handling file upload...") handlerLog.Println("Parsing form...") if err := r.ParseMultipartForm(32 << 20); err != nil { handlerLog.Fatalf("Parsing form: %s", err) } f, h, err := r.FormFile("file") if err != nil { handlerLog.Printf("Error accessing file: %s", err) http.Error(w, http.StatusText(http.StatusBadRequest), http.StatusBadRequest) return } defer f.Close() handlerLog.Println("Opening output file...") t, err := os.OpenFile(filepath.Join(path, filepath.Base(h.Filename)), os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0644) if err != nil { handlerLog.Printf("Opening output file: %s", err) http.Error(w, http.StatusText(http.StatusInternalServerError)+": "+err.Error(), http.StatusInternalServerError) return } defer t.Close() handlerLog.Println("Copying to output file...") if _, err = io.Copy(t, f); err != nil { handlerLog.Printf("Copying to output file: %s", err) http.Error(w, http.StatusText(http.StatusInternalServerError)+": "+err.Error(), http.StatusInternalServerError) return } handlerLog.Println("Finished handler!") }) } func main() { flag.Parse() // Check input if filename == "" { mainLog.Fatal("No filename given. Exiting...") } mainLog.Println("Setting up upload handler...") http.Handle("/upload", uploadHandler(targetPath)) wg := sync.WaitGroup{} wg.Add(1) // We want to finish the program after upload, as we only want to demonstrate go func() { mainLog.Println("Setting up listener...") listener, err := net.Listen("tcp", fmt.Sprintf("127.0.0.1:%d", port)) if err != nil { mainLog.Fatalf("%s", err) } defer listener.Close() port = listener.Addr().(*net.TCPAddr).Port mainLog.Printf("Listening to port %d on localhost", port) wg.Done() http.Serve(listener, nil) }() buf := bytes.NewBuffer(nil) bodyWriter := multipart.NewWriter(buf) // We need to truncate the input filename, as the server might be stupid and take the input // filename verbatim. Then, he will have directory parts which do not exist on the server. fileWriter, err := bodyWriter.CreateFormFile("file", filepath.Base(filename)) if err != nil { mainLog.Fatalf("Creating fileWriter: %s", err) } file, err := os.Open(filename) if err != nil { mainLog.Fatalf("Opening file: %s", err) } defer file.Close() if _, err := io.Copy(fileWriter, file); err != nil { mainLog.Fatalf("Buffering file: %s", err) } // We have all the data written to the bodyWriter. // Now we can infer the content type contentType := bodyWriter.FormDataContentType() // This is mandatory as it flushes the buffer. bodyWriter.Close() // As we wait for the server to spin up, we need to wait here. mainLog.Println("Waiting for the listener to be set up...") wg.Wait() req, err := http.NewRequest(http.MethodPut, fmt.Sprintf("http://127.0.0.1:%d/upload", port), buf) if err != nil { mainLog.Fatalf("Creating request: %s", err) } req.Header.Set("Content-Type", contentType) client := http.Client{} mainLog.Println("Sending file") res, err := client.Do(req) if err != nil { mainLog.Fatalf("Sending file: %s", err) } mainLog.Printf("Received %s from server. Exiting...", res.Status) }
以上就是《http PUT 请求在 golang 中上传 zip 文件》的详细内容,更多关于的资料请关注golang学习网公众号!
声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
-
502 收藏
-
502 收藏
-
501 收藏
-
501 收藏
-
501 收藏
最新阅读
更多>
-
139 收藏
-
204 收藏
-
325 收藏
-
477 收藏
-
486 收藏
-
439 收藏
课程推荐
更多>
-
- 前端进阶之JavaScript设计模式
- 设计模式是开发人员在软件开发过程中面临一般问题时的解决方案,代表了最佳的实践。本课程的主打内容包括JS常见设计模式以及具体应用场景,打造一站式知识长龙服务,适合有JS基础的同学学习。
- 立即学习 542次学习
-
- GO语言核心编程课程
- 本课程采用真实案例,全面具体可落地,从理论到实践,一步一步将GO核心编程技术、编程思想、底层实现融会贯通,使学习者贴近时代脉搏,做IT互联网时代的弄潮儿。
- 立即学习 507次学习
-
- 简单聊聊mysql8与网络通信
- 如有问题加微信:Le-studyg;在课程中,我们将首先介绍MySQL8的新特性,包括性能优化、安全增强、新数据类型等,帮助学生快速熟悉MySQL8的最新功能。接着,我们将深入解析MySQL的网络通信机制,包括协议、连接管理、数据传输等,让
- 立即学习 497次学习
-
- JavaScript正则表达式基础与实战
- 在任何一门编程语言中,正则表达式,都是一项重要的知识,它提供了高效的字符串匹配与捕获机制,可以极大的简化程序设计。
- 立即学习 487次学习
-
- 从零制作响应式网站—Grid布局
- 本系列教程将展示从零制作一个假想的网络科技公司官网,分为导航,轮播,关于我们,成功案例,服务流程,团队介绍,数据部分,公司动态,底部信息等内容区块。网站整体采用CSSGrid布局,支持响应式,有流畅过渡和展现动画。
- 立即学习 484次学习