go get -u github.com/gorilla/mux
默认的http包无法处理复杂的请求路由,例如从url中拆分出参数。该第三方包可方便的处理。
r := mux.NewRouter()
该路由接收http请求,并传递给注册的请求处理者。
r.HandleFunc("/books/{title}/page/{page}", func(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
title := vars["title"]
page := vars["page"]
fmt.Fprintf(w, "You've requested the book: %s on page %s\n", title, page)
})
/books/{title}/page/{page}包含两个动态字段:title和page。链接*/books/go-programming-blueprint/page/10会被分析出两个参数,go-programming-blueprint被分配到title*,10被分配到page。
mux.Vars
将字段从url中分析出,并以映射类型返回。
http.ListenAndServe(":8090", r)
监听指定端口,启用http服务和指定路由。
package main
import (
"fmt"
"net/http"
"github.com/gorilla/mux"
)
func main() {
r := mux.NewRouter()
r.HandleFunc("/books/{title}/page/{page}", func(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
title := vars["title"]
page := vars["page"]
fmt.Fprintf(w, "You've requested the book: %s on page %s\n", title, page)
})
http.ListenAndServe(":8090", r)
}