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

Path-based matching

A path parameter in the URL of an HTTP GET request looks like this:

https://example.org/articles/books/123

Since it is passed after the base URL and API endpoint, in this case https://example.org/articles/, they are called path parameters. In the preceding URL, books and 123 are path parameters. Let us see an example of how to create routes that can consume data supplied as path parameters. Follow these steps: 

  1. Create a new file for our program at the following path:
touch -p $GOPATH/src/github.com/git-user/chapter2/muxRouter/main.go
  1. The idea is to create a new router, mux.NewRouter, and use it as a handler with in-built http.Server. We can attach URL endpoints to handler functions on this router object. The URL endpoints attached can also be regular expressions. The simple program to collect path parameters from a client HTTP request and return back the same looks like this:
package main

import (
"fmt"
"log"
"net/http"
"time"

"github.com/gorilla/mux"
)

func ArticleHandler(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
w.WriteHeader(http.StatusOK)
fmt.Fprintf(w, "Category is: %v\n", vars["category"])
fmt.Fprintf(w, "ID is: %v\n", vars["id"])
}

func main() {
r := mux.NewRouter()
r.HandleFunc("/articles/{category}/{id:[0-9]+}", ArticleHandler)
srv := &http.Server{
Handler: r,
Addr: "127.0.0.1:8000",
WriteTimeout: 15 * time.Second,
ReadTimeout: 15 * time.Second,
}
log.Fatal(srv.ListenAndServe())
}
  1. Now run the server using the following command in a shell:
go run $GOPATH/src/github.com/git-user/chapter2/muxRouter/main.go
  1. Make a curl request from another shell and we can get the output as follows:
curl http://localhost:8000/articles/books/123

Category is: books ID is: 123

This example shows how to match and parse path parameters. There is one more popular way to collect variable information from an HTTP request and that is with query parameters. In the next section, we see how to create routes that match HTTP requests with query parameters.

主站蜘蛛池模板: 吉隆县| 介休市| 双辽市| 绥宁县| 江安县| 香格里拉县| 武平县| 麻城市| 博罗县| 东平县| 苏尼特左旗| 菏泽市| 来安县| 商水县| 牡丹江市| 司法| 襄樊市| 富裕县| 青岛市| 花莲市| 宜君县| 翁牛特旗| 陇川县| 葫芦岛市| 苍山县| 禹州市| 河南省| 定陶县| 拉萨市| 宾阳县| 松滋市| 安阳县| 福清市| 涟水县| 开江县| 霍山县| 南投县| 江永县| 东明县| 三穗县| 进贤县|