diff options
| author | JP Appel <jeanpierre.appel01@gmail.com> | 2024-10-09 16:03:12 -0400 |
|---|---|---|
| committer | JP Appel <jeanpierre.appel01@gmail.com> | 2024-10-09 16:03:12 -0400 |
| commit | 17e269202ba01e8467a87163395a1e6ac8261e02 (patch) | |
| tree | 38a4698f8789268a935c133d004f2bb9f7b0d81a /nonsense-time.go | |
| parent | a1af12ca8bf93a14b3017aa463a9463eaa4f1188 (diff) | |
Refactor middleware to separate package
Diffstat (limited to 'nonsense-time.go')
| -rw-r--r-- | nonsense-time.go | 67 |
1 files changed, 3 insertions, 64 deletions
diff --git a/nonsense-time.go b/nonsense-time.go index 4bb1067..f148266 100644 --- a/nonsense-time.go +++ b/nonsense-time.go @@ -1,79 +1,18 @@ package main import ( - "compress/gzip" - "context" "flag" "fmt" "log/slog" "net/http" "nonsense-time/api" + "nonsense-time/middleware" "os" - "strings" "time" ) var logger *slog.Logger -// Middleware to timeout requests after a given duration -func timeoutMiddleware(next http.Handler, duration time.Duration) http.Handler { - return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - ctx, cancel := context.WithTimeout(r.Context(), duration) - defer cancel() - - next.ServeHTTP(w, r.WithContext(ctx)) - }) -} - -type gzipResponseWriter struct { - gzip.Writer - http.ResponseWriter -} - -func newGzipResponseWriter(w http.ResponseWriter) *gzipResponseWriter { - gzrw := new(gzipResponseWriter) - gzrw.Writer = *gzip.NewWriter(w) - gzrw.ResponseWriter = w - - return gzrw -} - -func (gzrw *gzipResponseWriter) Close() error { - return gzrw.Writer.Close() -} - -func (gzrw *gzipResponseWriter) Header() http.Header { - return gzrw.ResponseWriter.Header() -} - -func (gzrw *gzipResponseWriter) Write(p []byte) (int, error) { - n, err := gzrw.Writer.Write(p) - return n, err -} - -func (gzrw *gzipResponseWriter) WriteHeader(statuscode int) { - gzrw.ResponseWriter.WriteHeader(statuscode) -} - -// Middleware to conditionally gzip a response -func gzipMiddleware(next http.Handler) http.Handler { - return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - acceptedEncodings := r.Header.Get("Accept-Encoding") - - if !strings.Contains(acceptedEncodings, "gzip") { - logger.DebugContext(r.Context(), "Using gzip middleware but client does not support gzip encoding") - next.ServeHTTP(w, r) - return - } - - w.Header().Add("Content-Encoding", "gzip") - gzrw := newGzipResponseWriter(w) - defer gzrw.Close() - - next.ServeHTTP(gzrw, r) - }) -} - func main() { port := flag.Int("p", 8080, "the port to listen on") @@ -111,8 +50,8 @@ func main() { api.Logger = logger - vtt := timeoutMiddleware(http.HandlerFunc(api.VttOnline), *waitTime) - vttLogs := gzipMiddleware(http.HandlerFunc(api.VttLogs)) + vtt := middleware.Timeout(http.HandlerFunc(api.VttOnline), *waitTime) + vttLogs := middleware.Gzip(http.HandlerFunc(api.VttLogs)) mux.Handle("GET /vtt/status", vtt) mux.HandleFunc("GET /vtt", api.VttRedirect) |
