|
在前面的示例中,我们研究了配置简单的 HTTP 服务器。
HTTP 服务器对于演示 |
|
![]()
package main |
|
import ( "fmt" "net/http" "time" ) |
|
func hello(w http.ResponseWriter, req *http.Request) { |
|
|
|
ctx := req.Context()
fmt.Println("server: hello handler started")
defer fmt.Println("server: hello handler ended")
|
|
等待几秒钟,然后再将回复发送给客户端。
这可以模拟服务器正在执行的某些工作。
在工作时,请密切关注 context 的 |
select {
case <-time.After(10 * time.Second):
fmt.Fprintf(w, "hello\n")
case <-ctx.Done():
|
|
context 的 |
err := ctx.Err()
fmt.Println("server:", err)
internalError := http.StatusInternalServerError
http.Error(w, err.Error(), internalError)
}
}
|
func main() { |
|
|
跟前面一样,我们在 |
http.HandleFunc("/hello", hello)
http.ListenAndServe(":8090", nil)
}
|
|
后台运行服务器。 |
$ go run context-in-http-servers.go &
|
|
模拟客户端发出 |
$ curl localhost:8090/hello server: hello handler started ^C server: context canceled server: hello handler ended |
下一个例子: 生成进程