Home Backend Development Golang golang proxy forwarding

golang proxy forwarding

May 27, 2023 pm 02:06 PM

With the rapid development of the Internet, more and more applications need to obtain data from different servers, and these data requests may need to go through multiple intermediate servers. Therefore, it is often necessary to use a proxy when developing applications. Requests are sent to the remote server until the required data is obtained.

This article will introduce how to use the Go language to build a simple proxy server that forwards client requests to another server and returns a response. Proxy servers can efficiently handle multiple client requests, reducing pressure on back-end servers and improving application performance and scalability.

Overview

In this article, we will learn how to create a golang-based proxy server that sends incoming requests to clients and forwards responses to the target server. We will use the standard library net/http implementation, which provides a simple and efficient way to handle HTTP requests and responses.

Preparation

Before we start writing the proxy server, we need to install the Go environment first. We can download and install Go from the official website https://golang.org/.

How the proxy server works

In the proxy server, we need to use the net/http package of the Go language to write code to intercept client requests. This package provides many useful functions and structures for processing and decoding HTTP requests and responses. In our proxy server, we will use the http.Handle() function to intercept client requests and redirect them to the remote server. We then use the http.Client() structure to send a request to the remote server and return the response to the client.

The following pseudocode demonstrates how the proxy server works:

When the client makes a request:

  • The client connects to the proxy server and sends HTTP ask.
  • The proxy server intercepts the client request and parses the request header and request body.
  • The proxy server checks whether the set target server exists, and returns an error if it does not exist.
  • The proxy server creates a new HTTP request, copies the request from the client into it, and sends it to the target server.
  • The target server receives the request from the proxy server and processes the request.
  • The target server creates and returns an HTTP response.
  • The proxy server receives the response from the target server and sends the response data back to the client.

Writing the proxy server

Now let us start writing the implementation of the proxy server. We need to create an HTTP server and set its listening address, port and client waiting time. We also need to add routing rules so that different handlers are selected based on client requests. In our case, we will use the http.Handle() function to add a route, and when the URL requested by the client is /proxy, we will redirect the request to the specified server. The following is a code snippet:

package main

import (
    "log"
    "net/http"
)

func main() {
    // 创建 http 服务器
    proxy := &Proxy{}

    // 添加路由规则
    http.Handle("/proxy", proxy)

    // 监听地址及端口
    log.Fatal(http.ListenAndServe(":8080", nil))
}

// 代理服务器结构体
type Proxy struct {
}

// 实现 http.Handler 接口的 ServeHTTP 方法
func (p *Proxy) ServeHTTP(w http.ResponseWriter, r *http.Request) {
    // 处理代理请求
}
Copy after login

In the above code, we create a structure named Proxy and implement the ServeHTTP() method in the http.Handler interface on it. The ServeHTTP() method receives two parameters: http.ResponseWriter and *http.Request objects. The former represents the data returned by the server to the client, and the latter represents the HTTP request header and request body requested by the client.

We then set up by adding a routing rule to set when a client requests /proxy in the URL, the request will be redirected to our handler.

Next, we have to write the code to handle the proxy request. We need to check that the target server exists and that the data requested by the client is correct. Here, we can use the http.NewRequest() function to create a new HTTP request object. We then use the Do() method in http.Client() to send the request and wait for the response. Finally, we return the response to the client.

The following is the complete code:

package main

import (

"io/ioutil"
"log"
"net/http"
Copy after login

)

func main() {

// 创建 http 服务器
proxy := &Proxy{}

// 添加路由规则
http.Handle("/proxy", proxy)

// 监听地址及端口
log.Fatal(http.ListenAndServe(":8080", nil))
Copy after login

}

// Proxy server structure
type Proxy struct {
}

// Implement the ServeHTTP method of the net/http.Handler interface
func (p Proxy) ServeHTTP(w http.ResponseWriter, r http.Request) {

// 检查目标服务器是否存在
targetUrl := "http://localhost:8888"
if len(targetUrl) == 0 {
    w.WriteHeader(http.StatusBadGateway)
    return
}

// 检查客户端请求的数据是否正确
if r.Method != "GET" {
    w.WriteHeader(http.StatusMethodNotAllowed)
    return
}

// 创建一个新的 HTTP 请求对象
req, err := http.NewRequest("GET", targetUrl, nil)
if err != nil {
    log.Fatal("请求创建失败", err)
}

// 使用 http.Client() 发送请求
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
    log.Fatal("请求发送失败", err)
}

