examples/server: Add logging middleware
This commit is contained in:
parent
b66b287f94
commit
991b18d526
@ -26,7 +26,7 @@ func main() {
|
||||
mux.Handle("/", gemini.FileServer(os.DirFS("/var/www")))
|
||||
|
||||
server := &gemini.Server{
|
||||
Handler: mux,
|
||||
Handler: logMiddleware(mux),
|
||||
ReadTimeout: 30 * time.Second,
|
||||
WriteTimeout: 1 * time.Minute,
|
||||
GetCertificate: certificates.Get,
|
||||
@ -55,3 +55,53 @@ func main() {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func logMiddleware(h gemini.Handler) gemini.Handler {
|
||||
return gemini.HandlerFunc(func(ctx context.Context, w gemini.ResponseWriter, r *gemini.Request) {
|
||||
lw := &logResponseWriter{rw: w}
|
||||
h.ServeGemini(ctx, lw, r)
|
||||
host := r.TLS().ServerName
|
||||
log.Printf("gemini: %s %q %d %d", host, r.URL, lw.status, lw.wrote)
|
||||
})
|
||||
}
|
||||
|
||||
type logResponseWriter struct {
|
||||
rw gemini.ResponseWriter
|
||||
status gemini.Status
|
||||
meta string
|
||||
mediatype string
|
||||
wroteHeader bool
|
||||
wrote int
|
||||
}
|
||||
|
||||
func (w *logResponseWriter) SetMediaType(mediatype string) {
|
||||
w.mediatype = mediatype
|
||||
}
|
||||
|
||||
func (w *logResponseWriter) Write(b []byte) (int, error) {
|
||||
if !w.wroteHeader {
|
||||
w.WriteHeader(gemini.StatusSuccess, w.mediatype)
|
||||
}
|
||||
n, err := w.rw.Write(b)
|
||||
w.wrote += n
|
||||
return n, err
|
||||
}
|
||||
|
||||
func (w *logResponseWriter) WriteHeader(status gemini.Status, meta string) {
|
||||
if w.wroteHeader {
|
||||
return
|
||||
}
|
||||
w.status = status
|
||||
w.meta = meta
|
||||
w.wroteHeader = true
|
||||
w.rw.WriteHeader(status, meta)
|
||||
w.wrote += len(meta) + 5
|
||||
}
|
||||
|
||||
func (w *logResponseWriter) Flush() error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (w *logResponseWriter) Close() error {
|
||||
return nil
|
||||
}
|
||||
|
Loading…
Reference in New Issue
Block a user