小白学标准库之 mux


本文介绍第三方库 gorilla/mux,相比于 Go 自带的 net/http 它能提供更为强大的路由处理功能。

mux 表示 HTTP request multiplexer (HTTP 请求多路复用器),它通过路由器(这里的路由器不是 TCP/IP 中的路由器)实现类 mux.Router 匹配用户请求,并将请求转发到系统注册的路由规则,由相应的规则对请求进行处理。

1. gorilla/mux 使用

首先使用 go get 导入 mux 包:

go get -u github.com/gorilla/mux

实现 mux server:

import (
        "fmt"
        "github.com/gorilla/mux"
        "net/http"
)

func main() {
        r := mux.NewRouter()

        r.HandleFunc("/books/list", ListHandler)
        r.HandleFunc("/books/{quality}/{price}", RecordHandler).Methods("GET")

        http.ListenAndServe(":8080", r)
}

func ListHandler(w http.ResponseWriter, r *http.Request) {
        w.WriteHeader(http.StatusOK)
        fmt.Fprintf(w, "hello, books...")
}

func RecordHandler(w http.ResponseWriter, r *http.Request) {
        vars := mux.Vars(r)

        quality := vars["quality"]
        price := vars["price"]

        w.WriteHeader(http.StatusOK)
        fmt.Fprintf(w, "books quality: %s, price: %s
", quality, price)
}

代码实现上:

  • 调用 mux 包的 NewRouter 构造一个路由器,通过路由器的 HandleFunc 方法建立请求和路由规则的关联。
  • server 端通过 http 包的 ListenAndServe 函数实现了路由器在地址的侦听。访问该地址的 URL 将被转发到路由器中相应的路由规则,并由路由规则处理 URL 请求。
  • mux 包的 Vars 函数解析路由参数。

查看程序实现效果。
server:

[chunqiu@104 mux]$ go run muxUpdater.go

[chunqiu@104 mux]$ netstat -antp | grep 8080
(Not all processes could be identified, non-owned process info
 will not be shown, you would have to be root to see it all.)
tcp6       0      0 :::8080                 :::*                    LISTEN      35739/muxUpdater
tcp6       0      0 ::1:36798               ::1:8080                TIME_WAIT   -

client:

[chunqiu@105 mux]$ curl http://10.159.***.***:8080/books
hello, books...

[chunqiui@105 mux]$ curl http://localhost:8080/books
hello, books...

2. gorilla/mux 实现

简单介绍 mux 包中请求多路复用路由的实现。

2.1 mux.NewRouter

路由器中包括路由切片,切片存储路由规则:

// This will send all incoming requests to the router.
type Router struct {
	// Routes to be matched, in order.
	routes []*Route

	// Routes by name for URL building.
	namedRoutes map[string]*Route
}

2.2 HandlerFunc

...
r.NewRoute().Path(path).HandlerFunc(f)

写不下去了.....

芝兰生于空谷,不以无人而不芳。
原文地址:https://www.cnblogs.com/xingzheanan/p/15506432.html