Home >Backend Development >Golang >How to Forward HTTP Requests to Another Server in Go?

How to Forward HTTP Requests to Another Server in Go?

DDD
DDDOriginal
2024-12-01 22:45:13253browse

How to Forward HTTP Requests to Another Server in Go?

Go http: Transferring Received HTTP Requests to Another Server

In scenarios where service versions coexist, it may be necessary to duplicate incoming HTTP requests to maintain compatibility. This article explores a method to redirect requests received by one service to another using the Go programming language.

Challenge:

A user faced an issue while attempting to duplicate POST requests in a Go service to a separate service. Setting req.URL.Host and req.Host directly resulted in the error "http: Request.RequestURI can't be set in client requests."

Solution:

The recommended approach is to create a new http.Request object and selectively copy the desired parts from the original request. This ensures that the RequestURI is properly set for the second request. Additionally, if the request body needs to be reused, it should be buffered and assigned to the body of the new request.

Go Code Example:

func handler(w http.ResponseWriter, req *http.Request) {
    // Buffer the body for reuse
    body, err := ioutil.ReadAll(req.Body)
    if err != nil {
        http.Error(w, err.Error(), http.StatusInternalServerError)
        return
    }
    req.Body = ioutil.NopCloser(bytes.NewReader(body))

    // Construct a new request with the desired URL and body
    proxyScheme := "http"
    proxyHost := "example.com"
    url := fmt.Sprintf("%s://%s%s", proxyScheme, proxyHost, req.RequestURI)
    proxyReq, err := http.NewRequest(req.Method, url, bytes.NewReader(body))

    // Copy essential headers
    proxyReq.Header = make(http.Header)
    for h, val := range req.Header {
        proxyReq.Header[h] = val
    }

    // Send the request to the other server
    resp, err := httpClient.Do(proxyReq)
    if err != nil {
        http.Error(w, err.Error(), http.StatusBadGateway)
        return
    }
    defer resp.Body.Close()

    // Handle the response as usual
}

This approach effectively transfers the incoming HTTP request to the other server while respecting the RequestURI and other critical HTTP parameters.

The above is the detailed content of How to Forward HTTP Requests to Another Server in Go?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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