-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathserve.go
99 lines (78 loc) · 2.25 KB
/
serve.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
package main
import (
"flag"
"fmt"
"net/http"
"os"
"strings"
"time"
"github.com/justinas/alice"
"github.com/kevinpollet/serve/log"
"github.com/kevinpollet/serve/middlewares"
)
var (
flagAddr = flag.String("addr", "127.0.0.1:8080", "")
flagAuth = flag.String("auth", "", "")
flagAuthFile = flag.String("auth-file", "", "")
flagDir = flag.String("dir", ".", "")
flagCert = flag.String("cert", "", "")
flagKey = flag.String("key", "", "")
)
const usage = `Usage: serve [options]
Options:
-addr Sets the server address. Default is "127.0.0.1:8080".
-auth Sets the basic auth credentials (password must be hashed with bcrypt and escaped with '').
-auth-file Sets the basic auth credentials following the ".htpasswd" format.
-dir Sets the directory containing the files to serve. Default is ".".
-cert Sets the TLS certificate.
-key Sets the TLS private key.
-help Prints this text.
`
func main() {
flag.Usage = func() {
fmt.Fprint(os.Stderr, usage)
os.Exit(2)
}
flag.Parse()
var handlers []alice.Constructor
switch {
case len(*flagAuth) > 0:
reader := strings.NewReader(*flagAuth)
basicAuthHandler, err := middlewares.NewBasicAuthHandler("serve", reader)
if err != nil {
errExit(err)
}
handlers = append(handlers, basicAuthHandler)
case len(*flagAuthFile) > 0:
file, err := os.Open(*flagAuthFile)
if err != nil {
errExit(err)
}
defer func() { _ = file.Close() }()
basicAuthHandler, err := middlewares.NewBasicAuthHandler("serve", file)
if err != nil {
errExit(err)
}
handlers = append(handlers, basicAuthHandler)
}
handlers = append(handlers, middlewares.NewNegotiateEncodingHandler(
middlewares.EncodingBrotli,
middlewares.EncodingGzip,
middlewares.EncodingDeflate,
))
server := http.Server{
Addr: *flagAddr,
ReadTimeout: 5 * time.Second,
WriteTimeout: 10 * time.Second,
Handler: NewFileServer(*flagDir, WithMiddlewares(handlers...)),
}
log.Logger().Printf("server is listening on: %s", server.Addr)
if len(*flagCert) > 0 && len(*flagKey) > 0 {
log.Logger().Fatal(server.ListenAndServeTLS(*flagCert, *flagKey))
}
log.Logger().Fatal(server.ListenAndServe())
}
func errExit(err error) {
log.Logger().Error(err)
os.Exit(1)
}