http PUT请求在golang中上传zip文件

我的客户端代码基本上是尝试使用 HTTP PUT METHOD 将 tar.gz 文件上传到服务器。但是服务器似乎不喜欢它并且似乎总是向我发送 500 错误响应。以下是代码。我不确定出了什么问题。


 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 尝试完全相同的请求,它似乎工作正常。


慕姐8265434
浏览 267回答 1
1回答

GCT1015

这是一个工作示例。最有可能的是,它归结为服务器有点简单并且按字面意思获取文件名的事实。并且由于您没有filepath.Base在您的 上使用uploadFileName,因此它上面可能有路径元素。只需将它用于您的文件名以进行测试。重置可能是由超时引起的。package mainimport (&nbsp; &nbsp; "bytes"&nbsp; &nbsp; "flag"&nbsp; &nbsp; "fmt"&nbsp; &nbsp; "io"&nbsp; &nbsp; "log"&nbsp; &nbsp; "mime/multipart"&nbsp; &nbsp; "net"&nbsp; &nbsp; "net/http"&nbsp; &nbsp; "os"&nbsp; &nbsp; "path/filepath"&nbsp; &nbsp; "sync")var (&nbsp; &nbsp; targetPath string&nbsp; &nbsp; filename&nbsp; &nbsp;string&nbsp; &nbsp; port&nbsp; &nbsp; &nbsp; &nbsp;int&nbsp; &nbsp; handlerLog *log.Logger&nbsp; &nbsp; mainLog&nbsp; &nbsp; *log.Logger)// This is automatically called after vars have been initialized and before mainfunc init() {&nbsp; &nbsp; flag.StringVar(&targetPath, "target", "./tmp", "target directory for uploads")&nbsp; &nbsp; flag.StringVar(&filename, "file", "", "file to upload")&nbsp; &nbsp; flag.IntVar(&port, "port", 0, "port to listen on. When 0, a random port is assigned")&nbsp; &nbsp; handlerLog = log.New(os.Stdout, "[handler] ", log.LstdFlags)&nbsp; &nbsp; mainLog = log.New(os.Stdout, "[main&nbsp; &nbsp;] ", log.LstdFlags)}// By returning a handler, we have an elegant way of initializing path.func uploadHandler(path string) http.Handler {&nbsp; &nbsp; // We make sure path is an existing directory when the handler takes over&nbsp; &nbsp; if s, err := os.Stat(path); err != nil {&nbsp; &nbsp; &nbsp; &nbsp; if os.IsNotExist(err) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; handlerLog.Printf("Target '%s' does not exist. Creating it...", path)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if cerr := os.MkdirAll(path, 0755); cerr != nil {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; handlerLog.Fatalf("Creating target: %s", err)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; } else {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; handlerLog.Fatalf("Error accessing '%s': %s", path, err)&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; } else if !s.IsDir() {&nbsp; &nbsp; &nbsp; &nbsp; handlerLog.Fatalf("Target '%s' is not a directory", path)&nbsp; &nbsp; }&nbsp; &nbsp; // Do NOT use this handler in production!!!&nbsp; &nbsp; // It is lacking all sorts of safety measures.&nbsp; &nbsp; // However, it is enough to demonstrate.&nbsp; &nbsp; return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {&nbsp; &nbsp; &nbsp; &nbsp; handlerLog.Println("Handling file upload...")&nbsp; &nbsp; &nbsp; &nbsp; handlerLog.Println("Parsing form...")&nbsp; &nbsp; &nbsp; &nbsp; if err := r.ParseMultipartForm(32 << 20); err != nil {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; handlerLog.Fatalf("Parsing form: %s", err)&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; f, h, err := r.FormFile("file")&nbsp; &nbsp; &nbsp; &nbsp; if err != nil {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; handlerLog.Printf("Error accessing file: %s", err)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; http.Error(w, http.StatusText(http.StatusBadRequest), http.StatusBadRequest)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; defer f.Close()&nbsp; &nbsp; &nbsp; &nbsp; handlerLog.Println("Opening output file...")&nbsp; &nbsp; &nbsp; &nbsp; t, err := os.OpenFile(filepath.Join(path, filepath.Base(h.Filename)), os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0644)&nbsp; &nbsp; &nbsp; &nbsp; if err != nil {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; handlerLog.Printf("Opening output file: %s", err)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; http.Error(w, http.StatusText(http.StatusInternalServerError)+": "+err.Error(), http.StatusInternalServerError)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; defer t.Close()&nbsp; &nbsp; &nbsp; &nbsp; handlerLog.Println("Copying to output file...")&nbsp; &nbsp; &nbsp; &nbsp; if _, err = io.Copy(t, f); err != nil {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; handlerLog.Printf("Copying to output file: %s", err)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; http.Error(w, http.StatusText(http.StatusInternalServerError)+": "+err.Error(), http.StatusInternalServerError)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; handlerLog.Println("Finished handler!")&nbsp; &nbsp; })}func main() {&nbsp; &nbsp; flag.Parse()&nbsp; &nbsp; // Check input&nbsp; &nbsp; if filename == "" {&nbsp; &nbsp; &nbsp; &nbsp; mainLog.Fatal("No filename given. Exiting...")&nbsp; &nbsp; }&nbsp; &nbsp; mainLog.Println("Setting up upload handler...")&nbsp; &nbsp; http.Handle("/upload", uploadHandler(targetPath))&nbsp; &nbsp; wg := sync.WaitGroup{}&nbsp; &nbsp; wg.Add(1)&nbsp; &nbsp; // We want to finish the program after upload, as we only want to demonstrate&nbsp; &nbsp; go func() {&nbsp; &nbsp; &nbsp; &nbsp; mainLog.Println("Setting up listener...")&nbsp; &nbsp; &nbsp; &nbsp; listener, err := net.Listen("tcp", fmt.Sprintf("127.0.0.1:%d", port))&nbsp; &nbsp; &nbsp; &nbsp; if err != nil {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; mainLog.Fatalf("%s", err)&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; defer listener.Close()&nbsp; &nbsp; &nbsp; &nbsp; port = listener.Addr().(*net.TCPAddr).Port&nbsp; &nbsp; &nbsp; &nbsp; mainLog.Printf("Listening to port %d on localhost", port)&nbsp; &nbsp; &nbsp; &nbsp; wg.Done()&nbsp; &nbsp; &nbsp; &nbsp; http.Serve(listener, nil)&nbsp; &nbsp; }()&nbsp; &nbsp; buf := bytes.NewBuffer(nil)&nbsp; &nbsp; bodyWriter := multipart.NewWriter(buf)&nbsp; &nbsp; // We need to truncate the input filename, as the server might be stupid and take the input&nbsp; &nbsp; // filename verbatim. Then, he will have directory parts which do not exist on the server.&nbsp; &nbsp; fileWriter, err := bodyWriter.CreateFormFile("file", filepath.Base(filename))&nbsp; &nbsp; if err != nil {&nbsp; &nbsp; &nbsp; &nbsp; mainLog.Fatalf("Creating fileWriter: %s", err)&nbsp; &nbsp; }&nbsp; &nbsp; file, err := os.Open(filename)&nbsp; &nbsp; if err != nil {&nbsp; &nbsp; &nbsp; &nbsp; mainLog.Fatalf("Opening file: %s", err)&nbsp; &nbsp; }&nbsp; &nbsp; defer file.Close()&nbsp; &nbsp; if _, err := io.Copy(fileWriter, file); err != nil {&nbsp; &nbsp; &nbsp; &nbsp; mainLog.Fatalf("Buffering file: %s", err)&nbsp; &nbsp; }&nbsp; &nbsp; // We have all the data written to the bodyWriter.&nbsp; &nbsp; // Now we can infer the content type&nbsp; &nbsp; contentType := bodyWriter.FormDataContentType()&nbsp; &nbsp; // This is mandatory as it flushes the buffer.&nbsp; &nbsp; bodyWriter.Close()&nbsp; &nbsp; // As we wait for the server to spin up, we need to wait here.&nbsp; &nbsp; mainLog.Println("Waiting for the listener to be set up...")&nbsp; &nbsp; wg.Wait()&nbsp; &nbsp; req, err := http.NewRequest(http.MethodPut, fmt.Sprintf("http://127.0.0.1:%d/upload", port), buf)&nbsp; &nbsp; if err != nil {&nbsp; &nbsp; &nbsp; &nbsp; mainLog.Fatalf("Creating request: %s", err)&nbsp; &nbsp; }&nbsp; &nbsp; req.Header.Set("Content-Type", contentType)&nbsp; &nbsp; client := http.Client{}&nbsp; &nbsp; mainLog.Println("Sending file")&nbsp; &nbsp; res, err := client.Do(req)&nbsp; &nbsp; if err != nil {&nbsp; &nbsp; &nbsp; &nbsp; mainLog.Fatalf("Sending file: %s", err)&nbsp; &nbsp; }&nbsp; &nbsp; mainLog.Printf("Received %s from server. Exiting...", res.Status)}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go