随心的博客

好记性不如个烂笔头,随心记录!

返回顶部

go net/http包的使用

前言:

Go语言标准库内建提供了net/http包,涵盖了HTTP客户端和服务端的具体实现。

使用net/http包,我们可以很方便地编写HTTP客户端或服务端的程序。

 

正文:

包的文档地址:https://go-zh.org/pkg/net/http

 

net/http 包 使用说明:

注册路由

http.HandleFunc("/index", getHandle)  

 

监听端口和启动服务

http.ListenAndServe("127.0.0.1:80", nil) 

 

请求处理

func getHandle(w http.ResponseWriter, r *http.Request) {

fmt.Println("hello http")      //输出到控制台

w.Write([]byte("hello world")) //输出到浏览器

}

 

示例1:实现简单的web服务

 

func getHandle(w http.ResponseWriter, r *http.Request) {

fmt.Println("hello http")      //输出到控制台

w.Write([]byte("hello world")) //输出到浏览器

}

main:

//注册路由

http.HandleFunc("/index", getHandle)

//监听

http.ListenAndServe("127.0.0.1:80", nil)

 

获取Request请求信息

func getHandle(w http.ResponseWriter, r *http.Request) {

fmt.Println("Method:", r.Method)  //Method: GET
fmt.Println("URL:", r.URL)      //URL: /index
fmt.Println("Body:", r.Body)     //Body: {}
fmt.Println("Header:", r.Header)   

//Header: map[Accept:[text/html,application/xhtml+xml...
fmt.Println("RemoteAddr:", r.RemoteAddr) //RemoteAddr: 127.0.0.1:55895

w.Write([]byte("hello world")) //输出到浏览器

}

去掉火狐浏览器请求两次的处理:

部分火狐浏览器开启了默认对 favicon的请求,这样就会自动请求两次。需要关闭掉。

 

去掉favicon.ico的请求,打开火狐浏览器

about:config

browser.chrome.site_icons  改为  false

 

自定义http服务

type myHandler struct{}

// 实现 ServeHttp接口

func (m myHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {

fmt.Println("hello ServeHTTP!")

w.Write([]byte("hello ServeHTTP!"))

}

 

func main()  {

var handler myHandler

//定义一个Server

server := http.Server{

Addr:    "127.0.0.1:7788",

Handler: handler,

}

err := server.ListenAndServe()

if err != nil {

  fmt.Println("err:", err)

}

}

 

完结

posted @ 2023-04-06 21:59  yangphp  阅读(57)  评论(0编辑  收藏  举报