gohttpservemux

Getting 404 error in Golang while sending get request to a route


I am beginner in Golang and following let's go book. I create a servemux instance in the app and register root route with wildcard route pattern. I try to access the route and I am getting 404 page not found error. Without the wildcard route pattern it is working fine. Below is my code. What is wrong after adding wildcard route pattern?

package main

import ( 
    "log"
    "net/http"
)
func home(w http.ResponseWriter, r *http.Request) {
    w.Write([]byte("Hello from Snippetbox"))
}
func main() {

    mux := http.NewServeMux()
    mux.HandleFunc("GET /{$}", home)

    log.Print("starting server on :4000")
    err := http.ListenAndServe(":4000", mux)
    log.Fatal(err) 
}

Solution

  • I also encountered the same issue. After several times of ineffective rollback, I noticed that the go.mod file doesn't existed. So, I ran the following command to create go.mod, which should be located in Chapter 2.1.

    go mod init snippetbox.alexedwards.net
    

    And the program reply "Hello from Snippetbox" as expected.

    Note: I run the code samples via debugging in visual studio code and go version is go1.22.2.