How to implement GET request in Golang

PHPz
Release: 2023-04-05 14:11:03
Original
2885 people have browsed it

Golang is an efficient programming language, and it is very convenient to carry out network development based on it. In network communication, GET request is the most common request method. This article will introduce in detail how to implement GET request in Golang.

1. GET request in Golang

In Golang, we can use the net/http package to send GET requests. This package provides a Client type that we can use to send an HTTP request.

The following is a sample code for sending a GET request:

package main

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

func main() {
    url := "https://www.example.com"
    resp, err := http.Get(url)
    if err != nil {
        fmt.Println("get url error:", err)
        return
    }
    defer resp.Body.Close()

    body, err := ioutil.ReadAll(resp.Body)
    if err != nil {
        fmt.Println("read body error:", err)
        return
    }

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

Let’s analyze the above code step by step:

  1. First, we define a url variable, which Indicates the URL we want to request.
  2. Use the http.Get method to send a request and assign the response result to the resp variable.
  3. For errors that may occur when sending HTTP requests, we use the err variable to capture.
  4. Before the function returns, use the defer statement to close the response Body stream.
  5. Read the content from the response Body stream and assign the result to the body variable.
  6. Finally, convert the response Body into a string and output it to the console.

2. GET request parameters

Often, a GET request not only needs to request the URL, but also needs to carry some request parameters. In Golang, we can use url.Values ​​to store parameters. The following is a sample code:

package main

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

func main() {
    url := "https://www.example.com"
    params := url.Values{}
    params.Set("key1", "value1")
    params.Set("key2", "value2")

    urlWithParams := url + "?" + params.Encode()
    resp, err := http.Get(urlWithParams)
    if err != nil {
        fmt.Println("get url error:", err)
        return
    }
    defer resp.Body.Close()

    body, err := ioutil.ReadAll(resp.Body)
    if err != nil {
        fmt.Println("read body error:", err)
        return
    }

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

We have added a part based on the original code:

  1. defines a url.Values ​​type variable named params.
  2. Use the params.Set method to set two parameters.
  3. Use the params.Encode method to encode the parameters into a string and splice them into the complete request URL.

In the above example, we use the params.Set method to carry two parameters for the request. In actual development, we can set more parameters according to needs.

3. Customize the header of the request

Sometimes we need to customize the header of the request, which can be achieved by setting the Header field of the http.Request structure. Here is an example:

package main

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

func main() {
    url := "https://www.example.com"
    req, _ := http.NewRequest("GET", url, nil)
    req.Header.Set("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")

    resp, err := http.DefaultClient.Do(req)
    if err != nil {
        fmt.Println("get url error:", err)
        return
    }
    defer resp.Body.Close()

    body, err := ioutil.ReadAll(resp.Body)
    if err != nil {
        fmt.Println("read body error:", err)
        return
    }

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

In this example, we use the http.NewRequest method to create a request and set a Header field named User-Agent. We also used the http.DefaultClient.Do method, which is a more flexible request method than http.Get, which allows us to customize more options.

4. Summary

In this article, we show how to use Golang to send GET requests, and also explain how to carry request parameters and set Header headers. Of course, this is far from all the content of using Golang for network programming. We can also use this language for POST requests, WebSocket communication, Socket programming, and more.

The above is the detailed content of How to implement GET request 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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!