Skip to content

Instantly share code, notes, and snippets.

@mpfund
Created February 29, 2016 07:39
Show Gist options
  • Save mpfund/db6c376d49bd08f51493 to your computer and use it in GitHub Desktop.
Save mpfund/db6c376d49bd08f51493 to your computer and use it in GitHub Desktop.
golang file upload
package main
import (
"bytes"
"fmt"
"io/ioutil"
"mime/multipart"
"net/http"
)
func main() {
var guidEmpty = "00000000-0000-0000-0000-000000000000"
uri := "http://localhost:8080/file/" + guidEmpty
pars := map[string]string{
"meta": "test",
}
req, _ := newfileUploadRequest(uri, pars, "upload", "mmm.txt", []byte("mmmm"))
client := http.Client{}
resp, _ := client.Do(req)
raw, _ := ioutil.ReadAll(resp.Body)
fmt.Println(string(raw))
}
func newfileUploadRequest(uri string, params map[string]string, paramName string, fName string,
fileContents []byte) (*http.Request, error) {
body := new(bytes.Buffer)
writer := multipart.NewWriter(body)
part, err := writer.CreateFormFile(paramName, fName)
if err != nil {
return nil, err
}
part.Write(fileContents)
for key, val := range params {
_ = writer.WriteField(key, val)
}
err = writer.Close()
if err != nil {
return nil, err
}
req, _ := http.NewRequest("POST", uri, body)
req.Header.Set("Content-Type", writer.FormDataContentType())
return req, err
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment