How to implement request forwarding and add delay function in Golang

PHPz
Release: 2023-04-05 10:42:06
Original
595 people have browsed it

When developing web applications, we often need to forward requests to another server for processing, such as implementing load balancing, request caching, etc. Golang is an efficient language, and the net/http package in its standard library provides a variety of ways to forward requests. Here, let’s discuss how to implement request forwarding and add delay functions in Golang.

First, we need to create an HTTP Server to receive user requests. For the convenience of demonstration, I will simulate request forwarding by starting two HTTP Servers locally. One of the Server's ports is 8081 and the other is 8082.

package main

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

func main() {
    http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
        log.Printf("request from: %s\n", r.RemoteAddr)
        resp, err := http.Get("http://127.0.0.1:8081")
        if err != nil {
            http.Error(w, err.Error(), http.StatusInternalServerError)
            return
        }
        defer resp.Body.Close()

        _, err = w.Write([]byte(fmt.Sprintf("[%s]: %s", r.RemoteAddr, resp.Status)))
        if err != nil {
            log.Printf("failed to write response: %s", err.Error())
        }
    })

    addr := ":8080"
    log.Printf("listening on %s...\n", addr)
    log.Fatal(http.ListenAndServe(addr, nil))
}
Copy after login

Next, we need to modify the code to implement request forwarding and add delay functions. Since Golang has good support for asynchronous operations, we can implement delays through goroutine and channels.

package main

import (
    "fmt"
    "log"
    "net/http"
    "time"
)

func main() {
    http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
        log.Printf("request from: %s\n", r.RemoteAddr)

        // 使用channel来实现延时
        done := make(chan bool)
        go func() {
            time.Sleep(1 * time.Second)
            done <- true
        }()

        // 请求转发
        resp, err := http.Get("http://127.0.0.1:8081")
        if err != nil {
            http.Error(w, err.Error(), http.StatusInternalServerError)
            return
        }
        defer resp.Body.Close()

        _, err = w.Write([]byte(fmt.Sprintf("[%s]: %s", r.RemoteAddr, resp.Status)))
        if err != nil {
            log.Printf("failed to write response: %s", err.Error())
        }

        // 等待延时完成
        <-done
    })

    addr := ":8080"
    log.Printf("listening on %s...\n", addr)
    log.Fatal(http.ListenAndServe(addr, nil))
}
Copy after login

In the above code, we created a channel, used goroutine to implement a 1 second delay, then used http.Get() to forward the request, and finally waited for the channel to send a signal, that is, delay After the request is completed, the response is returned to the user. In this way, the function of adding delay while forwarding the request is realized.

In addition to using goroutine and channel to implement delay, we can also use the time.Sleep() method provided in the time package, as shown below:

time.Sleep(1 * time.Second)
Copy after login

It should be noted that in practice In a production environment, we need to pay attention to the delay time to avoid application performance degradation caused by too long delay.

The above is the detailed content of How to implement request forwarding and add delay function 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!