前面我们一直说的是如何使用处理器中的 *http.Request 处理用户的请求,下面我
们来说一下如何使用 http.ResponseWriter 来给用户响应
给客户端响应一个字符串
处理器中的代码
func handler(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("你的请求我已经收到"))
}
浏览器中的结果
你的请求我已经收到
响应报文中的内容
HTTP/1.1 200 OK
Date: Fri, 10 Aug 2018 01:09:27 GMT
Content-Length: 27
Content-Type: text/plain; charset=utf-8 //响应的内容的类型
给客户端响应一个 HTML 页面
处理器中的代码
func handler(w http.ResponseWriter, r *http.Request) {
html := `<html>
<head>
<title>测试响应内容为网页</title>
<meta charset="utf-8"/>
</head>
<body>
我是以网页的形式响应过来的!
</body>
</html>`
w.Write([]byte(html))
}
浏览器中的结果
我是以网页的形式响应过来的!
通过在浏览器中右键→查看网页代码发现确实是一个 html 页面
响应报文中的内容
HTTP/1.1 200 OK
Date: Fri, 10 Aug 2018 01:26:58 GMT
Content-Length: 194
Content-Type: text/html; charset=utf-8
给客户端响应 JSON 格式的数据
处理器端代码
func handler(w http.ResponseWriter, r *http.Request) {
//设置响应头中内容的类型
w.Header().Set("Content-Type", "application/json")
user := User{
ID: 1,
Username: "admin",
Password: "123456",
}
//将 user 转换为 json 格式
json, _ := json.Marshal(user)
w.Write(json)
}
浏览器中的结果
{"ID":1,"Username":"admin","Password":"123456"}
响应报文中的内容
HTTP/1.1 200 OK
Content-Type: application/json
Date: Fri, 10 Aug 2018 01:58:02 GMT
Content-Length: 47
让客户端重定向
1) 处理器端代码
func handler(w http.ResponseWriter, r *http.Request) {
//以下操作必须要在 WriteHeader 之前进行
w.Header().Set("Location", "https:www.baidu.com")
w.WriteHeader(302)
}
2) 响应报文中的内容
HTTP/1.1 302 Found
Location: https:www.baidu.c
om
Date: Fri, 10 Aug 2018 01:45:04 GMT
Content-Length: 0
Content-Type: text/plain; charset=utf-8
现在还有问题
不能隔开文件调用,还没改过来