Skip to content
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

proposal: net/http: customizable Not Found and Method Not Allowed handlers #67971

Closed
hossein1376 opened this issue Jun 13, 2024 · 4 comments
Closed
Labels

Comments

@hossein1376
Copy link

Proposal Details

With the HTTP router changes in go1.22, many developers are considering standard library for daily use or production. Although, as of now, NotFound and MethodNotAllowed handlers are hard coded, with no way of change or overriding them.

If we look at thefindHandler function, we see:

	//...
	allowedMethods := mux.matchingMethods(host, path)
	if len(allowedMethods) > 0 {
		return HandlerFunc(func(w ResponseWriter, r *Request) {
			w.Header().Set("Allow", strings.Join(allowedMethods, ", "))
			Error(w, StatusText(StatusMethodNotAllowed), StatusMethodNotAllowed)
		}), "", nil, nil
	}
	return NotFoundHandler(), "", nil, nil
	//...

I propose adding the option to set these two handlers.

Implementation
Referring to my PR (#67970), a new MuxOption type is introduced and two functions called WithNotFoundHandler and WithNotAllowedHandler are added.
Also, function NewServeMux is updated to accept variadic parameter of type MuxOption. This ensures backward compatibility, while allowing for customization.

To make sure the default value of ServeMux is valid as well, findHandler function is updated to use custom handlers if provided, or to use the default handlers otherwise.

@gabyhelp
Copy link

Similar Issues

(Emoji vote if this was helpful or unhelpful; more detailed feedback welcome in this discussion.)

@seankhliao
Copy link
Member

Duplicate of #65648

@seankhliao seankhliao marked this as a duplicate of #65648 Jun 13, 2024
@seankhliao seankhliao closed this as not planned Won't fix, can't repro, duplicate, stale Jun 13, 2024
@hossein1376
Copy link
Author

Duplicate of #65648

That issue does not suggest a solution. This one offers a clear approach, plus opening the door for more customizations of the ServeMux type in the future.

@seankhliao
Copy link
Member

we haven't agreed in #65648 that it is a concrete issue to address first, let's keep the discussion in one place

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

3 participants