其他分享
首页 > 其他分享> > 小白学标准库之 mux

小白学标准库之 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\n", quality, price)
}

代码实现上:

查看程序实现效果。
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)

写不下去了.....

标签:http,mux,标准,books,小白学,8080,路由,路由器
来源: https://www.cnblogs.com/xingzheanan/p/15506432.html