Skip to content

Commit 1f8ff36

Browse files
net/http: add Server.DisableOptionsHandler for custom handling of OPTIONS *
Fixes #41773
1 parent ed1c8db commit 1f8ff36

File tree

2 files changed

+38
-1
lines changed

2 files changed

+38
-1
lines changed

src/net/http/serve_test.go

+33
Original file line numberDiff line numberDiff line change
@@ -3434,6 +3434,39 @@ func TestOptions(t *testing.T) {
34343434
}
34353435
}
34363436

3437+
func TestOptionsHandler(t *testing.T) {
3438+
rc := make(chan *Request, 1)
3439+
3440+
ts := httptest.NewUnstartedServer(HandlerFunc(func(w ResponseWriter, r *Request) {
3441+
rc <- r
3442+
}))
3443+
ts.Config.DisableOptionsHandler = true
3444+
ts.Start()
3445+
defer ts.Close()
3446+
3447+
conn, err := net.Dial("tcp", ts.Listener.Addr().String())
3448+
if err != nil {
3449+
t.Fatal(err)
3450+
}
3451+
defer conn.Close()
3452+
3453+
_, err = conn.Write([]byte("OPTIONS * HTTP/1.1\r\nHost: foo.com\r\n\r\n"))
3454+
if err != nil {
3455+
t.Fatal(err)
3456+
}
3457+
res, err := ReadResponse(bufio.NewReader(conn), &Request{Method: "OPTIONS"})
3458+
if err != nil {
3459+
t.Fatal(err)
3460+
}
3461+
if res.StatusCode != 200 {
3462+
t.Errorf("Got non-200 response to OPTIONS *: %#v", res)
3463+
}
3464+
3465+
if got := <-rc; got.Method != "OPTIONS" || got.RequestURI != "*" {
3466+
t.Errorf("Expected OPTIONS * request, got %v", got)
3467+
}
3468+
}
3469+
34373470
// Tests regarding the ordering of Write, WriteHeader, Header, and
34383471
// Flush calls. In Go 1.0, rw.WriteHeader immediately flushed the
34393472
// (*response).header to the wire. In Go 1.1, the actual wire flush is

src/net/http/server.go

+5-1
Original file line numberDiff line numberDiff line change
@@ -2570,6 +2570,10 @@ type Server struct {
25702570

25712571
Handler Handler // handler to invoke, http.DefaultServeMux if nil
25722572

2573+
// DisableOptionsHandler, if true, passes "OPTIONS *" requests to the Handler,
2574+
// otherwise responds with 200 OK and Content-Length: 0.
2575+
DisableOptionsHandler bool
2576+
25732577
// TLSConfig optionally provides a TLS configuration for use
25742578
// by ServeTLS and ListenAndServeTLS. Note that this value is
25752579
// cloned by ServeTLS and ListenAndServeTLS, so it's not
@@ -2896,7 +2900,7 @@ func (sh serverHandler) ServeHTTP(rw ResponseWriter, req *Request) {
28962900
if handler == nil {
28972901
handler = DefaultServeMux
28982902
}
2899-
if req.RequestURI == "*" && req.Method == "OPTIONS" {
2903+
if !sh.srv.DisableOptionsHandler && req.RequestURI == "*" && req.Method == "OPTIONS" {
29002904
handler = globalOptionsHandler{}
29012905
}
29022906

0 commit comments

Comments
 (0)