Skip to content

Instantly share code, notes, and snippets.

@yang-wei
Created August 4, 2018 04:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yang-wei/d3afcf3aca36b5fd05addb2ca3d77fdb to your computer and use it in GitHub Desktop.
Save yang-wei/d3afcf3aca36b5fd05addb2ca3d77fdb to your computer and use it in GitHub Desktop.
go upload
go run server.go

curl

curl -v -H 'Content-Type: multipart/form-data' -F "uploadfile=@./sample_video.mp4" -k http://localhost:8080/upload
package main
import (
"encoding/json"
"fmt"
"io"
"net/http"
"os"
"time"
)
type fileData struct {
File string `json:"file"`
}
func main() {
http.HandleFunc("/", hello)
http.HandleFunc("/upload", handleUpload)
http.ListenAndServe(":8080", nil)
}
func hello(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("hello!"))
}
func handleUpload(w http.ResponseWriter, r *http.Request) {
const maxUploadSize = 2 * 1024 * 1024 // 2MB
fmt.Printf("maxUploadSize: %v, headerContentLength: %v", maxUploadSize, r.Header.Get("Content-Length"))
r.Body = http.MaxBytesReader(w, r.Body, maxUploadSize)
if err := r.ParseMultipartForm(maxUploadSize); err != nil {
panic(err)
}
file, handler, err := r.FormFile("uploadfile")
if err != nil {
panic(err)
}
defer file.Close()
filepath := "./" + time.Now().Format("20060102_150405") + "_" + handler.Filename
f, err := os.OpenFile(filepath, os.O_WRONLY|os.O_CREATE, 0666)
if err != nil {
panic(err)
}
defer f.Close()
io.Copy(f, file)
w.Header().Set("Content-Type", "application/json; charset=utf-8")
json.NewEncoder(w).Encode(fileData{filepath})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment