Home > Back-end >  How to make path "/" dont match all others not matched paths in Golang net/http
How to make path "/" dont match all others not matched paths in Golang net/http

Time:04-29

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

CodePudding user response:

Since the mux you are using will match the / handler to any unregistered one, you'll have to check the path anytime your handler for the / path is called:

package main

import (
    "fmt"
    "log"
    "net/http"
)

func index(w http.ResponseWriter, req *http.Request) {
    if req.URL.Path != "/" { // Check path here
       http.NotFound(w, req)
       return
    }
    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("/foo", foo)
    mux.HandleFunc("/bar", bar)
    mux.HandleFunc("/", index)

    log.Fatal(s.ListenAndServe())
}
  •  Tags:  
  • go
  • Related