sxp
sxp

Reputation: 253

Function handler GoLang using Standard Library

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.

Upvotes: -1

Views: 433

Answers (2)

Burak Serdar
Burak Serdar

Reputation: 51592

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
    }
}

Upvotes: 2

dave
dave

Reputation: 64687

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)
}

Upvotes: 1

Related Questions