官术网_书友最值得收藏!

Query-based matching

Query parameters are variables that get passed along with the URL in an HTTP request. This is what we commonly see in a REST GET request. The gorilla/mux route can match and collect query parameters. See this following URL, for example:

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

It has id and category as query parameters. All query parameters begin after the ? character.

Let us modify our copy of our previous example into a new one with the name queryParameters/main.go. Modify the route object to point to a new handler called QueryHandler, like this:

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

In QueryHandler, we can use request.URL.Query() to obtain query parameters from the HTTP request. QueryHandler looks like this:

// QueryHandler handles the given query parameters
func QueryHandler(w http.ResponseWriter, r *http.Request) {
queryParams := r.URL.Query()
w.WriteHeader(http.StatusOK)
fmt.Fprintf(w, "Got parameter id:%s!\n", queryParams["id"][0])
fmt.Fprintf(w, "Got parameter category:%s!", queryParams["category"][0])
}

This program is similar to the previous example, but processes query parameters instead of path parameters.

Run the new program:

go run $GOPATH/src/github.com/git-user/chapter2/queryParameters/main.go

Fire a curl request in this format in a Terminal:

curl -X GET http://localhost:8000/articles\?id\=1345\&category\=birds

We need to escape special characters in the shell. If it is in the browser, there is no problem of escaping. The output looks like this:

Got parameter id:1345! 
Got parameter category:birds!

The r.URL.Query() function returns a map with all the parameter and value pairs. They are basically strings and, in order to use them in our program logic, we need to convert the number strings to integers. We can use Go's strconv package to convert a string to an integer, and vice versa.

We have used http.StatusOK to write a successful HTTP response. Similarly, use appropriate status codes for different REST operations. For example, 404 – Not found, 500 – Server error, and so on.
主站蜘蛛池模板: 饶平县| 北票市| 惠来县| 邻水| 连城县| 北安市| 徐水县| 沈阳市| 太白县| 卫辉市| 东乌珠穆沁旗| 焉耆| 山东| 大足县| 杭州市| 云龙县| 收藏| 溧水县| 志丹县| 泾阳县| 宁河县| 任丘市| 嘉禾县| 临潭县| 邳州市| 龙江县| 三亚市| 灵武市| 左贡县| 尼玛县| 炎陵县| 安阳市| 忻州市| 佛教| 乌鲁木齐市| 海淀区| 土默特左旗| 开原市| 工布江达县| 桃江县| 克东县|