summaryrefslogtreecommitdiff
path: root/upload.go
diff options
context:
space:
mode:
authorhorus_arch2015-05-12 20:57:04 +0200
committerhorus_arch2015-05-12 20:57:04 +0200
commit2e8e63e4a719a2b3adeeed2f1f54a8f3388ac2e4 (patch)
tree2ca8ba44cab2a662cccee50f0a8a616dde119027 /upload.go
parent5986015358e5b7cf523122bbdb6831dccf7ca306 (diff)
downloaduhttpd-2e8e63e4a719a2b3adeeed2f1f54a8f3388ac2e4.tar.gz
Add upload form.
Diffstat (limited to 'upload.go')
-rw-r--r--upload.go110
1 files changed, 110 insertions, 0 deletions
diff --git a/upload.go b/upload.go
new file mode 100644
index 0000000..6e0ce56
--- /dev/null
+++ b/upload.go
@@ -0,0 +1,110 @@
+package main
+
+import (
+ "html/template"
+ "io"
+ "log"
+ "net/http"
+ "os"
+ "strings"
+)
+
+func uploadHandler(dir string, quiet bool) http.Handler {
+ fn := func(w http.ResponseWriter, r *http.Request) {
+
+ // uhttpd strong
+ w.Header().Set("Server", "uhttpd")
+
+ // we are handling the upload
+ if r.Method == "POST" {
+
+ // we need the input file named "file"
+ file, header, err := r.FormFile("file")
+ if err != nil {
+ w.WriteHeader(500)
+ w.Write([]byte(err.Error()))
+ log.Println("ERROR", err.Error())
+ return
+ }
+
+ defer file.Close()
+
+ if !strings.HasSuffix(dir, "/") {
+ dir = dir + "/"
+ }
+
+ // lets create the desired file
+ out, err := os.Create(dir + header.Filename)
+ if err != nil {
+ w.WriteHeader(500)
+ w.Write([]byte(err.Error()))
+ log.Println("ERROR", err.Error())
+ return
+ }
+
+ defer out.Close()
+
+ // copy the old file in the created one
+ _, err = io.Copy(out, file)
+ if err != nil {
+ w.WriteHeader(500)
+ w.Write([]byte(err.Error()))
+ log.Println("ERROR", err.Error())
+ return
+ }
+
+ // do not log upload
+ if !quiet {
+ log.Println(r.Method, r.URL.Path, header.Filename, r.RemoteAddr)
+ }
+
+ // print for cli client
+ if r.URL.Query().Get("html") != "1" {
+ w.Write([]byte("Uploaded: " + header.Filename))
+ return
+ }
+
+ // print for browser
+ w.Header().Set("Content-Type", "text/html")
+ tmpl := template.New("uploaded")
+ tmpl, err = tmpl.Parse(getUploaded())
+ if err != nil {
+ log.Println(err.Error())
+ w.WriteHeader(500)
+ w.Write([]byte(err.Error()))
+ return
+ }
+
+ err = tmpl.Execute(w, struct{ File string }{File: header.Filename})
+ if err != nil {
+ log.Println(err.Error())
+ w.WriteHeader(500)
+ w.Write([]byte(err.Error()))
+ return
+ }
+ return
+ } else {
+ // we are just printing the upload form
+
+ w.Header().Set("Content-Type", "text/html")
+ tmpl := template.New("upload")
+ tmpl, err := tmpl.Parse(getUpload())
+ if err != nil {
+ log.Println(err.Error())
+ w.WriteHeader(500)
+ w.Write([]byte(err.Error()))
+ return
+ }
+
+ err = tmpl.Execute(w, nil)
+ if err != nil {
+ log.Println(err.Error())
+ w.WriteHeader(500)
+ w.Write([]byte(err.Error()))
+ return
+ }
+ return
+ }
+ }
+ return http.HandlerFunc(fn)
+}