Merging other languages
This commit is contained in:
172
en/03.3.md
172
en/03.3.md
@@ -1,87 +1,85 @@
|
||||
# 3.3 Go如何使得Web工作
|
||||
前面小节介绍了如何通过Go搭建一个Web服务,我们可以看到简单应用一个net/http包就方便的搭建起来了。那么Go在底层到底是怎么做的呢?万变不离其宗,Go的Web服务工作也离不开我们第一小节介绍的Web工作方式。
|
||||
|
||||
## web工作方式的几个概念
|
||||
|
||||
以下均是服务器端的几个概念
|
||||
|
||||
Request:用户请求的信息,用来解析用户的请求信息,包括post、get、cookie、url等信息
|
||||
|
||||
Response:服务器需要反馈给客户端的信息
|
||||
|
||||
Conn:用户的每次请求链接
|
||||
|
||||
Handler:处理请求和生成返回信息的处理逻辑
|
||||
|
||||
## 分析http包运行机制
|
||||
|
||||
如下图所示,是Go实现Web服务的工作模式的流程图
|
||||
|
||||

|
||||
|
||||
图3.9 http包执行流程
|
||||
|
||||
1. 创建Listen Socket, 监听指定的端口, 等待客户端请求到来。
|
||||
|
||||
2. Listen Socket接受客户端的请求, 得到Client Socket, 接下来通过Client Socket与客户端通信。
|
||||
|
||||
3. 处理客户端的请求, 首先从Client Socket读取HTTP请求的协议头, 如果是POST方法, 还可能要读取客户端提交的数据, 然后交给相应的handler处理请求, handler处理完毕准备好客户端需要的数据, 通过Client Socket写给客户端。
|
||||
|
||||
这整个的过程里面我们只要了解清楚下面三个问题,也就知道Go是如何让Web运行起来了
|
||||
|
||||
- 如何监听端口?
|
||||
- 如何接收客户端请求?
|
||||
- 如何分配handler?
|
||||
|
||||
前面小节的代码里面我们可以看到,Go是通过一个函数`ListenAndServe`来处理这些事情的,这个底层其实这样处理的:初始化一个server对象,然后调用了`net.Listen("tcp", addr)`,也就是底层用TCP协议搭建了一个服务,然后监控我们设置的端口。
|
||||
|
||||
下面代码来自Go的http包的源码,通过下面的代码我们可以看到整个的http处理过程:
|
||||
|
||||
func (srv *Server) Serve(l net.Listener) error {
|
||||
defer l.Close()
|
||||
var tempDelay time.Duration // how long to sleep on accept failure
|
||||
for {
|
||||
rw, e := l.Accept()
|
||||
if e != nil {
|
||||
if ne, ok := e.(net.Error); ok && ne.Temporary() {
|
||||
if tempDelay == 0 {
|
||||
tempDelay = 5 * time.Millisecond
|
||||
} else {
|
||||
tempDelay *= 2
|
||||
}
|
||||
if max := 1 * time.Second; tempDelay > max {
|
||||
tempDelay = max
|
||||
}
|
||||
log.Printf("http: Accept error: %v; retrying in %v", e, tempDelay)
|
||||
time.Sleep(tempDelay)
|
||||
continue
|
||||
}
|
||||
return e
|
||||
}
|
||||
tempDelay = 0
|
||||
c, err := srv.newConn(rw)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
go c.serve()
|
||||
}
|
||||
}
|
||||
|
||||
监控之后如何接收客户端的请求呢?上面代码执行监控端口之后,调用了`srv.Serve(net.Listener)`函数,这个函数就是处理接收客户端的请求信息。这个函数里面起了一个`for{}`,首先通过Listener接收请求,其次创建一个Conn,最后单独开了一个goroutine,把这个请求的数据当做参数扔给这个conn去服务:`go c.serve()`。这个就是高并发体现了,用户的每一次请求都是在一个新的goroutine去服务,相互不影响。
|
||||
|
||||
那么如何具体分配到相应的函数来处理请求呢?conn首先会解析request:`c.readRequest()`,然后获取相应的handler:`handler := c.server.Handler`,也就是我们刚才在调用函数`ListenAndServe`时候的第二个参数,我们前面例子传递的是nil,也就是为空,那么默认获取`handler = DefaultServeMux`,那么这个变量用来做什么的呢?对,这个变量就是一个路由器,它用来匹配url跳转到其相应的handle函数,那么这个我们有设置过吗?有,我们调用的代码里面第一句不是调用了`http.HandleFunc("/", sayhelloName)`嘛。这个作用就是注册了请求`/`的路由规则,当请求uri为"/",路由就会转到函数sayhelloName,DefaultServeMux会调用ServeHTTP方法,这个方法内部其实就是调用sayhelloName本身,最后通过写入response的信息反馈到客户端。
|
||||
|
||||
|
||||
详细的整个流程如下图所示:
|
||||
|
||||

