go语言进行http请求和处理http响应的几种方式

发送http请求的方式
方法一:使用http.Get、http.Post
func Get() {
	u := "http://localhost:8080"
	v := make(url.Values)
	v["name"] = []string{"jim"}
	v["age"] = []string{"12"}
	
	// v.Encode = "name=jee&age=12"
	res, err := http.Get(u + "?" + v.Encode())
	if err != nil {
		fmt.Println("req", err.Error())
		return
	}
	
	defer res.Body.Close()
}
方法二:通过http.Client和http.NewRequest
func Post(){
	cli := &http.Client{
		Timeout: 30 * time.Second,
	}
	
	// Post的body是一个io.Reader,url.Values、bytes.Buffer等都实现了io.Reader
	// bytes.Buffer使用方法:
	// a := new(bytes.Buffer)
	// json.NewEncoder(a).Encode(map[string]string{"name": "gee"})
	body := strings.NewReader(`{'name':'joe','age':12}`)
	req, err := http.NewRequest("GET", u+"?"+v.Encode(), body)
	if err != nil {
		fmt.Println("New request error:", err.Error())
		return
	}
	req.Header.Set("Content-Type", "application/json")

	resp, err := cli.Do(req)
	if err != nil {
		fmt.Println("err ", err.Error())
	}
	
	defer resp.Body.Close()
}
处理http响应的方式
方法一:使用ioutil.ReadAll
func Read(res *http.Response) {
	// 注意:不能对res.Body重复读取,第二次将读不到信息
	//1. 通过ioutil.ReadAll
	content, err := ioutil.ReadAll(res.Body)
	if err != nil {
		fmt.Println("-----res err-", err.Error())
		return
	}
	fmt.Println(string(content))
}
方法二:如果返回值是json,也可以这样读
func Read(res *http.Response) {
	content := map[string]interface{}{}
	err = json.NewDecoder(res.Body).Decode(&content)
	if err != nil {
		fmt.Println("err", err.Error())
		return
	}
	fmt.Println(content)
方法三:使用bytes.Buffer
func Read(res *http.Response) {
	content := new(bytes.Buffer)
	io.Copy(content, res.Body)
	fmt.Println(content.String())
}
  • 3
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
HTTP是一种基于请求-响应模式的协议,用于客户端和服务器之间的通信。在Go语言中,通过使用标准库中的`net/http`包来实现HTTP服务器和客户端。 HTTP服务器的实现主要包括以下几个步骤: 1. 创建一个HTTP服务器:使用`http.NewServeMux()`函数创建一个HTTP请求路由器。 ```go mux := http.NewServeMux() ``` 2. 定义HTTP处理函数:定义处理HTTP请求的函数,这些函数需要实现`http.Handler`接口,即拥有`ServeHTTP(ResponseWriter, *Request)`方法。 ```go func helloHandler(w http.ResponseWriter, r *http.Request) { fmt.Fprintln(w, "Hello, World!") } ``` 3. 绑定HTTP处理函数:使用`mux.Handle(pattern, handler)`函数将HTTP请求路由器与HTTP处理函数绑定。 ```go mux.Handle("/", http.HandlerFunc(helloHandler)) ``` 4. 启动HTTP服务器:使用`http.ListenAndServe(addr, handler)`函数启动HTTP服务器,其中`addr`是服务器监听的地址,`handler`是HTTP请求路由器。 ```go http.ListenAndServe(":8080", mux) ``` 完整的HTTP服务器实现代码如下: ```go package main import ( "fmt" "net/http" ) func helloHandler(w http.ResponseWriter, r *http.Request) { fmt.Fprintln(w, "Hello, World!") } func main() { mux := http.NewServeMux() mux.Handle("/", http.HandlerFunc(helloHandler)) http.ListenAndServe(":8080", mux) } ``` HTTP客户端的实现主要包括以下几个步骤: 1. 创建一个HTTP客户端:使用`http.Client`结构体创建一个HTTP客户端对象。 ```go client := &http.Client{} ``` 2. 创建一个HTTP请求:使用`http.NewRequest(method, url, body)`函数创建一个HTTP请求对象,其中`method`是HTTP请求方法,`url`是请求的URL,`body`是请求的消息体。 ```go req, err := http.NewRequest(http.MethodGet, "http://example.com", nil) ``` 3. 发送HTTP请求:使用HTTP客户端的`Do(req *http.Request)`方法发送HTTP请求,并返回HTTP响应对象。 ```go resp, err := client.Do(req) ``` 4. 处理HTTP响应:使用HTTP响应对象的方法处理HTTP响应,如读取响应内容、获取响应头等。 完整的HTTP客户端实现代码如下: ```go package main import ( "fmt" "io/ioutil" "net/http" ) func main() { client := &http.Client{} req, err := http.NewRequest(http.MethodGet, "http://example.com", nil) if err != nil { panic(err) } resp, err := client.Do(req) if err != nil { panic(err) } defer resp.Body.Close() body, err := ioutil.ReadAll(resp.Body) if err != nil { panic(err) } fmt.Println(string(body)) } ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值