Golang is a fast, simple, and secure programming language that is widely used for web application development. Initiating HTTP requests in Golang is a very common task. This article will introduce how to initiate HTTP requests in Golang.
The following is a simple example:
package main import ( "fmt" "net/http" ) func main() { response, err := http.Get("https://www.google.com") if err != nil { fmt.Println("请求错误:", err) return } defer response.Body.Close() fmt.Println("响应状态码:", response.Status) }
In this example, we use the http.Get() method to initiate an HTTP GET request and obtain the response. It should be noted that the response Body must be closed after use.
The following is an example:
package main import ( "fmt" "net/http" "net/url" ) func main() { formData := url.Values{ "username": {"admin"}, "password": {"123456"}, } response, err := http.PostForm("http://localhost:8080/login", formData) if err != nil { fmt.Println("请求错误:", err) return } defer response.Body.Close() fmt.Println("响应状态码:", response.Status) }
In this example, we use the http.PostForm() method to send a POST request with form data and get the response. It should be noted that form data needs to be encapsulated using the url.Values type.
The following is an example:
package main import ( "fmt" "net/http" ) func main() { request, err := http.NewRequest("GET", "https://www.google.com", nil) if err != nil { fmt.Println("创建请求失败:", err) return } request.Header.Set("X-Custom-Header", "Golang") client := &http.Client{} response, err := client.Do(request) if err != nil { fmt.Println("请求错误:", err) return } defer response.Body.Close() fmt.Println("响应状态码:", response.Status) }
In this example, we use the http.NewRequest() method to create a custom request and set a custom request head. It should be noted that we use the http.Client{} type to send requests.
The following is an example of using the httpclient library to send an HTTP request:
package main import ( "fmt" "github.com/mozillazg/request" ) func main() { client := request.New() response, err := client.Get("https://www.google.com") if err != nil { fmt.Println("请求错误:", err) return } defer response.Body.Close() fmt.Println("响应状态码:", response.Status) }
In this example, we use the httpclient library to create an HTTP client and send a GET ask.
Summary
Initiating HTTP requests in Golang is a very common task. The net/http package in the Golang standard library already provides HTTP client and server implementations, which can meet most needs. For more complex requirements, we can use third-party libraries to improve code readability and performance. When writing HTTP requests, you need to pay attention to some details. For example: the response Body must be closed after use, and the form data needs to be encapsulated using the url.Values type, etc.
The above is the detailed content of golang initiates a request. For more information, please follow other related articles on the PHP Chinese website!