Table of Contents
Introduction to basic requests
Request settings
request object
Request timeout
Concurrent requests
https request
Summary
Home Backend Development Golang A multi-faceted introduction to golang's network requests

A multi-faceted introduction to golang's network requests

Apr 14, 2023 pm 01:45 PM

With the development of the Internet, network communication is becoming more and more important. For different business scenarios, different programming languages ​​also have their own characteristics. In the use of network requests, golang also shows many excellent processing methods. This article will introduce golang's network requests from the following aspects:

  1. Basic request introduction
  2. Request settings
  3. Concurrent requests
  4. https request

Introduction to basic requests

To use golang to initiate network requests, we need to rely on the standard library "net/http", in which the client (Client) can initiate requests and receive responses. The following is a simple GET request example:

package main

import (
    "fmt"
    "net/http"
)

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

    // 可以通过 resp 对象获取响应信息,比如响应状态码、响应头等
    fmt.Println(resp.Status)

    // 读取响应数据
    buffer := make([]byte, 1024)
    for {
        n, err := resp.Body.Read(buffer)
        if err != nil && err != io.EOF {
            // 处理错误
        }
        if n == 0 {
            break
        }
        fmt.Println(string(buffer[:n]))
    }
}
Copy after login

Among them, we use the "http.Get" method to initiate a GET request. After obtaining the "resp" object, we can read the response data through the object. It should be noted that after reading the response data, the response body needs to be closed to avoid resource leakage.

Request settings

In addition to regular GET requests, we can also make other types of requests, such as POST, PUT, etc., and we can also make more fine-grained adjustments to the requests.

request object

Before initiating a request, we can set various parameters of the request, such as URL, request header, request body, etc., by creating the "http.Request" object. For example, the following is a POST request example:

package main

import (
    "bytes"
    "net/http"
)

func main() {
    url := "http://www.example.com/api"
    data := bytes.NewBufferString("hello world")

    // 创建一个 POST 请求,并设置请求头和请求体
    req, _ := http.NewRequest("POST", url, data)
    req.Header.Set("Content-Type", "application/json")

    // 发起请求
    client := http.DefaultClient
    resp, err := client.Do(req)
    if err != nil {
        // 处理错误
    }
    defer resp.Body.Close()

    // 处理响应
}
Copy after login

In this example, we use the "http.NewRequest" method to create a POST request object, and then set the request header and request body. Next, we use "http.DefaultClient.Do" to initiate a request and obtain the response object "resp". It's important to remember to close the response body when you're done.

Request timeout

Generally, request timeout is an issue that must be considered. Golang's "http.Client" supports setting the timeout of the request. We can use "http.Client.Timeout" to set the timeout. The sample code is as follows:

package main

import (
    "net/http"
    "time"
)

func main() {
    client := &http.Client{
        Timeout: 2 * time.Second,
    }

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

    // 处理响应
}
Copy after login

In this example, we create an "http .Client" object and set the request timeout to 2 seconds. It should be noted that the timeout should be set before use, rather than processed after an error is determined.

Concurrent requests

Golang, as a highly concurrency language, of course also has excellent concurrent request processing methods. Under normal circumstances, we will use concurrent requests to improve the efficiency of network requests. The following is a simple concurrent request example:

package main

import (
    "fmt"
    "net/http"
    "sync"
)

func main() {
    var urls = []string{"http://www.example.com/", "http://www.example.net/", "http://www.example.org/"}

    result := make(chan string)
    var wg sync.WaitGroup

    for _, url := range urls {
        wg.Add(1)
        go func(url string) {
            defer wg.Done()

            resp, err := http.Get(url)
            if err != nil {
                // 处理错误
            }
            defer resp.Body.Close()

            result <- url + " " + resp.Status
        }(url)
    }

    go func() {
        wg.Wait()
        close(result)
    }()

    // 持续读取结果,直到 result 被关闭
    for r := range result {
        fmt.Println(r)
    }
}
Copy after login

In this example, we use channel to transmit results and start multiple goroutines to initiate requests at the same time. The following points need to be noted in this example:

  1. We use sync.WaitGroup to count the number of goroutines and ensure that all goroutines have ended.
  2. In each goroutine, we use anonymous functions for parameter passing.
  3. In order to avoid goroutine blocking, we use channels to transfer results between goroutines.

https request

Especially when developing web applications, we will always encounter situations where we need to use https. In golang, we can directly use URLs starting with "https://" to initiate https requests without making additional settings. Here is a simple example:

package main

import (
    "crypto/tls"
    "fmt"
    "net/http"
)

func main() {
    tr := &http.Transport{
        TLSClientConfig: &tls.Config{
            InsecureSkipVerify: true, // 这里忽略了证书校验,实际情况下不应该这么做
        },
    }

    client := &http.Client{Transport: tr}
    resp, err := client.Get("https://www.example.com/")
    if err != nil {
        // 处理错误
    }
    defer resp.Body.Close()

    // 处理响应
    fmt.Println(resp.Status)
}
Copy after login

In this example, we use the "http.Transport" object to create the "http.Client" object and skip the https certificate verification. It should be noted that this should not be done in actual production, as this may cause security risks.

Summary

Through the introduction of this article, we have learned the basic network request processing methods and the excellent performance of golang in network requests. Of course, this article only introduces a relatively basic request processing method, and it needs to be adjusted according to specific scenarios in actual use.

The above is the detailed content of A multi-faceted introduction to golang's network requests. For more information, please follow other related articles on the PHP Chinese website!

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

Hot Article Tags

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Go language pack import: What is the difference between underscore and without underscore? Go language pack import: What is the difference between underscore and without underscore? Mar 03, 2025 pm 05:17 PM

Go language pack import: What is the difference between underscore and without underscore?

How do I write mock objects and stubs for testing in Go? How do I write mock objects and stubs for testing in Go? Mar 10, 2025 pm 05:38 PM

How do I write mock objects and stubs for testing in Go?

How to implement short-term information transfer between pages in the Beego framework? How to implement short-term information transfer between pages in the Beego framework? Mar 03, 2025 pm 05:22 PM

How to implement short-term information transfer between pages in the Beego framework?

How can I use tracing tools to understand the execution flow of my Go applications? How can I use tracing tools to understand the execution flow of my Go applications? Mar 10, 2025 pm 05:36 PM

How can I use tracing tools to understand the execution flow of my Go applications?

How can I define custom type constraints for generics in Go? How can I define custom type constraints for generics in Go? Mar 10, 2025 pm 03:20 PM

How can I define custom type constraints for generics in Go?

How to convert MySQL query result List into a custom structure slice in Go language? How to convert MySQL query result List into a custom structure slice in Go language? Mar 03, 2025 pm 05:18 PM

How to convert MySQL query result List into a custom structure slice in Go language?

How to write files in Go language conveniently? How to write files in Go language conveniently? Mar 03, 2025 pm 05:15 PM

How to write files in Go language conveniently?

How can I use linters and static analysis tools to improve the quality and maintainability of my Go code? How can I use linters and static analysis tools to improve the quality and maintainability of my Go code? Mar 10, 2025 pm 05:38 PM

How can I use linters and static analysis tools to improve the quality and maintainability of my Go code?

See all articles