Home >Backend Development >Golang >How to write http request in golang

How to write http request in golang

尚
Original
2020-01-14 17:35:563835browse

How to write http request in golang

How to write http request in golang:

Method 1: Use http.Newrequest

to generate http first. client -> Regenerate http.request -> Then submit the request: client.Do(request) -> Process the returned result. You can set some specific parameters for each step of the process. The following is the simplest and most basic example. :

//question ???将stdout重定向为response信息???
package main

import (
	"fmt"
	"io"
	"net/http"
	"os"
)

func main() {
    //生成client 参数为默认
	client := &http.Client{}
	
	//生成要访问的url
	url := "http://www.baidu.com"
	    
	//提交请求
	reqest, err := http.NewRequest("GET", url, nil)
	
	if err != nil {
		panic(err)
	}
	
	//处理返回结果
	response, _ := client.Do(reqest)
   
   //将结果定位到标准输出 也可以直接打印出来 或者定位到其他地方进行相应的处理
	stdout := os.Stdout
	_, err = io.Copy(stdout, response.Body)
   
   //返回的状态码
	status := response.StatusCode

	fmt.Println(status)

}

Method 2: Generate client first, and then use client.get/post..

The client structure itself also has some methods for sending api, such as client.get, client.post, client.postform..etc. Basically covers the main types of http requests. Usually, this is enough without any special configuration. In fact, the client's get or post method is also an encapsulation of the http.Newerequest method, and req.Header is also added in it. .Set("Content-Type", bodyType) is also ok for general use.

For more go language knowledge, please pay attention to the go language tutorial column on the PHP Chinese website.

The above is the detailed content of How to write http request in golang. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn