-
Notifications
You must be signed in to change notification settings - Fork 11
/
main.go
47 lines (39 loc) · 993 Bytes
/
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
package main
import (
"flag"
"fmt"
"log"
"net/http"
)
var Port int
var Dir string
func init() {
flag.IntVar(&Port, "port", 8000, "port to listen on")
flag.StringVar(&Dir, "dir", ".", "directory to serve")
}
// ResponseWriter wraps http.ResponseWriter to capture the HTTP status code
type ResponseWriter struct {
http.ResponseWriter
StatusCode int
}
func (w *ResponseWriter) WriteHeader(statusCode int) {
w.StatusCode = statusCode
w.ResponseWriter.WriteHeader(statusCode)
}
// Handler wraps http.Handler to log served files
type Handler struct {
http.Handler
}
func (h *Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
rw := &ResponseWriter{w, 0}
h.Handler.ServeHTTP(rw, r)
log.Println(r.RemoteAddr, r.Method, rw.StatusCode, r.URL)
}
func main() {
flag.Parse()
handler := &Handler{http.FileServer(http.Dir(Dir))}
http.Handle("/", handler)
addr := fmt.Sprintf(":%d", Port)
log.Printf("Listening on %s\n", addr)
log.Fatal(http.ListenAndServe(addr, nil))
}