default options handler
This commit is contained in:
@@ -3,6 +3,7 @@ package mux
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"io"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"os"
|
||||
@@ -13,6 +14,10 @@ type ServeCB func(srv *http.Server) error
|
||||
|
||||
// Serve with graceful shutdown
|
||||
func (r *Router) Serve(cb ServeCB) {
|
||||
// catch all options
|
||||
// lets get it thorugh all middlewares
|
||||
r.mux.Handle("OPTIONS /", optionsHandler{})
|
||||
|
||||
srv := &http.Server{
|
||||
Handler: r,
|
||||
}
|
||||
@@ -40,3 +45,18 @@ 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)
|
||||
}
|
||||
}
|
||||
|
Reference in New Issue
Block a user