|
||||
|
||||
图3.10 一个http连接处理流程
|
||||
|
||||
至此我们的三个问题已经全部得到了解答,你现在对于Go如何让Web跑起来的是否已经基本了解呢?
|
||||
|
||||
|
||||
## links
|
||||
* [目录](<preface.md>)
|
||||
* 上一节: [GO搭建一个简单的web服务](<03.2.md>)
|
||||
* 下一节: [Go的http包详解](<03.4.md>)
|
||||
# 3.3 How Go works with web
|
||||
|
||||
We learned to use the `net/http` package to build a simple web server in the previous section, and all those working principles are the same as those we will talk about in the first section of this chapter.
|
||||
|
||||
## Concepts in web principles
|
||||
|
||||
Request: request data from users, including POST, GET, Cookie and URL.
|
||||
|
||||
Response: response data from server to clients.
|
||||
|
||||
Conn: connections between clients and servers.
|
||||
|
||||
Handler: Request handling logic and response generation.
|
||||
|
||||
## http package operating mechanism
|
||||
|
||||
The following picture shows the work flow of a Go web server.
|
||||
|
||||

|
||||
|
||||
Figure 3.9 http work flow
|
||||
|
||||
1. Create a listening socket, listen to a port and wait for clients.
|
||||
2. Accept requests from clients.
|
||||
3. Handle requests, read HTTP header. If the request uses POST method, read data in the message body and pass them to handlers. Finally, socket returns response data to clients.
|
||||
|
||||
Once we know the answers to the three following questions, it's easy to know how the web works in Go.
|
||||
|
||||
- How do we listen to a port?
|
||||
- How do we accept client requests?
|
||||
- How do we allocate handlers?
|
||||
|
||||
In the previous section we saw that Go uses `ListenAndServe` to handle these steps: initialize a server object, call `net.Listen("tcp", addr)` to setup a TCP listener and listen to a specific address and port.
|
||||
|
||||
Let's take a look at the `http` package's source code.
|
||||
|
||||
//Build version go1.1.2.
|
||||
func (srv *Server) Serve(l net.Listener) error {
|
||||
defer l.Close()
|
||||
var tempDelay time.Duration // how long to sleep on accept failure
|
||||
for {
|
||||
rw, e := l.Accept()
|
||||
if e != nil {
|
||||
if ne, ok := e.(net.Error); ok && ne.Temporary() {
|
||||
if tempDelay == 0 {
|
||||
tempDelay = 5 * time.Millisecond
|
||||
} else {
|
||||
tempDelay *= 2
|
||||
}
|
||||
if max := 1 * time.Second; tempDelay > max {
|
||||
tempDelay = max
|
||||
}
|
||||
log.Printf("http: Accept error: %v; retrying in %v", e, tempDelay)
|
||||
time.Sleep(tempDelay)
|
||||
continue
|
||||
}
|
||||
return e
|
||||
}
|
||||
tempDelay = 0
|
||||
c, err := srv.newConn(rw)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
go c.serve()
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
How do we accept client requests after we begin listening to a port? In the source code, we can see that `srv.Serve(net.Listener)` is called to handle client requests. In the body of the function there is a `for{}`. It accepts a request, creates a new connection then starts a new goroutine, passing the request data to the `go c.serve()` goroutine. This is how Go supports high concurrency, and every goroutine is independent.
|
||||
|
||||
How do we use specific functions to handle requests? `conn` parses request `c.ReadRequest()` at first, then gets the corresponding handler: `handler := c.server.Handler` which is the second argument we passed when we called `ListenAndServe`. Because we passed `nil`, Go uses its default handler `handler = DefaultServeMux`. So what is `DefaultServeMux` doing here? Well, its the router variable which can call handler functions for specific URLs. Did we set this? Yes, we did. We did this in the first line where we used `http.HandleFunc("/", sayhelloName)`. We're using this function to register the router rule for the "/" path. When the URL is `/`, the router calls the function `sayhelloName`. DefaultServeMux calls ServerHTTP to get handler functions for different paths, calling `sayhelloName` in this specific case. Finally, the server writes data and responds to clients.
|
||||
|
||||
Detailed work flow:
|
||||
|
||||

|
||||
|
||||
Figure 3.10 Work flow of handling an HTTP request
|
||||
|
||||
I think you should know how Go runs web servers now.
|
||||
|
||||
## Links
|
||||
|
||||
- [Directory](preface.md)
|
||||
- Previous section: [Build a simple web server](03.2.md)
|
||||
- Next section: [Get into http package](03.4.md)
|
||||
|
||||
Reference in New Issue
Block a user