I'm playing around with the new go 1.22 features, but I can't seem to reach GET "/users/register" handler function and instead receive 404. What is the issue here? snippet from package main:
func main() {
if err := godotenv.Load(); err != nil {
log.Fatal("Failed to load .env:", err)
}
_, err := repository.InitDB()
if err != nil {
log.Fatal("Failed to initialise the database:", err)
}
userMux := http.NewServeMux()
if err := handlers.InitUserRoutes(userMux); err != nil {
log.Fatal("Failed to initialise user routes:", err)
}
mux := http.NewServeMux()
mux.Handle("/users/", userMux)
log.Fatal(http.ListenAndServe(fmt.Sprintf("%s:%s", os.Getenv("DOMAIN"), os.Getenv("PORT")), mux))
}
snippet from package handlers:
var templates *template.Template
func InitUserRoutes(mux *http.ServeMux) error {
var err error
templates, err = utils.ParseTemplates("web/templates/user")
if err != nil {
return err
}
mux.HandleFunc("GET /register/", registerGet)
mux.HandleFunc("POST /register/", registerPost)
return nil
}
func registerGet(w http.ResponseWriter, r *http.Request) {
fmt.Println("I'm here")
err := templates.ExecuteTemplate(w, "register.html", nil)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
}
func registerPost(w http.ResponseWriter, r *http.Request) {
if err := r.ParseForm(); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
fmt.Printf("%#v\n\n%#v", r.Form, r.PostForm)
email, username, password := r.FormValue("email"), r.FormValue("username"), r.FormValue("password")
fmt.Printf("%v, %v, %v\n", email, username, password)
}
snippet from package utils:
func ParseTemplates(folderPath string) (*template.Template, error) {
return template.ParseGlob(filepath.Join(folderPath, "*.html"))
}
it works fine for me
package main
import (
"fmt"
"log"
"net/http"
)
func main() {
prefix := "/users"
userMux := http.NewServeMux()
userMux.HandleFunc("GET /register/", registerGet)
userMux.HandleFunc("GET /register2/", registerGet)
userMux.HandleFunc("POST /register/", registerPost)
mux := http.NewServeMux()
mux.Handle("/users/{pathname...}", http.StripPrefix(prefix, userMux))
log.Fatal(http.ListenAndServe(":12345", mux))
}
func registerGet(w http.ResponseWriter, r *http.Request) {
fmt.Fprintln(w, r.Method, "I'm here", r.RequestURI)
}
func registerPost(w http.ResponseWriter, r *http.Request) {
fmt.Fprintln(w, r.Method, "I'm here", r.RequestURI)
}