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
Go by Example
通过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.StatusInternalServerError
http.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秒内取消访问,上下文会结束执行。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)