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
|
package main
import (
"flag"
"fmt"
"log"
"net"
"net/http"
"os"
)
func accessLog(h http.Handler, quiet bool) http.Handler {
t := &TemplateHandler{handler: h}
fn := func(w http.ResponseWriter, r *http.Request) {
if !quiet {
log.Println(r.Method, r.URL.Path, r.RemoteAddr)
}
t.ServeHTTP(w, r)
}
return http.HandlerFunc(fn)
}
var _allow_upload bool // todo: inject as dependency
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.")
quiet_f := flag.Bool("quiet", false, "Be quiet, suppress output.")
flag.Parse()
port := os.Getenv("PORT")
if port == "" {
port = *port_f
}
if !*quiet_f {
fmt.Print("You started µhttpd listening on " + *ip_f + ":" + port + " serving \"" + *dir_f + "\" as content.")
if !*disallow_upl_f {
fmt.Println(" Upload is enabled and accessible under /upload.")
} else {
fmt.Println(" Upload is disabled.")
}
fmt.Print("To view open your browser and try to open this as a url: ")
if *ip_f == "0.0.0.0" {
addrs, err := net.InterfaceAddrs()
if err != nil {
log.Fatal(err)
return
}
for cnt, adr := range addrs {
if ipnet, ok := adr.(*net.IPNet); ok && !ipnet.IP.IsLoopback() {
if ipnet.IP.To4() != nil {
if cnt > 1 {
fmt.Printf(" or http://%s:%s/", ipnet.IP.String(), port)
} else {
fmt.Printf("http://%s:%s/", ipnet.IP.String(), port)
}
}
}
}
} else {
fmt.Print("http://" + *ip_f + ":" + port + "/")
}
fmt.Print("\n\n")
}
mux := http.NewServeMux()
if !*disallow_upl_f {
os.MkdirAll(*upl_dir_f, 0755)
mux.Handle("/upload", uploadHandler(*upl_dir_f, *quiet_f))
_allow_upload = true
}
mux.Handle("/", accessLog(http.FileServer(http.Dir(*dir_f)), *quiet_f))
log.Fatal(http.ListenAndServe(*ip_f+":"+port, mux))
}
|