aboutsummaryrefslogtreecommitdiff
path: root/vendor/github.com/Xe/ln/ex/http.go
blob: c5715a35539ade920b2a334e8df38020023ddfcc (plain)
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
package ex

import (
	"net"
	"net/http"
	"time"

	"github.com/Xe/ln"
)

func HTTPLog(next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		host, _, _ := net.SplitHostPort(r.RemoteAddr)
		f := ln.F{
			"remote_ip":       host,
			"x_forwarded_for": r.Header.Get("X-Forwarded-For"),
			"path":            r.URL.Path,
		}
		ctx := ln.WithF(r.Context(), f)
		st := time.Now()

		next.ServeHTTP(w, r.WithContext(ctx))

		af := time.Now()
		f["request_duration"] = af.Sub(st)

		ws, ok := w.(interface {
			Status() int
		})
		if ok {
			f["status"] = ws.Status()
		}

		ln.Log(r.Context(), f)
	})
}