本文主要是介绍HTTP Clients and Servers and Context,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
HTTP请求
resp, err := http.Get("http://gobyexample.com")
if err != nil {panic(err)
}
defer resp.Body.Close()
fmt.Println("Response status:", resp.Status)
scanner := bufio.NewScanner(resp.Body)
for i := 0; scanner.Scan() && i < 5; i++ {fmt.Println(scanner.Text())
}
if err := scanner.Err(); err != nil {panic(err)
}
Response status: 200 OK
<!DOCTYPE html>
<html>
<head>
<meta charset=“utf-8”>
<title>Go by Example</title>
通过http客户端方法,可向其他服务器的接口发送请求并接收数据。
HTTP服务
首先实现响应方法:
func hello(w http.ResponseWriter, r *http.Request) {fmt.Fprintf(w, "hello\n")
}
func headers(w http.ResponseWriter, r *http.Request) {for name, headers := range r.Header {for _, h := range headers {fmt.Fprintf(w, "%v: %v\n", name, h)}}fmt.Fprintf(w, "%v", r.Header)
}
然后实现监听方法:
http.HandleFunc("/hello", hello)
http.HandleFunc("/headers", headers)
http.ListenAndServe(":8090", nil)
编译并运行程序:
% ./http-servers
打开浏览器,访问地址:http://localhost:8090/hello
展示内容如下:
hello
访问地址:http://localhost:8090/headers
展示内容如下:
Upgrade-Insecure-Requests: 1
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,/;q=0.8
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/15.4 Safari/605.1.15
Accept-Language: zh-cn
Accept-Encoding: gzip, deflate
Connection: keep-alive
上下文
首先实现响应方法:
func hello(w http.ResponseWriter, r *http.Request) {ctx := r.Context()fmt.Println("server: hello handler started")defer fmt.Println("server: hello handler ended")select {case <-time.After(10 * time.Second):fmt.Fprintf(w, "hello\n")case <-ctx.Done():err := ctx.Err()fmt.Println("server:", err)internalError := http.StatusInternalServerErrorhttp.Error(w, err.Error(), internalError)}
}
然后实现监听方法:
http.HandleFunc("/hello", hello)
http.ListenAndServe(":8090", nil)
编译并运行程序:
% ./context-in-http-servers
打开浏览器,访问地址并等待10秒:http://localhost:8090/hello
展示内容如下:
hello
命令行输出:
server: hello handler started
server: hello handler ended
访问地址并在10秒内取消访问,命令行输出:
server: hello handler started
server: context canceled
server: hello handler ended
从代码中可以看出,select
会等待time.After
或ctx.Done
。如果等待10秒,内容会展示到浏览器;如果10秒内取消访问,上下文会结束执行。
这篇关于HTTP Clients and Servers and Context的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!