Files

58 lines
1.7 KiB
Go
Raw Permalink Normal View History

2023-07-21 09:16:58 +02:00
// Package middleware provides middleware for the idp service.
2020-02-13 21:33:06 +01:00
package middleware
import (
"net/http"
"strings"
2020-03-11 13:25:26 +01:00
2021-08-09 17:28:00 +02:00
"go.opentelemetry.io/otel/attribute"
"go.opentelemetry.io/otel/codes"
2023-06-22 10:09:10 +02:00
"go.opentelemetry.io/otel/trace"
2020-02-13 21:33:06 +01:00
)
// Static is a middleware that serves static assets.
func Static(root string, fs http.FileSystem, tp trace.TracerProvider) func(http.Handler) http.Handler {
2020-02-13 21:33:06 +01:00
if !strings.HasSuffix(root, "/") {
root = root + "/"
}
static := http.StripPrefix(
root,
http.FileServer(
fs,
),
)
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
2023-06-22 10:09:10 +02:00
spanOpts := []trace.SpanStartOption{
trace.WithSpanKind(trace.SpanKindServer),
}
ctx, span := tp.Tracer("idp").Start(r.Context(), "serve static asset", spanOpts...)
2020-03-11 13:25:26 +01:00
defer span.End()
r = r.WithContext(ctx)
2020-02-13 21:33:06 +01:00
// serve the static assets for the identifier web app
if strings.HasPrefix(r.URL.Path, "/signin/v1/static/") {
if strings.HasSuffix(r.URL.Path, "/") {
// but no listing of folders
2021-08-09 17:28:00 +02:00
span.SetAttributes(attribute.KeyValue{Key: "path", Value: attribute.StringValue(r.URL.Path)})
span.SetStatus(codes.Error, "asset not found")
2020-02-13 21:33:06 +01:00
http.NotFound(w, r)
} else {
r.URL.Path = strings.Replace(r.URL.Path, "/signin/v1/static/", "/signin/v1/identifier/static/", 1)
2021-08-09 17:28:00 +02:00
span.SetAttributes(attribute.KeyValue{Key: "server", Value: attribute.StringValue(r.URL.Path)})
if strings.HasSuffix(r.URL.Path, ".css") {
w.Header().Set("Cache-Control", "no-cache")
}
2020-02-13 21:33:06 +01:00
static.ServeHTTP(w, r)
}
return
}
2021-08-09 17:28:00 +02:00
span.SetAttributes(attribute.KeyValue{Key: "path", Value: attribute.StringValue(r.URL.Path)})
span.SetStatus(codes.Ok, "ok")
2021-08-09 17:37:58 +02:00
next.ServeHTTP(w, r)
2020-02-13 21:33:06 +01:00
})
}
}