Merging other languages
This commit is contained in:
316
en/03.4.md
316
en/03.4.md
@@ -1,181 +1,135 @@
|
||||
# 3.4 Go的http包详解
|
||||
前面小节介绍了Go怎么样实现了Web工作模式的一个流程,这一小节,我们将详细地解剖一下http包,看它到底是怎样实现整个过程的。
|
||||
|
||||
Go的http有两个核心功能:Conn、ServeMux
|
||||
|
||||
## Conn的goroutine
|
||||
与我们一般编写的http服务器不同, Go为了实现高并发和高性能, 使用了goroutines来处理Conn的读写事件, 这样每个请求都能保持独立,相互不会阻塞,可以高效的响应网络事件。这是Go高效的保证。
|
||||
|
||||
Go在等待客户端请求里面是这样写的:
|
||||
|
||||
c, err := srv.newConn(rw)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
go c.serve()
|
||||
|
||||
这里我们可以看到客户端的每次请求都会创建一个Conn,这个Conn里面保存了该次请求的信息,然后再传递到对应的handler,该handler中便可以读取到相应的header信息,这样保证了每个请求的独立性。
|
||||
|
||||
## ServeMux的自定义
|
||||
我们前面小节讲述conn.server的时候,其实内部是调用了http包默认的路由器,通过路由器把本次请求的信息传递到了后端的处理函数。那么这个路由器是怎么实现的呢?
|
||||
|
||||
它的结构如下:
|
||||
|
||||
type ServeMux struct {
|
||||
mu sync.RWMutex //锁,由于请求涉及到并发处理,因此这里需要一个锁机制
|
||||
m map[string]muxEntry // 路由规则,一个string对应一个mux实体,这里的string就是注册的路由表达式
|
||||
hosts bool // 是否在任意的规则中带有host信息
|
||||
}
|
||||
|
||||
下面看一下muxEntry
|
||||
|
||||
type muxEntry struct {
|
||||
explicit bool // 是否精确匹配
|
||||
h Handler // 这个路由表达式对应哪个handler
|
||||
pattern string //匹配字符串
|
||||
}
|
||||
|
||||
接着看一下Handler的定义
|
||||
|
||||
type Handler interface {
|
||||
ServeHTTP(ResponseWriter, *Request) // 路由实现器
|
||||
}
|
||||
|
||||
Handler是一个接口,但是前一小节中的`sayhelloName`函数并没有实现ServeHTTP这个接口,为什么能添加呢?原来在http包里面还定义了一个类型`HandlerFunc`,我们定义的函数`sayhelloName`就是这个HandlerFunc调用之后的结果,这个类型默认就实现了ServeHTTP这个接口,即我们调用了HandlerFunc(f),强制类型转换f成为HandlerFunc类型,这样f就拥有了ServeHTTP方法。
|
||||
|
||||
type HandlerFunc func(ResponseWriter, *Request)
|
||||
|
||||
// ServeHTTP calls f(w, r).
|
||||
func (f HandlerFunc) ServeHTTP(w ResponseWriter, r *Request) {
|
||||
f(w, r)
|
||||
}
|
||||
|
||||
路由器里面存储好了相应的路由规则之后,那么具体的请求又是怎么分发的呢?请看下面的代码,默认的路由器实现了`ServeHTTP`:
|
||||
|
||||
func (mux *ServeMux) ServeHTTP(w ResponseWriter, r *Request) {
|
||||
if r.RequestURI == "*" {
|
||||
w.Header().Set("Connection", "close")
|
||||
w.WriteHeader(StatusBadRequest)
|
||||
return
|
||||
}
|
||||
h, _ := mux.Handler(r)
|
||||
h.ServeHTTP(w, r)
|
||||
}
|
||||
|
||||
如上所示路由器接收到请求之后,如果是`*`那么关闭链接,不然调用`mux.Handler(r)`返回对应设置路由的处理Handler,然后执行`h.ServeHTTP(w, r)`
|
||||
|
||||
也就是调用对应路由的handler的ServerHTTP接口,那么mux.Handler(r)怎么处理的呢?
|
||||
|
||||
func (mux *ServeMux) Handler(r *Request) (h Handler, pattern string) {
|
||||
if r.Method != "CONNECT" {
|
||||
if p := cleanPath(r.URL.Path); p != r.URL.Path {
|
||||
_, pattern = mux.handler(r.Host, p)
|
||||
return RedirectHandler(p, StatusMovedPermanently), pattern
|
||||
}
|
||||
}
|
||||
return mux.handler(r.Host, r.URL.Path)
|
||||
}
|
||||
|
||||
func (mux *ServeMux) handler(host, path string) (h Handler, pattern string) {
|
||||
mux.mu.RLock()
|
||||
defer mux.mu.RUnlock()
|
||||
|
||||
// Host-specific pattern takes precedence over generic ones
|
||||
if mux.hosts {
|
||||
h, pattern = mux.match(host + path)
|
||||
}
|
||||
if h == nil {
|
||||
h, pattern = mux.match(path)
|
||||
}
|
||||
if h == nil {
|
||||
h, pattern = NotFoundHandler(), ""
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
原来他是根据用户请求的URL和路由器里面存储的map去匹配的,当匹配到之后返回存储的handler,调用这个handler的ServeHTTP接口就可以执行到相应的函数了。
|
||||
|
||||
通过上面这个介绍,我们了解了整个路由过程,Go其实支持外部实现的路由器 `ListenAndServe`的第二个参数就是用以配置外部路由器的,它是一个Handler接口,即外部路由器只要实现了Handler接口就可以,我们可以在自己实现的路由器的ServeHTTP里面实现自定义路由功能。
|
||||
|
||||
如下代码所示,我们自己实现了一个简易的路由器
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net/http"
|
||||
)
|
||||
|
||||
type MyMux struct {
|
||||
}
|
||||
|
||||
func (p *MyMux) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
if r.URL.Path == "/" {
|
||||
sayhelloName(w, r)
|
||||
return
|
||||
}
|
||||
http.NotFound(w, r)
|
||||
return
|
||||
}
|
||||
|
||||
func sayhelloName(w http.ResponseWriter, r *http.Request) {
|
||||
fmt.Fprintf(w, "Hello myroute!")
|
||||
}
|
||||
|
||||
func main() {
|
||||
mux := &MyMux{}
|
||||
http.ListenAndServe(":9090", mux)
|
||||
}
|
||||
|
||||
## Go代码的执行流程
|
||||
|
||||
通过对http包的分析之后,现在让我们来梳理一下整个的代码执行过程。
|
||||
|
||||
- 首先调用Http.HandleFunc
|
||||
|
||||
按顺序做了几件事:
|
||||
|
||||
1 调用了DefaultServeMux的HandleFunc
|
||||
|
||||
2 调用了DefaultServeMux的Handle
|
||||
|
||||
3 往DefaultServeMux的map[string]muxEntry中增加对应的handler和路由规则
|
||||
|
||||
- 其次调用http.ListenAndServe(":9090", nil)
|
||||
|
||||
按顺序做了几件事情:
|
||||
|
||||
1 实例化Server
|
||||
|
||||
2 调用Server的ListenAndServe()
|
||||
|
||||
3 调用net.Listen("tcp", addr)监听端口
|
||||
|
||||
4 启动一个for循环,在循环体中Accept请求
|
||||
|
||||
5 对每个请求实例化一个Conn,并且开启一个goroutine为这个请求进行服务go c.serve()
|
||||
|
||||
6 读取每个请求的内容w, err := c.readRequest()
|
||||
|
||||
7 判断handler是否为空,如果没有设置handler(这个例子就没有设置handler),handler就设置为DefaultServeMux
|
||||
|
||||
8 调用handler的ServeHttp
|
||||
|
||||
9 在这个例子中,下面就进入到DefaultServeMux.ServeHttp
|
||||
|
||||
10 根据request选择handler,并且进入到这个handler的ServeHTTP
|
||||
|
||||
mux.handler(r).ServeHTTP(w, r)
|
||||
|
||||
11 选择handler:
|
||||
|
||||
A 判断是否有路由能满足这个request(循环遍历ServerMux的muxEntry)
|
||||
|
||||
B 如果有路由满足,调用这个路由handler的ServeHttp
|
||||
|
||||
C 如果没有路由满足,调用NotFoundHandler的ServeHttp
|
||||
|
||||
## links
|
||||
* [目录](<preface.md>)
|
||||
* 上一节: [Go如何使得web工作](<03.3.md>)
|
||||
* 下一节: [小结](<03.5.md>)
|
||||
# 3.4 Get into http package
|
||||
|
||||
In previous sections, we learned about the work flow of the web and talked a little bit about Go's `http` package. In this section, we are going to learn about two core functions in the `http` package: Conn and ServeMux.
|
||||
|
||||
## goroutine in Conn
|
||||
|
||||
Unlike normal HTTP servers, Go uses goroutines for every job initiated by Conn in order to achieve high concurrency and performance, so every job is independent.
|
||||
|
||||
Go uses the following code to wait for new connections from clients.
|
||||
|
||||
c, err := srv.newConn(rw)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
go c.serve()
|
||||
|
||||
As you can see, it creates a new goroutine for every connection, and passes the handler that is able to read data from the request to the goroutine.
|
||||
|
||||
## Customized ServeMux
|
||||
|
||||
We used Go's default router in previous sections when discussing conn.server, with the router passing request data to a back-end handler.
|
||||
|
||||
The struct of the default router:
|
||||
|
||||
type ServeMux struct {
|
||||
mu sync.RWMutex // because of concurrency, we have to use a mutex here
|
||||
m map[string]muxEntry // router rules, every string mapping to a handler
|
||||
}
|
||||
|
||||
The struct of muxEntry:
|
||||
|
||||
type muxEntry struct {
|
||||
explicit bool // exact match or not
|
||||
h Handler
|
||||
}
|
||||
|
||||
The interface of Handler:
|
||||
|
||||
type Handler interface {
|
||||
ServeHTTP(ResponseWriter, *Request) // routing implementer
|
||||
}
|
||||
|
||||
`Handler` is an interface, but if the function `sayhelloName` didn't implement this interface, then how did we add it as handler? The answer lies in another type called `HandlerFunc` in the `http` package. We called `HandlerFunc` to define our `sayhelloName` method, so `sayhelloName` implemented `Handler` at the same time. It's like we're calling `HandlerFunc(f)`, and the function `f` is force converted to type `HandlerFunc`.
|
||||
|
||||
type HandlerFunc func(ResponseWriter, *Request)
|
||||
|
||||
// ServeHTTP calls f(w, r).
|
||||
func (f HandlerFunc) ServeHTTP(w ResponseWriter, r *Request) {
|
||||
f(w, r)
|
||||
}
|
||||
|
||||
How does the router call handlers after we set the router rules?
|
||||
|
||||
The router calls `mux.handler.ServeHTTP(w, r)` when it receives requests. In other words, it calls the `ServeHTTP` interface of the handlers which have implemented it.
|
||||
|
||||
Now, let's see how `mux.handler` works.
|
||||
|
||||
func (mux *ServeMux) handler(r *Request) Handler {
|
||||
mux.mu.RLock()
|
||||
defer mux.mu.RUnlock()
|
||||
|
||||
// Host-specific pattern takes precedence over generic ones
|
||||
h := mux.match(r.Host + r.URL.Path)
|
||||
if h == nil {
|
||||
h = mux.match(r.URL.Path)
|
||||
}
|
||||
if h == nil {
|
||||
h = NotFoundHandler()
|
||||
}
|
||||
return h
|
||||
}
|
||||
|
||||
The router uses the request's URL as a key to find the corresponding handler saved in the map, then calls handler.ServeHTTP to execute functions to handle the data.
|
||||
|
||||
You should understand the default router's work flow by now, and Go actually supports customized routers. The second argument of `ListenAndServe` is for configuring customized routers. It's an interface of `Handler`. Therefore, any router that implements the `Handler` interface can be used.
|
||||
|
||||
The following example shows how to implement a simple router.
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net/http"
|
||||
)
|
||||
|
||||
type MyMux struct {
|
||||
}
|
||||
|
||||
func (p *MyMux) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
if r.URL.Path == "/" {
|
||||
sayhelloName(w, r)
|
||||
return
|
||||
}
|
||||
http.NotFound(w, r)
|
||||
return
|
||||
}
|
||||
|
||||
func sayhelloName(w http.ResponseWriter, r *http.Request) {
|
||||
fmt.Fprintf(w, "Hello myroute!")
|
||||
}
|
||||
|
||||
func main() {
|
||||
mux := &MyMux{}
|
||||
http.ListenAndServe(":9090", mux)
|
||||
}
|
||||
|
||||
## Go code execution flow
|
||||
|
||||
Let's take a look at the whole execution flow.
|
||||
|
||||
- Call `http.HandleFunc`
|
||||
1. Call HandleFunc of DefaultServeMux
|
||||
2. Call Handle of DefaultServeMux
|
||||
3. Add router rules to map[string]muxEntry of DefaultServeMux
|
||||
- Call `http.ListenAndServe(":9090", nil)`
|
||||
1. Instantiate Server
|
||||
2. Call ListenAndServe method of Server
|
||||
3. Call net.Listen("tcp", addr) to listen to port
|
||||
4. Start a loop and accept requests in the loop body
|
||||
5. Instantiate a Conn and start a goroutine for every request: `go c.serve()`
|
||||
6. Read request data: `w, err := c.readRequest()`
|
||||
7. Check whether handler is empty or not, if it's empty then use DefaultServeMux
|
||||
8. Call ServeHTTP of handler
|
||||
9. Execute code in DefaultServeMux in this case
|
||||
10. Choose handler by URL and execute code in that handler function: `mux.handler.ServeHTTP(w, r)`
|
||||
11. How to choose handler:
|
||||
A. Check router rules for this URL
|
||||
B. Call ServeHTTP in that handler if there is one
|
||||
C. Call ServeHTTP of NotFoundHandler otherwise
|
||||
|
||||
## Links
|
||||
|
||||
- [Directory](preface.md)
|
||||
- Previous section: [How Go works with web](03.3.md)
|
||||
- Next section: [Summary](03.5.md)
|
||||
|
||||
Reference in New Issue
Block a user