Skip to content

net/http: add Server.OptionsHandler for custom handling of OPTIONS * #49013

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 36 additions & 0 deletions src/net/http/serve_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -3434,6 +3434,42 @@ func TestOptions(t *testing.T) {
}
}

func TestOptionsHandler(t *testing.T) {
rc := make(chan *Request, 1)

ts := httptest.NewUnstartedServer(HandlerFunc(func(w ResponseWriter, r *Request) {
t.Fatalf("Got unexpected request %v", r)
}))
ts.Config.OptionsHandler = HandlerFunc(func(w ResponseWriter, r *Request) {
w.Header().Set("Content-Length", "0")
rc <- r
})
ts.Start()
defer ts.Close()

conn, err := net.Dial("tcp", ts.Listener.Addr().String())
if err != nil {
t.Fatal(err)
}
defer conn.Close()

_, err = conn.Write([]byte("OPTIONS * HTTP/1.1\r\nHost: foo.com\r\n\r\n"))
if err != nil {
t.Fatal(err)
}
res, err := ReadResponse(bufio.NewReader(conn), &Request{Method: "OPTIONS"})
if err != nil {
t.Fatal(err)
}
if res.StatusCode != 200 {
t.Errorf("Got non-200 response to OPTIONS *: %#v", res)
}

if got := <-rc; got.Method != "OPTIONS" || got.RequestURI != "*" {
t.Errorf("Expected OPTIONS * request, got %v", got)
}
}

// Tests regarding the ordering of Write, WriteHeader, Header, and
// Flush calls. In Go 1.0, rw.WriteHeader immediately flushed the
// (*response).header to the wire. In Go 1.1, the actual wire flush is
Expand Down
9 changes: 8 additions & 1 deletion src/net/http/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -2570,6 +2570,10 @@ type Server struct {

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

// OptionsHandler handles "OPTIONS *" requests.
// If nil, server responds with 200 OK and Content-Length: 0.
OptionsHandler Handler

// TLSConfig optionally provides a TLS configuration for use
// by ServeTLS and ListenAndServeTLS. Note that this value is
// cloned by ServeTLS and ListenAndServeTLS, so it's not
Expand Down Expand Up @@ -2897,7 +2901,10 @@ func (sh serverHandler) ServeHTTP(rw ResponseWriter, req *Request) {
handler = DefaultServeMux
}
if req.RequestURI == "*" && req.Method == "OPTIONS" {
handler = globalOptionsHandler{}
handler = sh.srv.OptionsHandler
if handler == nil {
handler = globalOptionsHandler{}
}
}

if req.URL != nil && strings.Contains(req.URL.RawQuery, ";") {
Expand Down