栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Go语言

HTTP Clients and Servers and Context

Go语言 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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




Go by Example

通过http客户端方法,可向其他服务器的接口发送请求并接收数据。

HTTP服务

首先实现响应方法:

func hello(w http.ResponseWriter, r *http.Request) {
	fmt.Fprintf(w, "hellon")
}
func headers(w http.ResponseWriter, r *http.Request) {
	for name, headers := range r.Header {
		for _, h := range headers {
			fmt.Fprintf(w, "%v: %vn", 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, "hellon")
	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秒内取消访问,上下文会结束执行。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/904673.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号