Golang学习笔记之网络包nethttp

xiaoxiao2022-06-12  34

Get访问网址,获取响应,可得到header,status,statuscode等

const URL = "127.0.0.1:8080" Resp, err := http.GET(URL)

如果要添加cookie,添加头部参数,用http.Do(req)

//新建一个请求对象 Req,err := http.NewRequest(“GET”,”URL”,strings.NewReader(“mobile=xxxxxxxxxx&isRemberPwd=1 ”)) //设置请求头 Req.Header.Set("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8" ) //进行访问 Resp,err := http.Do(req)

Go http 服务端 Go处理http请求主要跟两个东西相关, URL路由注册 ServerMux URL处理函数 Handler (之前学习过python的django框架,所以能够理解,就是django里的urlconf跟view)

Handler 负责输出http响应等头跟正文,任何满足http.Handler接口对象都可作为一个处理器,通俗的说,对象只要有如下签名的ServerHTTP方法即可

ServerHTTP(http.ResponseWriter,*http.Request)

Golang内置来几个函数作为处理器FileServer,NotFoundHandler 和 RedirectHandler

例子

//创建一个空的url路由 mux := http.NewServerMux() //创建一个新的处理器,该处理器将收到的所有请求都执行重定向到url去 Rh := http.RedirectHandler(url,code) //将创建的处理器注册到url路由中 Mix.Handler(“/“,Rh) //建立新的服务器,并通过ListenAndServer函数监听所有请求,并传入mux进行匹配。 http.ListenAndServer(“:port”, mux)

ListenAndServer接收两个参数,adds string, handler Handler,但是我们传入的是一个mux,为ServerMux类型,为什么没出错?因为ServerMux实现了ServerHTTP方法,故也可以视为Handler,即接口的泛型

函数也能作为方法的接收者??答案是可以,可以用闭包

自定义处理器

type timeHandler struct { format string } func (th *timeHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { tm := time.Now().Format(th.format) w.Write([]byte("The time is: " + tm)) }

timeHandler 实现了ServeHTTP方法,可以视为ServerHTTP对象。即可当作处理器

让函数也能变成处理器,通过http.HandlerFunc类型来让一个常规函数满足作为一个Handler接口的条件。

任何函数有(http.ResponseWriter, *http.Request)参数的,都能通过http.HandlerFunc(MyFunc)将其转化为HandlerFunc类型,转称该类型后,HandlerFunc内置了ServerHTTP方法,故MyFunc就成为了处理器

func timeHandler(w http.ResponseWriter, r *http.Request) { tm := time.Now().Format(time.RFC1123) w.Write([]byte("The time is: " + tm)) } //将timeHandler转化为http.HandlerFunc类型 th := http.HandlerFunc(timeHandler) 然后就可以注册到url路由里了

有一个快捷的方法,mux里有个函数可以将转换跟注册放到一个函数里完成

mux.HandlerFunc(“/”,MyFunc)

但是这种方式不适合传递参数 有一种解决办法是将该函数写成闭包

func timeHandler(format string) http.Handler { fn := func(w http.ResponseWriter, r *http.Request) { tm := time.Now().Format(format) w.Write([]byte("The time is: " + tm)) } return http.HandlerFunc(fn) }

该闭包返回http.HandlerFunc()处理过后的处理器函数。

也可以这么写-先转换再返回

func timeHandler(format string) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { tm := time.Now().Format(format) w.Write([]byte("The time is: " + tm)) }) }

或者这样返回的时候再转换

func timeHandler(format string) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { tm := time.Now().Format(format) w.Write([]byte("The time is: " + tm)) } }

DefaultServerMux 当我们不通过http.NewServerMux()创建mux的时候(不显式声明mux),会使用默认的DefaultServerMux,它随net/http包初始化而初始化。使用默认mux的流程

th := http.HandlerFunc(timeHandler) http.Handle("/time", th) log.Println("Listening...") http.ListenAndServe(":3000", nil)

如有错误,欢迎指正交流

转载请注明原文地址: https://www.6miu.com/read-4932227.html

最新回复(0)