From 859d4fa45808e526bb7b8f5bc43f393294782d18 Mon Sep 17 00:00:00 2001 From: Ankit Patial Date: Mon, 4 Nov 2024 11:06:49 +0530 Subject: [PATCH] option handler --- router_serve.go | 28 ++++++++++++---------------- 1 file changed, 12 insertions(+), 16 deletions(-) diff --git a/router_serve.go b/router_serve.go index 76ba5ae..3c579e6 100644 --- a/router_serve.go +++ b/router_serve.go @@ -16,7 +16,18 @@ type ServeCB func(srv *http.Server) error func (r *Router) Serve(cb ServeCB) { // catch all options // lets get it thorugh all middlewares - r.mux.Handle("OPTIONS /", optionsHandler{}) + r.OPTIONS("/", func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Length", "0") + if r.ContentLength != 0 { + // Read up to 4KB of OPTIONS body (as mentioned in the + // spec as being reserved for future use), but anything + // over that is considered a waste of server resources + // (or an attack) and we abort and close the connection, + // courtesy of MaxBytesReader's EOF behavior. + mb := http.MaxBytesReader(w, r.Body, 4<<10) + io.Copy(io.Discard, mb) + } + }) srv := &http.Server{ Handler: r, @@ -45,18 +56,3 @@ func (r *Router) Serve(cb ServeCB) { <-idleConnsClosed } - -type optionsHandler struct{} - -func (optionsHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { - w.Header().Set("Content-Length", "0") - if r.ContentLength != 0 { - // Read up to 4KB of OPTIONS body (as mentioned in the - // spec as being reserved for future use), but anything - // over that is considered a waste of server resources - // (or an attack) and we abort and close the connection, - // courtesy of MaxBytesReader's EOF behavior. - mb := http.MaxBytesReader(w, r.Body, 4<<10) - io.Copy(io.Discard, mb) - } -}