From c2af049b8af811a546bfa6b11f362c9c1e706343 Mon Sep 17 00:00:00 2001 From: Marten Seemann Date: Sat, 20 Aug 2016 22:20:43 +0700 Subject: [PATCH] add an upload handler to the demo server --- example/main.go | 40 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 40 insertions(+) diff --git a/example/main.go b/example/main.go index e4d70f8e..81263f97 100644 --- a/example/main.go +++ b/example/main.go @@ -1,12 +1,15 @@ package main import ( + "crypto/md5" "crypto/tls" + "errors" "flag" "fmt" "io" "io/ioutil" "log" + "mime/multipart" "net/http" "strings" "sync" @@ -29,6 +32,11 @@ func (b *binds) Set(v string) error { return nil } +// Size is needed by the /demo/upload handler to determine the size of the uploaded file +type Size interface { + Size() int64 +} + func init() { http.HandleFunc("/demo/tile", func(w http.ResponseWriter, r *http.Request) { // Small 40x40 png @@ -58,6 +66,38 @@ func init() { } w.Write(body) }) + + // accept file uploads and return the MD5 of the uploaded file + // maximum accepted file size is 1 GB + http.HandleFunc("/demo/upload", func(w http.ResponseWriter, r *http.Request) { + if r.Method == http.MethodPost { + var err error + err = r.ParseMultipartForm(1 << 30) // 1 GB + if err == nil { + var file multipart.File + file, _, err = r.FormFile("uploadfile") + if err == nil { + var size int64 + if sizeInterface, ok := file.(Size); ok { + size = sizeInterface.Size() + b := make([]byte, size) + file.Read(b) + md5 := md5.Sum(b) + fmt.Fprintf(w, "%x", md5) + return + } + err = errors.New("Couldn't get uploaded file size.") + } + } + if err != nil { + utils.Infof("Error receiving upload: %#v", err) + } + } + io.WriteString(w, `
+
+ +
`) + }) } func main() {