-
Notifications
You must be signed in to change notification settings - Fork 0
/
gost.go
84 lines (66 loc) · 1.75 KB
/
gost.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
package main
import (
"fmt"
"log"
"net/http"
"os"
"runtime"
"github.com/vwochnik/gost/fileserver"
"github.com/vwochnik/gost/template"
)
const Version = "0.1.2"
var args Arguments
func init() {
runtime.GOMAXPROCS(runtime.NumCPU())
parseArguments(&args)
if len(args.log) > 0 {
file, err := os.OpenFile(args.log, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666)
exitOnError(err)
defer file.Close()
log.SetOutput(file)
} else if args.quiet {
file, err := os.Open(os.DevNull)
exitOnError(err)
defer file.Close()
log.SetOutput(file)
log.SetFlags(0)
}
}
func main() {
listen := fmt.Sprintf("%s:%d", args.host, args.port)
fileserver.NotFoundHandler = func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/html; charset=utf-8")
w.WriteHeader(404)
template.ErrorTemplate(w, "File Not Found", 404)
}
fileserver.ErrorHandler = func(w http.ResponseWriter, r *http.Request, msg string, code int) {
w.Header().Set("Content-Type", "text/html; charset=utf-8")
w.WriteHeader(code)
template.ErrorTemplate(w, msg, code)
}
fileserver.DirListHandler = func(w http.ResponseWriter, f http.File) {
w.Header().Set("Content-Type", "text/html; charset=utf-8")
template.DirectoryTemplate(w, f)
}
http.Handle("/", fileserver.FileServer(http.Dir(args.directory)))
handler := buildHttpHandler()
log.Printf("Static file server running at %s. Ctrl+C to quit.\n", listen)
err := http.ListenAndServe(listen, handler)
if err != nil {
log.Fatalln(err)
}
}
func buildHttpHandler() http.Handler {
var handler http.Handler
handler = http.DefaultServeMux
if args.cors {
handler = corsHandler(handler)
}
if args.noCache {
handler = cacheHandler(handler)
}
if !args.quiet {
handler = logHandler(handler)
}
return handler
}