I'm using golang net/http to create some endpoints in an API.
I have an index function mapped to / path. I need any path that was not explicitly declared to mux to return 404.
The docs says:
Note that since a pattern ending in a slash names a rooted subtree, the pattern "/" matches all paths not matched by other registered patterns, not just the URL with Path == "/".
So, how can I do this?
Follows a MRE:
package main
import (
"fmt"
"log"
"net/http"
)
func index(w http.ResponseWriter, req *http.Request) {
fmt.Fprintln(w, "index")
}
func foo(w http.ResponseWriter, req *http.Request) {
fmt.Fprintln(w, "foo")
}
func bar(w http.ResponseWriter, req *http.Request) {
fmt.Fprintln(w, "bar")
}
func main() {
mux := http.NewServeMux()
s := &http.Server{
Addr: ":8000",
Handler: mux,
}
mux.HandleFunc("/", index)
mux.HandleFunc("/foo", foo)
mux.HandleFunc("/bar", bar)
log.Fatal(s.ListenAndServe())
}
When I run:
$ curl 'http://localhost:8000/'
index
$ curl 'http://localhost:8000/foo'
foo
$ curl 'http://localhost:8000/bar'
bar
$ curl 'http://localhost:8000/notfoo'
index // Expected 404 page not found
Starting with Go 1.22, you can now match only / by using the /{$} pattern
Example:
package main
import (
"fmt"
"log"
"net/http"
)
func index(w http.ResponseWriter, req *http.Request) {
fmt.Fprintln(w, "index")
}
func main() {
mux := http.NewServeMux()
s := &http.Server{
Addr: ":8000",
Handler: mux,
}
mux.HandleFunc("/{$}", index)
log.Fatal(s.ListenAndServe())
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With