Home > Backend Development > Golang > How to make network requests in Golang

How to make network requests in Golang

PHPz
Release: 2023-03-30 10:04:37
Original
1531 people have browsed it

Golang is an efficient programming language that is widely used in web application and network service development. In network services, requests are a very important part. This article will introduce how to make network requests in Golang, including GET requests and POST requests.

  1. GET request

GET request is one of the most commonly used network request methods. It is used to get data from the server. It is usually used to get files such as HTML, CSS and JavaScript. It can also be used to get API data. In Golang, GET requests can be easily made using the Get method provided by the net/http package in the standard library. Here is a simple example:

package main

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

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

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

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

In the above code, we use the http.Get method to send a GET request to https://www.example.com/ and read the server's response. If an error occurs, we will handle it with special handling. Additionally, we use a defer statement to ensure that the response body is closed before the function returns.

  1. POST request

The POST request is used to submit data to the server, typically form data or JSON data to an API endpoint. In Golang, POST requests can be easily made using the Post method provided by the http package. Here is a simple example:

package main

import (
    "fmt"
    "io/ioutil"
    "net/http"
    "strings"
)

func main() {
    url := "https://www.example.com/api"
    data := strings.NewReader(`{"name": "John", "age": 30}`)

    resp, err := http.Post(url, "application/json", data)
    if err != nil {
        // 处理错误
        return
    }
    defer resp.Body.Close()

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

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

In the above code, we use the http.Post method to send a POST request to https://www.example.com/api and submit the JSON data. We use the strings.NewReader method to convert the JSON data into a data stream and set the content-type to application/json. We then read the server's response and output it to the console.

  1. Custom request

Sometimes we need to customize HTTP request headers or parameters. In this case, we can use the http.NewRequest method to create a custom request. Here is a simple example:

package main

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

func main() {
    url := "https://www.example.com/api"
    req, err := http.NewRequest("GET", url, nil)
    if err != nil {
        // 处理错误
        return
    }

    req.Header.Add("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36")

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

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

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

In the above code, we create a GET request using the http.NewRequest method and add a custom User-Agent header. After creating the request, we use the Do method of the http.Client{} structure to send the request and get the response.

Summary

In this article, we introduced how to make GET and POST requests in Golang and how to customize HTTP requests. Use the methods mentioned above to make your network services more efficient and reliable.

The above is the detailed content of How to make network requests in Golang. 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