Skip to content

Instantly share code, notes, and snippets.

@artyom
Created October 17, 2018 17:37
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 artyom/584320a174c0c2bfd814269d6d6112de to your computer and use it in GitHub Desktop.
Save artyom/584320a174c0c2bfd814269d6d6112de to your computer and use it in GitHub Desktop.
upload form to see how browser posts files to a form
// TODO describe program
package main
import (
"fmt"
"io"
"io/ioutil"
"net/http"
"os"
"strings"
)
func main() {
if err := run(); err != nil {
os.Stderr.WriteString(err.Error() + "\n")
os.Exit(1)
}
}
func run() error {
return http.ListenAndServe("localhost:8080", http.HandlerFunc(handler))
}
func handler(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
w.Write([]byte(page))
return
}
file, header, err := r.FormFile("file")
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
fmt.Fprintf(w, "request headers:\n\n")
for k, v := range r.Header {
fmt.Fprintf(w, "%s: %s\n", k, strings.Join(v, ", "))
}
fmt.Fprintln(w, "\nfile header:")
fmt.Fprintf(w, "\tFilename: %q\n\tHeader: %v\n\tSize: %d\n",
header.Filename, header.Header, header.Size)
n, err := io.Copy(ioutil.Discard, file)
fmt.Fprintf(w, "\nfile read: %d bytes, error: %v\n", n, err)
}
const page = `<!doctype html>
<head><title>submit form</title><meta charset=utf-8>
<style>body{font-size:x-large;margin:2em auto;max-width:50%}</style>
<body>
<form method=post enctype=multipart/form-data>
<input id=file type=file name=file>
<input type=submit></form>
`
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment