2 uploader -- simplest form file uploader
3 Copyright (C) 2018 Sergey Matveev <stargrave@stargrave.org>
19 "golang.org/x/crypto/blake2s"
20 "golang.org/x/net/netutil"
24 WriteBufSize = 1 << 20
27 func upload(w http.ResponseWriter, r *http.Request) {
28 if r.Method == http.MethodGet {
29 w.Write([]byte(`<html>
30 <head><title>Upload</title></head><body>
31 <form enctype="multipart/form-data" action="/upload/" method="post">
32 <input type="file" name="fileupload" /><input type="submit" />
33 </form></body></html>`))
36 mr, err := r.MultipartReader()
41 p, err := mr.NextPart()
46 if p.FormName() != "fileupload" {
47 fmt.Println("non file form field")
51 fd, err := os.OpenFile(now.Format(time.RFC3339Nano), os.O_WRONLY|os.O_CREATE, 0600)
57 h, err := blake2s.New256(nil)
61 fdBuf := bufio.NewWriterSize(fd, WriteBufSize)
62 mw := io.MultiWriter(fdBuf, h)
63 n, err := io.Copy(mw, p)
68 if err = fdBuf.Flush(); err != nil {
72 fmt.Fprintf(w, "bytes: %d\nBLAKE2s: %s\n", n, hex.EncodeToString(h.Sum(nil)))
76 bind := flag.String("bind", "[::]:8086", "Address to bind to")
77 conns := flag.Int("conns", 2, "Maximal number of connections")
79 ln, err := net.Listen("tcp", *bind)
83 fmt.Println("listening on", *bind)
84 ln = netutil.LimitListener(ln, *conns)
86 ReadHeaderTimeout: 10 * time.Second,
87 MaxHeaderBytes: 10 * (1 << 10),
89 http.HandleFunc("/upload/", upload)