forked from timtadh/cc-survey
/
main.go
132 lines (115 loc) · 2.7 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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
package main
import (
"fmt"
"log"
"net/http"
"os"
"path/filepath"
"time"
)
import (
"github.com/timtadh/getopt"
)
import (
"github.com/timtadh/cc-survey/views"
)
var ErrorCodes map[string]int = map[string]int{
"usage": 0,
"version": 2,
"opts": 3,
"badint": 5,
"baddir": 6,
"badfile": 7,
}
var UsageMessage string = "cc-survey --help"
var ExtendedMessage string = `
cc-survey
Options
-h, --help view this message
-l, --listen=<addr>:<port> what to listen on
default: 0.0.0.0:80
-a, --assets=<path> path to asset dir
-c, --clones=<path> path to clones dir
-s, --src=<path> path to the source
`
func Usage(code int) {
fmt.Fprintln(os.Stderr, UsageMessage)
if code == 0 {
fmt.Fprintln(os.Stdout, ExtendedMessage)
code = ErrorCodes["usage"]
}
os.Exit(code)
}
func main() {
_, optargs, err := getopt.GetOpt(
os.Args[1:],
"hl:a:c:s:",
[]string{ "help", "listen=", "assets", "clones=", "src=" },
)
if err != nil {
fmt.Fprintln(os.Stderr, "error parsing command line flags", err)
Usage(ErrorCodes["opts"])
}
listen := "0.0.0.0:80"
assets := ""
clones := ""
source := ""
for _, oa := range optargs {
switch oa.Opt() {
case "-h", "--help":
Usage(0)
os.Exit(0)
case "-l", "--listen":
listen = oa.Arg()
case "-a", "--assets":
assets, err = filepath.Abs(oa.Arg())
if err != nil {
fmt.Fprintf(os.Stderr, "assets path was bad: %v", err)
Usage(ErrorCodes["opts"])
}
case "-c", "--clones":
clones, err = filepath.Abs(oa.Arg())
if err != nil {
fmt.Fprintf(os.Stderr, "clones path was bad: %v", err)
Usage(ErrorCodes["opts"])
}
case "-s", "--src":
source, err = filepath.Abs(oa.Arg())
if err != nil {
fmt.Fprintf(os.Stderr, "source path was bad: %v", err)
Usage(ErrorCodes["opts"])
}
default:
fmt.Fprintf(os.Stderr, "Unknown flag '%v'\n", oa.Opt())
Usage(ErrorCodes["opts"])
}
}
if assets == "" {
fmt.Fprintln(os.Stderr, "You must supply a path to the assets")
Usage(ErrorCodes["opts"])
}
if clones == "" {
fmt.Fprintln(os.Stderr, "You must supply a path to the clones")
Usage(ErrorCodes["opts"])
}
if source == "" {
fmt.Fprintln(os.Stderr, "You must supply a path to the source")
Usage(ErrorCodes["opts"])
}
handler := views.Routes(assets, clones, source)
server := &http.Server{
Addr: listen,
Handler: handler,
ReadTimeout: 1 * time.Second,
WriteTimeout: 1 * time.Second,
MaxHeaderBytes: http.DefaultMaxHeaderBytes,
TLSConfig: nil,
TLSNextProto: nil,
ConnState: nil,
ErrorLog: nil,
}
err = server.ListenAndServe()
if err != nil {
log.Fatal(err)
}
}