Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make path "/" dont match all others not matched paths in Golang net/http

Tags:

go

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
like image 517
wiltonsr Avatar asked Oct 25 '25 20:10

wiltonsr


1 Answers

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())
}

like image 100
iTrooz Avatar answered Oct 27 '25 10:10

iTrooz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!