defer resp.Body.Close()

// 读取响应的数据
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
    log.Fatal("读取响应数据失败", err)
}

// 将响应数据返回给客户端
w.Write(body)
Copy after login

}

运行代理服务器

现在我们已经完成了代理服务器的编写,请使用以下命令在命令行中运行该服务器,其中 targetUrl 是我们要转发的目标服务器的 IP 地址和端口。

$ go run main.go -targetUrl=http://localhost:8888

接下来,在浏览器中输入以下 URL,将客户端请求发送到代理服务器中:

http://localhost:8080/proxy

此时,代理服务器将转发该请求到目标服务器,并等待响应。当目标服务器返回响应时,代理服务器将响应数据返回给客户端。我们可以在代码中设置超时时间来控制客户端请求的等待时间,以及设置日志记录来实时查看代理服务器的运行情况。

结论

本文介绍了如何使用 Go 语言构建代理服务器,并演示了代理服务器的操作流程。虽然我们实现的代理服务器比较简单,但可以轻松扩展它来处理更复杂的请求。如果您有进一步的需求,可以使用类似的方法来扩展该服务器,以更好地满足您的需求。
Copy after login

The above is the detailed content of golang proxy forwarding. 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 AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Tools

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)

What are the vulnerabilities of Debian OpenSSL What are the vulnerabilities of Debian OpenSSL Apr 02, 2025 am 07:30 AM

OpenSSL, as an open source library widely used in secure communications, provides encryption algorithms, keys and certificate management functions. However, there are some known security vulnerabilities in its historical version, some of which are extremely harmful. This article will focus on common vulnerabilities and response measures for OpenSSL in Debian systems. DebianOpenSSL known vulnerabilities: OpenSSL has experienced several serious vulnerabilities, such as: Heart Bleeding Vulnerability (CVE-2014-0160): This vulnerability affects OpenSSL 1.0.1 to 1.0.1f and 1.0.2 to 1.0.2 beta versions. An attacker can use this vulnerability to unauthorized read sensitive information on the server, including encryption keys, etc.

How do you use the pprof tool to analyze Go performance? How do you use the pprof tool to analyze Go performance? Mar 21, 2025 pm 06:37 PM

The article explains how to use the pprof tool for analyzing Go performance, including enabling profiling, collecting data, and identifying common bottlenecks like CPU and memory issues.Character count: 159

How do you write unit tests in Go? How do you write unit tests in Go? Mar 21, 2025 pm 06:34 PM

The article discusses writing unit tests in Go, covering best practices, mocking techniques, and tools for efficient test management.

What is the problem with Queue thread in Go's crawler Colly? What is the problem with Queue thread in Go's crawler Colly? Apr 02, 2025 pm 02:09 PM

Queue threading problem in Go crawler Colly explores the problem of using the Colly crawler library in Go language, developers often encounter problems with threads and request queues. �...

What libraries are used for floating point number operations in Go? What libraries are used for floating point number operations in Go? Apr 02, 2025 pm 02:06 PM

The library used for floating-point number operation in Go language introduces how to ensure the accuracy is...

PostgreSQL monitoring method under Debian PostgreSQL monitoring method under Debian Apr 02, 2025 am 07:27 AM

This article introduces a variety of methods and tools to monitor PostgreSQL databases under the Debian system, helping you to fully grasp database performance monitoring. 1. Use PostgreSQL to build-in monitoring view PostgreSQL itself provides multiple views for monitoring database activities: pg_stat_activity: displays database activities in real time, including connections, queries, transactions and other information. pg_stat_replication: Monitors replication status, especially suitable for stream replication clusters. pg_stat_database: Provides database statistics, such as database size, transaction commit/rollback times and other key indicators. 2. Use log analysis tool pgBadg

What is the go fmt command and why is it important? What is the go fmt command and why is it important? Mar 20, 2025 pm 04:21 PM

The article discusses the go fmt command in Go programming, which formats code to adhere to official style guidelines. It highlights the importance of go fmt for maintaining code consistency, readability, and reducing style debates. Best practices fo

Transforming from front-end to back-end development, is it more promising to learn Java or Golang? Transforming from front-end to back-end development, is it more promising to learn Java or Golang? Apr 02, 2025 am 09:12 AM

Backend learning path: The exploration journey from front-end to back-end As a back-end beginner who transforms from front-end development, you already have the foundation of nodejs,...

See all articles