/
main.go
175 lines (151 loc) · 4.07 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
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
package main
import (
"compress/gzip"
"flag"
"fmt"
"io"
"log"
"net/http"
"os"
"path/filepath"
"runtime"
"strings"
"time"
)
const (
apacheFormatPattern = "%s %.4f - [%s] \"%s\" %d %d %s %s\n"
version = "1.1.0"
)
func main() {
address := flag.String("address", "127.0.0.1", "The address to listen on")
path := flag.String("path", "", "Path to the document root")
port := flag.String("port", "8080", "The port to listen on")
tls := flag.Bool("tls", false, "Use TLS")
cert := flag.String("cert", "cert.pem", "The TLS certificate to use")
key := flag.String("key", "key.pem", "The TLS key to use.")
compress := flag.Bool("gz", false, "Use gzip compression.")
flag.Parse()
if *tls == true {
if *port == "8080" {
*port = "8443"
}
}
addrFmt := fmt.Sprintf("%s:%s", *address, *port)
mux := http.DefaultServeMux
mux.Handle("/", http.FileServer(http.Dir(*path)))
println("Starting server with document root: '" + filepath.Base(*path) + "'")
if *tls == true {
println(" at https://" + addrFmt + "/")
} else {
println(" at http://" + addrFmt + "/")
}
println("dserve", version, "built with go version: ", runtime.Version())
var loggingHandler http.Handler
if *compress {
loggingHandler = NewApacheLoggingHandler(NewGzipHandler(mux), os.Stderr)
} else {
loggingHandler = NewApacheLoggingHandler(mux, os.Stderr)
}
server := &http.Server{
Addr: addrFmt,
Handler: loggingHandler,
}
if *tls == true {
if err := server.ListenAndServeTLS(*cert, *key); err != nil {
log.Fatal(err)
}
} else {
if err := server.ListenAndServe(); err != nil {
log.Fatal(err)
}
}
}
// Borrowed and modified from a gist...need to find and attribute...
type gzipResponseWriter struct {
io.Writer
http.ResponseWriter
}
func (w gzipResponseWriter) Write(b []byte) (int, error) {
return w.Writer.Write(b)
}
func NewGzipHandler(handler http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if !strings.Contains(r.Header.Get("Accept-Encoding"), "gzip") {
handler.ServeHTTP(w, r)
return
}
w.Header().Set("Content-Encoding", "gzip")
gz := gzip.NewWriter(w)
defer gz.Close()
gzw := gzipResponseWriter{Writer: gz, ResponseWriter: w}
handler.ServeHTTP(gzw, r)
return
})
}
type ApacheLogRecord struct {
http.ResponseWriter
ip string
time time.Time
method, uri, protocol string
status int
responseBytes int64
referrer string
userAgent string
elapsedTime time.Duration
}
func (r *ApacheLogRecord) Log(out io.Writer) {
timeFormatted := r.time.Format("02/Jan/2006 03:04:05")
requestLine := fmt.Sprintf("%s %s %s", r.method, r.uri, r.protocol)
fmt.Fprintf(out, apacheFormatPattern,
r.ip,
r.elapsedTime.Seconds(),
timeFormatted,
requestLine,
r.status,
r.responseBytes,
r.referrer,
r.userAgent)
}
func (r *ApacheLogRecord) Write(p []byte) (int, error) {
written, err := r.ResponseWriter.Write(p)
r.responseBytes += int64(written)
return written, err
}
func (r *ApacheLogRecord) WriteHeader(status int) {
r.status = status
r.ResponseWriter.WriteHeader(status)
}
type ApacheLoggingHandler struct {
handler http.Handler
out io.Writer
}
func NewApacheLoggingHandler(handler http.Handler, out io.Writer) http.Handler {
return &ApacheLoggingHandler{
handler: handler,
out: out,
}
}
func (h *ApacheLoggingHandler) ServeHTTP(rw http.ResponseWriter, r *http.Request) {
clientIP := r.RemoteAddr
if colon := strings.LastIndex(clientIP, ":"); colon != -1 {
clientIP = clientIP[:colon]
}
record := &ApacheLogRecord{
ResponseWriter: rw,
ip: clientIP,
time: time.Time{},
method: r.Method,
uri: r.RequestURI,
protocol: r.Proto,
status: http.StatusOK,
referrer: r.Referer(),
userAgent: r.UserAgent(),
elapsedTime: time.Duration(0),
}
startTime := time.Now()
h.handler.ServeHTTP(record, r)
finishTime := time.Now()
record.time = finishTime.UTC()
record.elapsedTime = finishTime.Sub(startTime)
record.Log(h.out)
}