{"id":208322,"date":"2025-07-08T17:38:20","date_gmt":"2025-07-08T09:38:20","guid":{"rendered":"https:\/\/server.hk\/cnblog\/208322\/"},"modified":"2025-07-08T17:38:20","modified_gmt":"2025-07-08T09:38:20","slug":"http-put-%e8%af%b7%e6%b1%82%e5%9c%a8-golang-%e4%b8%ad%e4%b8%8a%e4%bc%a0-zip-%e6%96%87%e4%bb%b6","status":"publish","type":"post","link":"https:\/\/server.hk\/cnblog\/208322\/","title":{"rendered":"http PUT \u8bf7\u6c42\u5728 golang \u4e2d\u4e0a\u4f20 zip \u6587\u4ef6"},"content":{"rendered":"<p><b><\/b> <\/p>\n<p>\u5f53\u524d\u4f4d\u7f6e\uff1a <span>&gt;<\/span> <span>&gt;<\/span> <span>&gt;<\/span> <span>&gt;<\/span> <span>http PUT \u8bf7\u6c42\u5728 golang \u4e2d\u4e0a\u4f20 zip \u6587\u4ef6<\/span><\/p>\n<p><span>\u6765\u6e90\uff1astackoverflow<\/span><br \/>\n<span>2024-05-01 18:57:33<\/span><br \/>\n<span><i><\/i>0\u6d4f\u89c8<\/span><br \/>\n<span style=\"cursor: pointer\"><i><\/i>\u6536\u85cf<\/span> <\/p>\n<p>\u672c\u7bc7\u6587\u7ae0\u7ed9\u5927\u5bb6\u5206\u4eab\u300ahttp PUT \u8bf7\u6c42\u5728 golang \u4e2d\u4e0a\u4f20 zip \u6587\u4ef6\u300b\uff0c\u8986\u76d6\u4e86Golang\u7684\u5e38\u89c1\u57fa\u7840\u77e5\u8bc6\uff0c\u5176\u5b9e\u4e00\u4e2a\u8bed\u8a00\u7684\u5168\u90e8\u77e5\u8bc6\u70b9\u4e00\u7bc7\u6587\u7ae0\u662f\u4e0d\u53ef\u80fd\u8bf4\u5b8c\u7684\uff0c\u4f46\u5e0c\u671b\u901a\u8fc7\u8fd9\u4e9b\u95ee\u9898\uff0c\u8ba9\u8bfb\u8005\u5bf9\u81ea\u5df1\u7684\u638c\u63e1\u7a0b\u5ea6\u6709\u4e00\u5b9a\u7684\u8ba4\u8bc6(B \u6570)\uff0c\u4ece\u800c\u5f25\u8865\u81ea\u5df1\u7684\u4e0d\u8db3\uff0c\u66f4\u597d\u7684\u638c\u63e1\u5b83\u3002<\/p>\n<p> \u95ee\u9898\u5185\u5bb9<br \/>\n <\/p>\n<p>\u6211\u7684\u5ba2\u6237\u7aef\u4ee3\u7801\u57fa\u672c\u4e0a\u662f\u5c1d\u8bd5\u4f7f\u7528 http put \u65b9\u6cd5\u5c06 tar.gz \u6587\u4ef6\u4e0a\u4f20\u5230\u670d\u52a1\u5668\u3002\u7136\u800c\u670d\u52a1\u5668\u4f3c\u4e4e\u4e0d\u559c\u6b22\u5b83\u5e76\u4e14\u603b\u662f\u5411\u6211\u53d1\u9001 500 error \u54cd\u5e94\u3002\u4ee5\u4e0b\u662f\u4ee3\u7801\u3002\u6211\u4e0d\u786e\u5b9a\u51fa\u4e86\u4ec0\u4e48\u95ee\u9898\u3002<\/p>\n<pre>func upLoadFileToServer (uploadFileName string) {\n    tr := &amp;http.Transport{\n          TLSClientConfig: &amp;tls.Config{InsecureSkipVerify: true},\n          ExpectContinueTimeout : 30 * time.Second,\n        }\n\n    client := &amp;http.Client{ Transport:tr,\n                          Timeout: 20 * time.Second}\n\n    timeCurrent = time.Now()\n    fileContents, err := ioutil.ReadFile(uploadFileName)\n    if err != nil {\n     log.Println(\"Failed to Read the File\", uploadFileName, err)\n    }\n\n    PutReq, _ := http.NewRequest(\"PUT\", \"https:\/\/www.example.com\/upload\", strings.NewReader(string(fileContents)))\n\n    PutReq.Header.Set(\"Content-Type\", \"application\/zip\")\n    PutReq.ContentLength = int64(len(string(fileContents)))\n\n\n    PutReq.Header.Set(\"Expect\", \"100-continue\")\n    PutReq.Header.Set(\"Accept\", \"*\/*\")\n    PutReq.Header.Set(\"Date\", timeCurrent.Format(time.RFC1123))\n    PutResp, err := client.Do(inventoryPutReq)\n    }<\/pre>\n<p>\u6709\u65f6\u6211\u4f1a\u6ce8\u610f\u5230\u201cconnection reset by peer\u201d\u9519\u8bef\u3002\u4f46\u5927\u591a\u6570\u65f6\u5019\u5b83\u662f 500\u3002\u6211\u4f7f\u7528 postman \u5c1d\u8bd5\u5b8c\u5168\u76f8\u540c\u7684\u8bf7\u6c42\uff0c\u5b83\u4f3c\u4e4e\u5de5\u4f5c\u6b63\u5e38\u3002 <\/p>\n<p> <\/p>\n<h2>\u89e3\u51b3\u65b9\u6848<\/h2>\n<p> <\/p>\n<p>\u8fd9\u662f\u4e00\u4e2a\u5de5\u4f5c\u793a\u4f8b\u3002<\/p>\n<p>\u6700\u6709\u53ef\u80fd\u7684\u60c5\u51b5\u662f\uff0c\u670d\u52a1\u5668\u6709\u70b9\u7b80\u5355\uff0c\u5e76\u4e14\u6309\u5b57\u9762\u610f\u601d\u83b7\u53d6\u6587\u4ef6\u540d\u3002\u7531\u4e8e\u60a8\u6ca1\u6709\u5728 <code>uploadfilename<\/code> \u4e0a\u4f7f\u7528 <code>filepath.base<\/code>\uff0c\u56e0\u6b64\u5b83\u53ef\u80fd\u5305\u542b\u8def\u5f84\u5143\u7d20\u3002\u53ea\u9700\u5728\u60a8\u7684\u6587\u4ef6\u540d\u4e0a\u4f7f\u7528\u5b83\u5373\u53ef\u8fdb\u884c\u6d4b\u8bd5\u3002<\/p>\n<p>\u91cd\u7f6e\u53ef\u80fd\u662f\u7531\u4e8e\u8d85\u65f6\u9020\u6210\u7684\u3002<\/p>\n<pre>package main\n\nimport (\n    \"bytes\"\n    \"flag\"\n    \"fmt\"\n    \"io\"\n    \"log\"\n    \"mime\/multipart\"\n    \"net\"\n    \"net\/http\"\n    \"os\"\n    \"path\/filepath\"\n    \"sync\"\n)\n\nvar (\n    targetPath string\n    filename   string\n    port       int\n    handlerLog *log.Logger\n    mainLog    *log.Logger\n)\n\n\/\/ This is automatically called after vars have been initialized and before main\nfunc init() {\n    flag.StringVar(&amp;targetPath, \"target\", \".\/tmp\", \"target directory for uploads\")\n    flag.StringVar(&amp;filename, \"file\", \"\", \"file to upload\")\n    flag.IntVar(&amp;port, \"port\", 0, \"port to listen on. When 0, a random port is assigned\")\n    handlerLog = log.New(os.Stdout, \"[handler] \", log.LstdFlags)\n    mainLog = log.New(os.Stdout, \"[main   ] \", log.LstdFlags)\n}\n\n\/\/ By returning a handler, we have an elegant way of initializing path.\nfunc uploadHandler(path string) http.Handler {\n\n    \/\/ We make sure path is an existing directory when the handler takes over\n    if s, err := os.Stat(path); err != nil {\n        if os.IsNotExist(err) {\n            handlerLog.Printf(\"Target '%s' does not exist. Creating it...\", path)\n            if cerr := os.MkdirAll(path, 0755); cerr != nil {\n                handlerLog.Fatalf(\"Creating target: %s\", err)\n            }\n        } else {\n            handlerLog.Fatalf(\"Error accessing '%s': %s\", path, err)\n        }\n    } else if !s.IsDir() {\n        handlerLog.Fatalf(\"Target '%s' is not a directory\", path)\n    }\n\n    \/\/ Do NOT use this handler in production!!!\n    \/\/ It is lacking all sorts of safety measures.\n    \/\/ However, it is enough to demonstrate.\n    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n        handlerLog.Println(\"Handling file upload...\")\n\n        handlerLog.Println(\"Parsing form...\")\n        if err := r.ParseMultipartForm(32 &lt;&lt; 20); err != nil {\n            handlerLog.Fatalf(\"Parsing form: %s\", err)\n        }\n        f, h, err := r.FormFile(\"file\")\n        if err != nil {\n            handlerLog.Printf(\"Error accessing file: %s\", err)\n            http.Error(w, http.StatusText(http.StatusBadRequest), http.StatusBadRequest)\n            return\n        }\n        defer f.Close()\n\n        handlerLog.Println(\"Opening output file...\")\n        t, err := os.OpenFile(filepath.Join(path, filepath.Base(h.Filename)), os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0644)\n        if err != nil {\n            handlerLog.Printf(\"Opening output file: %s\", err)\n            http.Error(w, http.StatusText(http.StatusInternalServerError)+\": \"+err.Error(), http.StatusInternalServerError)\n            return\n        }\n        defer t.Close()\n\n        handlerLog.Println(\"Copying to output file...\")\n        if _, err = io.Copy(t, f); err != nil {\n            handlerLog.Printf(\"Copying to output file: %s\", err)\n\n            http.Error(w, http.StatusText(http.StatusInternalServerError)+\": \"+err.Error(), http.StatusInternalServerError)\n            return\n        }\n        handlerLog.Println(\"Finished handler!\")\n    })\n}\n\nfunc main() {\n    flag.Parse()\n\n    \/\/ Check input\n    if filename == \"\" {\n        mainLog.Fatal(\"No filename given. Exiting...\")\n    }\n\n    mainLog.Println(\"Setting up upload handler...\")\n    http.Handle(\"\/upload\", uploadHandler(targetPath))\n\n    wg := sync.WaitGroup{}\n    wg.Add(1)\n\n    \/\/ We want to finish the program after upload, as we only want to demonstrate\n    go func() {\n        mainLog.Println(\"Setting up listener...\")\n\n        listener, err := net.Listen(\"tcp\", fmt.Sprintf(\"127.0.0.1:%d\", port))\n        if err != nil {\n            mainLog.Fatalf(\"%s\", err)\n        }\n        defer listener.Close()\n\n        port = listener.Addr().(*net.TCPAddr).Port\n        mainLog.Printf(\"Listening to port %d on localhost\", port)\n\n        wg.Done()\n        http.Serve(listener, nil)\n    }()\n\n    buf := bytes.NewBuffer(nil)\n    bodyWriter := multipart.NewWriter(buf)\n\n    \/\/ We need to truncate the input filename, as the server might be stupid and take the input\n    \/\/ filename verbatim. Then, he will have directory parts which do not exist on the server.\n    fileWriter, err := bodyWriter.CreateFormFile(\"file\", filepath.Base(filename))\n    if err != nil {\n        mainLog.Fatalf(\"Creating fileWriter: %s\", err)\n    }\n\n    file, err := os.Open(filename)\n    if err != nil {\n        mainLog.Fatalf(\"Opening file: %s\", err)\n    }\n    defer file.Close()\n\n    if _, err := io.Copy(fileWriter, file); err != nil {\n        mainLog.Fatalf(\"Buffering file: %s\", err)\n    }\n\n    \/\/ We have all the data written to the bodyWriter.\n    \/\/ Now we can infer the content type\n    contentType := bodyWriter.FormDataContentType()\n\n    \/\/ This is mandatory as it flushes the buffer.\n    bodyWriter.Close()\n\n    \/\/ As we wait for the server to spin up, we need to wait here.\n    mainLog.Println(\"Waiting for the listener to be set up...\")\n    wg.Wait()\n\n    req, err := http.NewRequest(http.MethodPut, fmt.Sprintf(\"http:\/\/127.0.0.1:%d\/upload\", port), buf)\n    if err != nil {\n        mainLog.Fatalf(\"Creating request: %s\", err)\n    }\n    req.Header.Set(\"Content-Type\", contentType)\n\n    client := http.Client{}\n\n    mainLog.Println(\"Sending file\")\n    res, err := client.Do(req)\n    if err != nil {\n        mainLog.Fatalf(\"Sending file: %s\", err)\n    }\n\n    mainLog.Printf(\"Received %s from server. Exiting...\", res.Status)\n}<\/pre>\n<p>\u4ee5\u4e0a\u5c31\u662f\u300ahttp PUT \u8bf7\u6c42\u5728 golang \u4e2d\u4e0a\u4f20 zip \u6587\u4ef6\u300b\u7684\u8be6\u7ec6\u5185\u5bb9\uff0c\u66f4\u591a\u5173\u4e8e\u7684\u8d44\u6599\u8bf7\u5173\u6ce8\u516c\u4f17\u53f7\uff01<\/p>\n","protected":false},"excerpt":{"rendered":"<p>\u5f53\u524d\u4f4d\u7f6e\uff1a &gt; &gt; &#46;&#46;&#46;<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"closed","ping_status":"","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[4925],"tags":[],"class_list":["post-208322","post","type-post","status-publish","format-standard","hentry","category-4925"],"_links":{"self":[{"href":"https:\/\/server.hk\/cnblog\/wp-json\/wp\/v2\/posts\/208322","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/server.hk\/cnblog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/server.hk\/cnblog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/server.hk\/cnblog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/server.hk\/cnblog\/wp-json\/wp\/v2\/comments?post=208322"}],"version-history":[{"count":0,"href":"https:\/\/server.hk\/cnblog\/wp-json\/wp\/v2\/posts\/208322\/revisions"}],"wp:attachment":[{"href":"https:\/\/server.hk\/cnblog\/wp-json\/wp\/v2\/media?parent=208322"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/server.hk\/cnblog\/wp-json\/wp\/v2\/categories?post=208322"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/server.hk\/cnblog\/wp-json\/wp\/v2\/tags?post=208322"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}