1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
|
package main
import (
"flag"
"fmt"
"io"
"log"
"net/http"
"os"
"strings"
)
func accessLog(h http.Handler) http.Handler {
t := &TemplateHandler{handler: h}
//t := &TemplateHandler{}
fn := func(w http.ResponseWriter, r *http.Request) {
log.Println(r.Method, r.URL.Path, r.RemoteAddr)
t.ServeHTTP(w, r)
}
return http.HandlerFunc(fn)
}
/*
func TemplateHandler(h http.Handler) http.Handler {
h.handler
}
*/
func uploadHandler(dir string) http.Handler {
fn := func(w http.ResponseWriter, r *http.Request) {
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 + "/"
}
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()
_, err = io.Copy(out, file)
if err != nil {
w.WriteHeader(500)
w.Write([]byte(err.Error()))
log.Println("ERROR", err.Error())
return
}
log.Println(r.Method, r.URL.Path, header.Filename, r.RemoteAddr)
w.Write([]byte("Uploaded " + header.Filename))
}
return http.HandlerFunc(fn)
}
func main() {
ip_f := flag.String("ip", "0.0.0.0", "IP adress to listen on.")
port_f := flag.String("port", "3000", "Port to listen on.")
dir_f := flag.String("dir", ".", "Directory to serve.")
disallow_upl_f := flag.Bool("disallow-upload", false, "Disallow uploads to /upload.")
upl_dir_f := flag.String("upload-dir", ".", "Directory to store uploaded files.")
flag.Parse()
port := os.Getenv("PORT")
if port == "" {
port = *port_f
}
fmt.Println("Starting uhttpd serving \"" + *dir_f + "\" on " + *ip_f + ":" + port + ".")
mux := http.NewServeMux()
if !*disallow_upl_f {
os.MkdirAll(*upl_dir_f, 0755)
mux.Handle("/upload", uploadHandler(*upl_dir_f))
}
mux.Handle("/", accessLog(http.FileServer(http.Dir(*dir_f))))
log.Fatal(http.ListenAndServe(*ip_f+":"+port, mux))
}
|