第十章、go语言网络编程,35_go实现http服务器

使用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
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值