Query-based matching

Query parameters are those that get passed along with the URL. This is what we commonly see in a REST GET request. Gorilla Mux can create a route for matching a URL with the given query parameters:

http://localhost:8000/articles/?id=123&category=books

Let us add functionality to our program:

// Add this in your main program
r := mux.NewRouter()
r.HandleFunc("/articles", QueryHandler)
r.Queries("id", "category")

It limits the query with the preceding URL. The id and category match with the Queries list. Empty values are allowed for parameters. QueryHandler looks like this. You can use request.URL.Query() to obtain query parameters in your handler function:

func QueryHandler(w http.ResponseWriter, r *http.Request){
queryParams := r.URL.Query()
w.WriteHeader(http.StatusOK)
fmt.Fprintf(w, "Got parameter id:%s! ", queryParams["id"])
fmt.Fprintf(w, "Got parameter category:%s!", queryParams["category"])
}
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.117.138.178