使用HTTP写一个web服务器,浏览器访问时显示hello go,打印客户端发送的请求包(结构体)。
源代码
package main
import (
"fmt"
"net/http"
)
//w,给客户端回复数据
//req,读取客户端发送的数据
func HandleConn(w http.ResponseWriter, req *http.Request) {
fmt.Println("req.Method = ", req.Method) //请求方法
fmt.Println("req.URL = ", req.URL) //请求的地址
fmt.Println("req.Header = ", req.Header) //头部信息,map键值对
fmt.Println("req.Body = ", req.Body) //空
fmt.Println("req.RemoteAddr = ", req.RemoteAddr) //客户端IP和端口
w.Write([]byte("hello go"))
}
func main() {
//注册处理函数,用户连接时,自动调用指定的处理函数
http.HandleFunc("/go.html", HandleConn)
//监听绑定
http.ListenAndServe(":8000", nil)
}
打印输出
浏览器访问http://127.0.0.1:8000/go.html
req.Method = GET
req.URL = /go.html
req.Header = map[Accept:[text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/ /*;q=0.8,application/signed-exchange;v=b3;q=0.9] Accept-Encoding:[gzip, deflate, br] Accept-Language:[zh-CN,zh;q=0.9] Cache-Control:[max-age=0] Connection:[keep-alive] Sec-Ch-Ua:["Google Chrome";v="89", "Chromium";v="89", ";Not A Brand";v="99"] Sec-Ch-Ua-Mobile:[?0] Sec-Fetch-Dest:[document] Sec-Fetch-Mode:[navigate] Sec-Fetch-Site:[none] Sec-Fetch-User:[?1] Upgrade-Insecure-Requests:[1] User-Agent:[Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.72 Safari/537.36]]
req.Body = {}
req.RemoteAddr = 127.0.0.1:15553