Last active
April 14, 2025 12:54
-
Star
(105)
You must be signed in to star a gist -
Fork
(20)
You must be signed in to fork a gist
-
-
Save andrewmilson/19185aab2347f6ad29f5 to your computer and use it in GitHub Desktop.
Golang multipart/form-data File Upload
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"net/http" | |
"os" | |
"bytes" | |
"path" | |
"path/filepath" | |
"mime/multipart" | |
"io" | |
) | |
func main() { | |
fileDir, _ := os.Getwd() | |
fileName := "upload-file.txt" | |
filePath := path.Join(fileDir, fileName) | |
file, _ := os.Open(filePath) | |
defer file.Close() | |
body := &bytes.Buffer{} | |
writer := multipart.NewWriter(body) | |
part, _ := writer.CreateFormFile("file", filepath.Base(file.Name())) | |
io.Copy(part, file) | |
writer.Close() | |
r, _ := http.NewRequest("POST", "http://example.com", body) | |
r.Header.Add("Content-Type", writer.FormDataContentType()) | |
client := &http.Client{} | |
client.Do(r) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
No It doesn't.
If you want to achieve zero copy, you can use os.pipe instead of sendfile.
sendfile is fit to tcp package so, it is hard to use with http package.
See this code snippet and benchmarks of it.