summaryrefslogtreecommitdiff
path: root/srv/api/middleware.go
diff options
context:
space:
mode:
authorBrian Picciano <mediocregopher@gmail.com>2021-08-07 20:38:37 -0600
committerBrian Picciano <mediocregopher@gmail.com>2021-08-07 20:38:37 -0600
commit0197d9cd493b5785bca05f476856540ec64da64a (patch)
treedb19ac4bfa602b1e0b001769c57d6b7c37d96fc4 /srv/api/middleware.go
parentdce39b836a0fd6e37ab2499c2e0e232572c17ad6 (diff)
split configuration parsing out into separate packages, split api out as well
Diffstat (limited to 'srv/api/middleware.go')
-rw-r--r--srv/api/middleware.go78
1 files changed, 78 insertions, 0 deletions
diff --git a/srv/api/middleware.go b/srv/api/middleware.go
new file mode 100644
index 0000000..e3e85bb
--- /dev/null
+++ b/srv/api/middleware.go
@@ -0,0 +1,78 @@
+package api
+
+import (
+ "net"
+ "net/http"
+ "time"
+
+ "github.com/mediocregopher/mediocre-go-lib/v2/mctx"
+ "github.com/mediocregopher/mediocre-go-lib/v2/mlog"
+)
+
+func addResponseHeaders(headers map[string]string, h http.Handler) http.Handler {
+ return http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
+ for k, v := range headers {
+ rw.Header().Set(k, v)
+ }
+ h.ServeHTTP(rw, r)
+ })
+}
+
+func annotateMiddleware(h http.Handler) http.Handler {
+ return http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
+
+ type reqInfoKey string
+
+ ip, _, _ := net.SplitHostPort(r.RemoteAddr)
+
+ ctx := r.Context()
+ ctx = mctx.Annotate(ctx,
+ reqInfoKey("remote_ip"), ip,
+ reqInfoKey("url"), r.URL,
+ reqInfoKey("method"), r.Method,
+ )
+
+ r = r.WithContext(ctx)
+ h.ServeHTTP(rw, r)
+ })
+}
+
+type logResponseWriter struct {
+ http.ResponseWriter
+ statusCode int
+}
+
+func newLogResponseWriter(rw http.ResponseWriter) *logResponseWriter {
+ return &logResponseWriter{
+ ResponseWriter: rw,
+ statusCode: 200,
+ }
+}
+
+func (lrw *logResponseWriter) WriteHeader(statusCode int) {
+ lrw.statusCode = statusCode
+ lrw.ResponseWriter.WriteHeader(statusCode)
+}
+
+func logMiddleware(logger *mlog.Logger, h http.Handler) http.Handler {
+ return http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
+
+ r = setRequestLogger(r, logger)
+
+ lrw := newLogResponseWriter(rw)
+
+ started := time.Now()
+ h.ServeHTTP(lrw, r)
+ took := time.Since(started)
+
+ type logCtxKey string
+
+ ctx := r.Context()
+ ctx = mctx.Annotate(ctx,
+ logCtxKey("took"), took.String(),
+ logCtxKey("response_code"), lrw.statusCode,
+ )
+
+ logger.Info(ctx, "handled HTTP request")
+ })
+}