Skip to content

Instantly share code, notes, and snippets.

@ckeyer
Created August 9, 2015 08:54
Show Gist options
  • Save ckeyer/f2a672dccf24cd46c46b to your computer and use it in GitHub Desktop.
Save ckeyer/f2a672dccf24cd46c46b to your computer and use it in GitHub Desktop.
Upload File by http for go
func Upload() (err error) {
// Create buffer
buf := new(bytes.Buffer) // caveat IMO dont use this for large files, \
// create a tmpfile and assemble your multipart from there (not tested)
w := multipart.NewWriter(buf)
// Create file field
fw, err := w.CreateFormFile("file", "nginx.txt") //这里的file很重要,必须和服务器端的FormFile一致
if err != nil {
fmt.Println("c")
return err
}
fd, err := os.Open("G:\\code\\go\\src\\github.com\\lab204\\mmDeploy\\file_server\\nginx.conf")
if err != nil {
fmt.Println("d")
return err
}
defer fd.Close()
// Write file field from file to upload
_, err = io.Copy(fw, fd)
if err != nil {
fmt.Println("e")
return err
}
// Important if you do not close the multipart writer you will not have a
// terminating boundry
w.Close()
req, err := http.NewRequest("POST", "http://localhost/upload.txt?force=true", buf)
if err != nil {
fmt.Println("f")
return err
}
req.Header.Set("Content-Type", w.FormDataContentType())
var client http.Client
res, err := client.Do(req)
if err != nil {
fmt.Println("g")
return err
}
io.Copy(os.Stderr, res.Body) // Replace this with Status.Code check
fmt.Println("h")
return err
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment