Skip to content

Instantly share code, notes, and snippets.

@Komosa
Created October 13, 2015 21:44
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 Komosa/c1003c3b7faea392c2e3 to your computer and use it in GitHub Desktop.
Save Komosa/c1003c3b7faea392c2e3 to your computer and use it in GitHub Desktop.
Simple file receiver
package main
import (
"io"
"log"
"net/http"
"os"
)
func main() {
err := http.ListenAndServe(":12345", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Method == "GET" {
showForm(w, "")
} else {
acceptFile(w, r)
}
}))
if err != nil {
log.Fatal("ListenAndServe: ", err)
}
}
func acceptFile(w http.ResponseWriter, r *http.Request) {
defer r.Body.Close()
fi, _, err := r.FormFile("file")
if err != nil {
http.Error(w, "FormFile: "+err.Error(), 500)
return
}
fn := "plik.data"
if fv := r.FormValue("name"); fv != "" {
fn = fv
}
fo, err := os.Create(fn)
if err != nil {
http.Error(w, "os.Create: "+err.Error(), 500)
return
}
defer fo.Close()
_, err = io.Copy(fo, fi)
if err != nil {
http.Error(w, "io.Copy: "+err.Error(), 500)
return
}
showForm(w, "Ok!")
}
func showForm(w io.Writer, bonus string) {
io.WriteString(w, "<html><head><title>Zapodaj plika!</title></head>"+
"<body><h1>"+bonus+"</h1>"+
"<form method='POST' enctype='multipart/form-data' action='#'>"+
"Nazwa pliku:<input type=text name=name><br/>"+
"<input type=file name=file><br/>"+
"<input type=submit name=Uhuu!>"+
"</form></body></html>")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment