golang http request

王林
Release: 2023-05-27 13:16:39
Original
1442 people have browsed it

Go language is a fast, reliable, and concise programming language that is favored for its excellent concurrency and network programming capabilities. When doing network programming, HTTP requests are an inevitable part of the program development process. This article will introduce how to make HTTP requests in Go language.

1. Import and net/http package

HTTP requests and responses are implemented in Go language through the net/http package. Import the package:

import (
    "net/http"
)
Copy after login

2. GET request

The following code shows how to use http.Get() to send a GET request:

resp, err := http.Get("https://www.google.com")
if err != nil {
    //处理错误
}
defer resp.Body.Close()

body, err := ioutil.ReadAll(resp.Body)
if err != nil {
    //处理错误
}

fmt.Println(string(body))
Copy after login

When running this code, A GET request will be sent to https://www.google.com and the HTML source code of the website will be returned. The Get() function returns a *http.Response type pointer, which contains all HTTP response information (including status code, response headers, response body, etc.). We use the defer statement to ensure that the response body is closed when the function returns.

3. POST request

The following code shows how to use the http.Post() method to send a POST request:

values := map[string]string{
    "name":  "test",
    "email": "test@gmail.com",
}

data := url.Values{}
for key, value := range values {
    data.Set(key, value)
}

url := "https://example.com/api"
req, err := http.NewRequest("POST", url, strings.NewReader(data.Encode()))
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")

if err != nil {
    //处理错误
}

client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
    //处理错误
}
defer resp.Body.Close()

body, err := ioutil.ReadAll(resp.Body)
if err != nil {
    //处理错误
}

fmt.Println(string(body))
Copy after login

In this way, we use the http.NewRequest() function to create POST request, then set the request header and request body. When sending a request we use the htt.Client() object and send the request to the specified URL. When the code is finished running, regardless of success or failure, be sure to close http.Response.Body.

4. PUT request

Similar to the POST request, the PUT request can also be sent using http.NewRequest() in the Go language:

values := "{"name":"test","email":"test@gmail.com"}"
url := "https://example.com/api"
req, err := http.NewRequest("PUT", url, bytes.NewBuffer([]byte(values)))

if err != nil {
    //处理错误
}

client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
    //处理错误
}
defer resp.Body.Close()

body, err := ioutil.ReadAll(resp.Body)
if err != nil {
    //处理错误
}

fmt.Println(string(body))
Copy after login

Bytes are used here. NewBuffer() function to convert variable values ​​into a buffer and put it in Request.Body.

5. DELETE request

Similar to the GET request, the DELETE request can also be sent by using the http.Get() function:

url := "https://example.com/api?id=123"
req, err := http.NewRequest("DELETE", url, nil)

if err != nil {
    //处理错误
}

client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
    //处理错误
}
defer resp.Body.Close()

body, err := ioutil.ReadAll(resp.Body)
if err != nil {
    //处理错误
}

fmt.Println(string(body))
Copy after login

The url parameters here include The ID of the resource we want to delete. Note that when parameters are passed to the URL, URL encoding is required to ensure that the parameter values ​​are passed correctly.

Conclusion

HTTP requests and responses in the Go language are implemented through the net/http package. This article describes how to use this package to send GET, POST, PUT, and DELETE requests, and explains how to handle the results of the responses. HTTP is the foundation of modern web applications, and understanding this can also help extend your application to support HTTP requests and responses.

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

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!