Created
October 13, 2015 21:44
-
-
Save Komosa/c1003c3b7faea392c2e3 to your computer and use it in GitHub Desktop.
Simple file receiver
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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