-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
78 lines (65 loc) · 1.55 KB
/
main.go
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
package main
import (
"fmt"
"log"
"net"
"net/http"
"os"
)
const (
defaultRoot = "."
defaultHost = "localhost"
defaultPort = "8000"
defaultHostPort = defaultHost + ":" + defaultPort
)
const helpTxt = `Serves the content of a directory as HTTP
usage: serve [-h] [addr] [dir]
options:
addr Address to listen on. Defaults to "` + defaultHostPort + `"
Format is host:port where "host" can be omitted to listen on all
network interfaces.
dir File server root directory, defaults to current directory
-h/--help Show this message`
func main() {
log.SetFlags(0)
log.SetPrefix("[serve] ")
dir, addr, help, exit := parseCommandLine(os.Args[1:])
if help {
fmt.Fprintln(os.Stderr, helpTxt)
os.Exit(exit)
}
host, port, err := net.SplitHostPort(addr)
if err != nil {
fmt.Fprintln(os.Stderr, "Error:", err)
os.Exit(1)
}
if host == "" {
host = "*"
}
if _, err := os.Stat(dir); err != nil {
fmt.Fprintln(os.Stderr, "Error:", err)
os.Exit(1)
}
log.Println("serving", dir, "on http://"+host+":"+port+"/")
panic(http.ListenAndServe(addr, noCache(http.FileServer(http.Dir(dir)))))
}
// parseCommandLine
func parseCommandLine(args []string) (dir, addr string, help bool, exit int) {
dir = defaultRoot
addr = defaultHostPort
nargs := len(args)
switch {
case nargs == 0: // all default
case args[0] == "-h", args[0] == "--help":
help = true
case nargs > 2:
help = true
exit = 1
case nargs == 1: // just addr
addr = args[0]
default:
addr = args[0]
dir = args[1]
}
return
}