-
Notifications
You must be signed in to change notification settings - Fork 1.8k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Path variable not parsed #709
Labels
Comments
Hi @KGKallasmaa Could you put complete code snippet here, as I can test it out it is working fine. This is the code I have used package main
import (
"fmt"
"log"
"net/http"
"time"
"github.com/gorilla/handlers"
"github.com/gorilla/mux"
)
func YourHandler(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("Ping!\n"))
}
func FindUserById(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
id, ok := vars["id"]
if !ok {
w.WriteHeader(http.StatusBadRequest)
w.Write([]byte("userId is required"))
return
}
fmt.Println("User id " + id)
w.WriteHeader(http.StatusOK)
w.Write([]byte("User id" + id))
}
func main() {
r := mux.NewRouter()
// Routes consist of a path and a handler function.
r.HandleFunc("/ping", YourHandler)
r.HandleFunc("/user/{id}", FindUserById)
// Bind to a port and pass our router in
ch := handlers.CORS(handlers.AllowedOrigins([]string{"*"}))
//log.Fatal(http.ListenAndServe(":8000", ch(r)))
s := http.Server{
Addr: "localhost:8000",
Handler: ch(r),
ReadTimeout: 5 * time.Second,
WriteTimeout: 10 * time.Second,
IdleTimeout: 120 * time.Second,
}
log.Fatal(s.ListenAndServe())
} |
I use this code: package main
import (
"log"
"net/http"
"time"
"github.com/gorilla/mux"
)
func main() {
r := mux.NewRouter()
r.HandleFunc("/", HomeHandler)
r.HandleFunc("/v1/user/{id}", FindUserById())
s := http.Server{
Addr: "localhost:8000",
Handler: r,
ReadTimeout: 5 * time.Second,
WriteTimeout: 10 * time.Second,
IdleTimeout: 120 * time.Second,
}
log.Fatal(s.ListenAndServe())
}
func HomeHandler(w http.ResponseWriter, r *http.Request) {
_, _ = w.Write([]byte("Hello"))
}
func FindUserById() http.HandlerFunc {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
id, ok := vars["id"]
if !ok {
w.WriteHeader(http.StatusBadRequest)
_, _ = w.Write([]byte("userId is required"))
return
}
w.WriteHeader(http.StatusOK)
_, _ = w.Write([]byte(id))
})
} And works fine for me, I imagine the time that passed, you solved this problem, right? |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Describe the bug
I'm trying to return information about a specific user. Somehow the path variable is not recognised
…
Versions
…
Steps to Reproduce
NB
When I replaced the id path variable with a specific nr (e.g. 123) then it returned a 400 error ("userId is required")
Expected behavior
The router recognises the path variable.
Code Snippets
ENDPOINT
/v1/user/{id}
HANDLER
The text was updated successfully, but these errors were encountered: