I have an endpoint like events/{id}
and a handler for it. How can I get {id}
without using Gorilla/Mux. What are the GoLang in-built alternatives that can achieve this? Need to do this without gorilla/Mux or other third-party libraries. I know this can be done with mux.Vars but can't use it here.
Asked
Active
Viewed 340 times
-1
-
2id := strings.TrimPrefix(req.URL.Path, "/events/") – Charlie Tumahai Jan 22 '20 at 06:32
2 Answers
2
If you already managed to direct the traffic to your handler, then you can simply parse the URL path yourself:
func HandlerFunc(w http.ResponseWriter, request *http.Request) {
segments := strings.Split(request.URL.Path, "/")
// If path is /events/id, then segments[2] will have the id
}
Request.URL.Path is already URL decoded, so if your parameters may contain slashes use Request.RequestURI and url.PathUnescape instead:
segments := strings.Split(r.RequestURI, "/")
for i := range segments {
var err error
segments[i], err = url.PathUnescape(segments[i])
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
}

Peter
- 29,454
- 5
- 48
- 60

Burak Serdar
- 46,455
- 3
- 40
- 59
1
You can just get the slice of the string starting after /events/
:
func eventHandler(w http.ResponseWriter, r *http.Request) {
id := r.URL.Path[len("/events/"):]
w.Write([]byte("The ID is " + id))
}
func main() {
http.HandleFunc("/events/", eventHandler)
}

dave
- 62,300
- 5
- 72
- 93