-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
78 lines (66 loc) · 2.03 KB
/
main.go
File metadata and controls
78 lines (66 loc) · 2.03 KB
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
// test server for hugo build content dir
// go run main.go
package main
import (
"io/fs"
"log"
"net/http"
"time"
"embed"
)
//go:embed public/*
var content embed.FS
const subPath = "/linux-for-devops-engineers/" // repo name
type (
// struct for holding response details
responseData struct {
status int
size int
}
// http.ResponseWriter implementation
loggingResponseWriter struct {
http.ResponseWriter // compose original http.ResponseWriter
responseData *responseData
}
)
func (r *loggingResponseWriter) Write(b []byte) (int, error) {
size, err := r.ResponseWriter.Write(b) // write response using original http.ResponseWriter
r.responseData.size += size // capture size
return size, err
}
func (r *loggingResponseWriter) WriteHeader(statusCode int) {
r.ResponseWriter.WriteHeader(statusCode) // write status code using original http.ResponseWriter
r.responseData.status = statusCode // capture status code
}
func WithLogging(h http.Handler) http.Handler {
logFn := func(rw http.ResponseWriter, req *http.Request) {
start := time.Now()
responseData := &responseData{
status: 0,
size: 0,
}
lrw := loggingResponseWriter{
ResponseWriter: rw, // compose original http.ResponseWriter
responseData: responseData,
}
h.ServeHTTP(&lrw, req) // serve the original request
duration := time.Since(start)
// log request details
log.Printf("status=%v method=%v uri=%v duration=%v size=%v", responseData.status, req.Method, req.RequestURI, duration, responseData.size)
}
return http.HandlerFunc(logFn)
}
func main() {
mux := http.NewServeMux()
fsys, _ := fs.Sub(content, "public")
// use embed.
mux.Handle("/", WithLogging(http.FileServer(http.FS(fsys))))
// use StripPrefix to modify the request
// URL's path before the FileServer sees it:
mux.Handle(subPath, WithLogging(http.StripPrefix(subPath, http.FileServer(http.FS(fsys)))))
log.Println("http server started on :8080")
err := http.ListenAndServe(":8080", mux)
if err != nil {
log.Fatal("ListenAndServe: ", err)
}
}