Skip to content

Instantly share code, notes, and snippets.

@benthor
Last active August 29, 2015 14:12
Show Gist options
  • Save benthor/94e9eaad3c6d2850ab34 to your computer and use it in GitHub Desktop.
Save benthor/94e9eaad3c6d2850ab34 to your computer and use it in GitHub Desktop.
package main
import (
"fmt"
"io"
"log"
"net/http"
"os"
"path/filepath"
"strings"
"time"
)
func main() {
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
res := []string{}
if r.Method == "POST" {
reader, err := r.MultipartReader()
if err != nil {
log.Println(err)
res = append(res, err.Error())
} else {
for {
p, err := reader.NextPart()
if err != nil {
if err == io.EOF {
res = append(res, "all done")
break
} else {
log.Println(err)
res = append(res, err.Error())
continue
}
}
fname := p.FileName()
if fname == "" {
fname = time.Now().String()
log.Printf("no filename found, using %s", fname)
}
f, err := os.Create(filepath.Join("uploads", fname))
if err != nil {
res = append(res, err.Error())
log.Println(err)
}
log.Printf("receiving %s", fname)
io.Copy(f, p)
res = append(res, fmt.Sprintf("OK, created %s", fname))
log.Printf("upload of %s done", fname)
}
}
}
message := ""
if len(res) > 0 {
message += "<ul><li>" + strings.Join(res, "</li><li>") + "</li><ul>"
}
fmt.Fprintf(w, `
<html>
<head></head>
<body>
%s
<form name="upload" method="POST" action="/" enctype="multipart/form-data">
<input type="file" name="fileupload" multiple/>
<input type="submit" value="Go" />
</form>
</body>
</html>
`, message)
})
log.Fatal(http.ListenAndServe(":8000", nil))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment