go语言net/http包

一、net/http介绍

简单来说,go语言的net/http包实现了HTTP客户端和服务端的交互

二、HTTP协议

HTTP是超文本传输协议(HTTP,HyperText Transfer Protocol)的英文缩写,是基于TCP/IP通讯协议之上用来传输HTML和图片文件的应用协议,原本是用来从万维网服务器传输超文本到本地浏览器。它是一个应用层面向对象的协议,优点是简捷、快速,适用于分布式超媒体信息系统。HTTP协议主要工作于B-S架构之上,这个时候浏览器作为HTTP的客户端通过URL向HTTP的服务器(web服务器)发送所有请求,web服务器根据接收到的请求后,向客户端发送响应信息。客户端向服务器请求发送时,需要传送请求方法和路径。路径就是URL,而HTTP常用的请求方法为GET和POST方法,每种方法规定了客户端与服务器通讯方式和数据报文。设计HTTP最初的目的是为了提供一种发布和接收HTML页面的方法。

三、基本的HTTP/HTTPS请求

Get、Head、Post和PostForm函数发出HTTP/HTTPS请求。

1、GET发出HTTP/HTTPS请求。

func Get(url string) (resp *Response, err error)

 Get向指定的URL发出GET请求。如果响应是以下重定向代码之一,Get会跟随重定向(重定向就是,在网页上设置一个约束条件,条件满足,就自动转入到其它网页、网址,比如要输入账号密码点击登入后,正确就进入首页,不正确返回登入页面报个账号或密码登入错误),最多10个重定向:301 (Moved Permanently) 、302 (Found) 、303 (See Other) 、307 (Temporary Redirect)、 308 (Permanent Redirect)

如果重定向过多或存在HTTP协议错误,则返回错误。任何返回的错误都是*url.Error类型的,如果请求超时,那就将url.Error值的Timeout方法报出true。

res, err := http.Get("http://www.google.com/robots.txt")
 if err != nil {
     log.Fatal(err) 
 }
body, err := io.ReadAll(res.Body)
 res.Body.Close() 
if res.StatusCode > 299 {
     log.Fatalf("Response failed with status code: %d and\nbody: %s\n", res.StatusCode, body) }
 if err != nil { 
    log.Fatal(err) 
}
 fmt.Printf("%s", body)//2022/10/09 22:09:28 Get "http://www.google.com/robots.txt": dial tcp 127.0.0.1:80: connectex: No connection could be made because the target machine actively refused it.

2、 Head发出HTTP/HTTPS请求

func (c *Client) Head(url string) (resp *Response, err error)

 Head向指定的URL发出一个Head请求。如果响应是以下重定向代码之一,Head在调用Client的CheckRedirect函数后遵循重定向:301 (Moved Permanently) 、302 (Found)、 303 (See Other)、 307 (Temporary Redirect)、 308 (Permanent Redirect)

用指定的上下文发出请求。Context,使用NewRequestWithContext和Client.Do。

3、Post发出HTTP/HTTPS请求。

func Post(url, contentType string, body io.Reader) (resp *Response, err error)

Post向指定的URL发出Post。调用者应该关闭响应。如果所提供的对象是io.close,则在请求之后关闭。要设置自定义头文件,使用NewRequest和Client.Do。

func main() {
	url := "http://127.0.0.1:9090/post"
	contentType := "application/json"
	data := `{"name":"小王子","age":18}`
	resp, err := http.Post(url, contentType, strings.NewReader(data))
	if err != nil {
		fmt.Printf("post failed, err:%v\n", err)
		return
	}
	defer resp.Body.Close()
	b, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		fmt.Printf("get resp failed, err:%v\n", err)
		return
	}
	fmt.Println(string(b))
}

4、PostForm发出HTTP/HTTPS请求

func (c *Client) PostForm(url string, data url.Values) (resp *Response, err error)

PostForm向指定的URL发出POST,将数据的keys和URL编码values作为请求主体。

Content-Type头被设置为application/x-www-form-urlencoded。要设置其他报头,使用NewRequest和Client.Do。

当err为nil时,resp总是包含一个非nil的resps . body。调用者应该关闭resp。

你可能感兴趣的:(go语言之包,http,服务器,网络)