Convert Figma logo to code with AI

elazarl logogoproxy

An HTTP proxy library for Go

6,081
1,111
6,081
186

Top Related Projects

37,624

An interactive TLS-capable intercepting HTTP proxy for penetration testers and software developers.

A platform for building proxies to bypass network restrictions.

14,736

Lantern官方版本下载 蓝灯 翻墙 代理 科学上网 外网 加速器 梯子 路由 - Быстрый, надежный и безопасный доступ к открытому интернету - lantern proxy vpn censorship-circumvention censorship gfw accelerator پراکسی لنترن، ضدسانسور، امن، قابل اعتماد و پرسرعت

go port of shadowsocks (Deprecated)

16,346

GO Simple Tunnel - a simple tunnel written in golang

Quick Overview

GoProxy is an HTTP/HTTPS proxy library for Go. It provides a customizable proxy server that can be used to intercept, modify, and forward HTTP and HTTPS requests and responses. This library is particularly useful for debugging, testing, and implementing custom proxy behavior in Go applications.

Pros

  • Easy to use and integrate into existing Go projects
  • Supports both HTTP and HTTPS traffic interception
  • Highly customizable with hooks for modifying requests and responses
  • Actively maintained with regular updates and bug fixes

Cons

  • Limited documentation and examples for advanced use cases
  • May require additional configuration for complex proxy scenarios
  • Performance may be impacted when handling large volumes of traffic
  • Lacks built-in support for some advanced proxy features (e.g., caching, load balancing)

Code Examples

  1. Creating a basic proxy server:
package main

import (
    "github.com/elazarl/goproxy"
    "log"
    "net/http"
)

func main() {
    proxy := goproxy.NewProxyHttpServer()
    log.Fatal(http.ListenAndServe(":8080", proxy))
}
  1. Modifying requests:
proxy.OnRequest().DoFunc(func(r *http.Request, ctx *goproxy.ProxyCtx) (*http.Request, *http.Response) {
    r.Header.Set("X-GoProxy", "true")
    return r, nil
})
  1. Blocking specific domains:
proxy.OnRequest(goproxy.DstHostIs("example.com")).DoFunc(func(r *http.Request, ctx *goproxy.ProxyCtx) (*http.Request, *http.Response) {
    return r, goproxy.NewResponse(r, goproxy.ContentTypeText, http.StatusForbidden, "Blocked")
})
  1. Logging requests:
proxy.OnRequest().DoFunc(func(r *http.Request, ctx *goproxy.ProxyCtx) (*http.Request, *http.Response) {
    log.Printf("Request: %s %s", r.Method, r.URL)
    return r, nil
})

Getting Started

To use GoProxy in your Go project, follow these steps:

  1. Install the library:

    go get github.com/elazarl/goproxy
    
  2. Import the library in your Go code:

    import "github.com/elazarl/goproxy"
    
  3. Create a new proxy server and start listening:

    proxy := goproxy.NewProxyHttpServer()
    log.Fatal(http.ListenAndServe(":8080", proxy))
    
  4. Customize the proxy behavior by adding request and response handlers as needed.

Competitor Comparisons

37,624

An interactive TLS-capable intercepting HTTP proxy for penetration testers and software developers.

Pros of mitmproxy

  • More feature-rich with a command-line interface, web interface, and Python scripting support
  • Better documentation and active community support
  • Supports HTTP/2 and WebSockets

Cons of mitmproxy

  • Written in Python, which may be slower than Go for certain operations
  • Larger codebase and potentially more complex to contribute to
  • Steeper learning curve for users not familiar with Python

Code Comparison

mitmproxy (Python):

def request(flow: http.HTTPFlow) -> None:
    if flow.request.pretty_host == "example.com":
        flow.request.headers["Custom-Header"] = "Value"

goproxy (Go):

goproxy.OnRequest().DoFunc(func(r *http.Request, ctx *goproxy.ProxyCtx) (*http.Request, *http.Response) {
    if r.Host == "example.com" {
        r.Header.Set("Custom-Header", "Value")
    }
    return r, nil
})

Both examples show how to modify headers for requests to a specific host, demonstrating the syntax differences between Python and Go. mitmproxy's approach is more concise, while goproxy's is more explicit in its function structure.

A platform for building proxies to bypass network restrictions.

Pros of v2ray-core

  • More comprehensive networking protocol support, including VMess, VLESS, and Trojan
  • Advanced routing capabilities with flexible rule-based traffic routing
  • Better suited for complex network environments and bypassing censorship

Cons of v2ray-core

  • Steeper learning curve due to its complexity and extensive configuration options
  • Higher resource consumption compared to the lightweight goproxy

Code Comparison

v2ray-core (config example):

{
  "inbounds": [{
    "port": 1080,
    "protocol": "socks",
    "settings": {
      "auth": "noauth"
    }
  }],
  "outbounds": [{
    "protocol": "freedom"
  }]
}

goproxy (usage example):

proxy := goproxy.NewProxyHttpServer()
proxy.Verbose = true
log.Fatal(http.ListenAndServe(":8080", proxy))

Summary

v2ray-core offers more advanced features and protocol support, making it suitable for complex networking scenarios and circumventing censorship. However, it comes with a steeper learning curve and higher resource usage. goproxy, on the other hand, is simpler to use and more lightweight, but lacks some of the advanced features found in v2ray-core. The choice between the two depends on the specific requirements of the project and the level of complexity needed.

14,736

Lantern官方版本下载 蓝灯 翻墙 代理 科学上网 外网 加速器 梯子 路由 - Быстрый, надежный и безопасный доступ к открытому интернету - lantern proxy vpn censorship-circumvention censorship gfw accelerator پراکسی لنترن، ضدسانسور، امن، قابل اعتماد و پرسرعت

Pros of Lantern

  • Full-featured censorship circumvention tool with a user-friendly GUI
  • Supports multiple protocols and advanced features like traffic obfuscation
  • Active development with frequent updates and a large user base

Cons of Lantern

  • More complex setup and configuration compared to Goproxy
  • Heavier resource usage due to additional features and GUI
  • May be overkill for simple proxy needs

Code Comparison

Lantern (main proxy handling):

func (proxy *Proxy) Handle(ctx context.Context, conn net.Conn) error {
    // Complex connection handling with multiple protocols
    // ...
}

Goproxy (main proxy handling):

func (proxy *ProxyHttpServer) ServeHTTP(w http.ResponseWriter, r *http.Request) {
    // Simpler HTTP-focused proxy handling
    // ...
}

Lantern offers a more comprehensive solution for censorship circumvention with advanced features, while Goproxy provides a simpler, lightweight HTTP/HTTPS proxy implementation. Lantern is better suited for end-users needing robust censorship bypass, while Goproxy is more appropriate for developers integrating proxy functionality into their applications or for simpler proxy requirements.

go port of shadowsocks (Deprecated)

Pros of shadowsocks-go

  • Designed specifically for circumventing internet censorship
  • Implements the SOCKS5 proxy protocol, which is more versatile for various applications
  • Offers encryption and obfuscation features for enhanced privacy and security

Cons of shadowsocks-go

  • Less actively maintained compared to goproxy
  • More complex setup and configuration process
  • Limited to SOCKS5 proxy functionality, while goproxy supports HTTP/HTTPS as well

Code Comparison

shadowsocks-go:

cipher := ss.NewCipher(config.Method, config.Password)
listenAddr := net.JoinHostPort(config.Server, config.ServerPort)
ln, err := net.Listen("tcp", listenAddr)

goproxy:

proxy := goproxy.NewProxyHttpServer()
proxy.Verbose = true
log.Fatal(http.ListenAndServe(":8080", proxy))

The code snippets highlight the different focus of each project. shadowsocks-go emphasizes encryption and custom network protocols, while goproxy provides a simpler setup for HTTP proxy functionality.

16,346

GO Simple Tunnel - a simple tunnel written in golang

Pros of gost

  • More comprehensive proxy solution with support for multiple protocols (HTTP, SOCKS4, SOCKS5, Shadowsocks, etc.)
  • Built-in encryption and obfuscation features for enhanced security
  • Supports chaining of multiple proxies for increased anonymity

Cons of gost

  • More complex configuration due to its extensive feature set
  • Potentially higher resource usage compared to goproxy's lightweight design
  • Less focused on HTTP proxy functionality, which may be overkill for simple use cases

Code Comparison

goproxy:

proxy := goproxy.NewProxyHttpServer()
proxy.Verbose = true
log.Fatal(http.ListenAndServe(":8080", proxy))

gost:

chain := gost.NewChain(
    gost.Node{Protocol: "http", Addr: ":8080"},
    gost.Node{Protocol: "socks5", Addr: ":1080"},
)
log.Fatal(chain.Run())

The code snippets demonstrate that goproxy is more straightforward for setting up a simple HTTP proxy, while gost offers more flexibility in configuring multiple proxy types and chaining them together.

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

GoProxy

GoDoc Status

GoProxy is a library to create a customized HTTP/HTTPS proxy server using Go (aka Golang), with several configurable settings available. The target of this project is to offer an optimized proxy server, usable with reasonable amount of traffic, yet customizable and programmable.

The proxy itself is simply a net/http handler, so you can add multiple middlewares (panic recover, logging, compression, etc.) over it. It can be easily integrated with any other HTTP network library.

In order to use goproxy, one should set their browser (or any other client) to use goproxy as an HTTP proxy. Here is how you do that in Chrome and in Firefox. If you decide to start with the base example, the URL you should use as proxy is localhost:8080, which is the default one in our example.

Features

  • Perform certain actions only on specific hosts, with a single equality comparison or with regex evaluation
  • Manipulate requests and responses before sending them to the browser
  • Use a custom http.Transport to perform requests to the target server
  • You can specify a MITM certificates cache, to reuse them later for other requests to the same host, thus saving CPU. Not enabled by default, but you should use it in production!
  • Redirect normal HTTP traffic to a custom handler, when the target is a relative path (e.g. /ping)
  • You can choose the logger to use, by implementing the Logger interface

Proxy modes

  1. Regular HTTP proxy
  2. HTTPS through CONNECT
  3. HTTPS MITM ("Man in the Middle") proxy server, in which the server generate TLS certificates to parse request/response data and perform actions on them
  4. "Hijacked" proxy connection, where the configured handler can access the raw net.Conn data

Maintainers

Contributions

If you have any trouble, suggestion, or if you find a bug, feel free to reach out by opening a GitHub issue. This is an open source project managed by volunteers, and we're happy to discuss anything that can improve it.

Make sure to explain everything, including the reason behind the issue and what you want to change, to make the problem easier to understand. You can also directly open a Pull Request, if it's a small code change, but you need to explain in the description everything. If you open a pull request named refactoring with 5,000 lines changed, we won't merge it... :D

The code for this project is released under the BSD 3-Clause license, making it useful for commercial uses as well.

A taste of GoProxy

To get a taste of goproxy, here you are a basic HTTP/HTTPS proxy that just forward data to the destination:

package main

import (
    "log"
    "net/http"

    "github.com/elazarl/goproxy"
)

func main() {
    proxy := goproxy.NewProxyHttpServer()
    proxy.Verbose = true
    log.Fatal(http.ListenAndServe(":8080", proxy))
}

Request handler

This line will add X-GoProxy: yxorPoG-X header to all requests sent through the proxy, before sending them to the destination:

proxy.OnRequest().DoFunc(
    func(r *http.Request,ctx *goproxy.ProxyCtx)(*http.Request,*http.Response) {
        r.Header.Set("X-GoProxy","yxorPoG-X")
        return r,nil
    })

When the OnRequest() input is empty, the function specified in DoFunc will process all incoming requests to the proxy. In this case, it will add a header to the request and return it to the caller. The proxy will send the modified request to the destination. You can also use Do instead of DoFunc, if you implement the specified interface in your type.

⚠️ Note we returned a nil value as the response. If the returned response is not nil, goproxy will discard the request and send the specified response to the client.

Conditional Request handler

Refuse connections to www.reddit.com between 8 and 17 in the server local timezone:

proxy.OnRequest(goproxy.DstHostIs("www.reddit.com")).DoFunc(
    func(req *http.Request,ctx *goproxy.ProxyCtx)(*http.Request,*http.Response) {
        if h,_,_ := time.Now().Clock(); h >= 8 && h <= 17 {
			resp := goproxy.NewResponse(r, goproxy.ContentTypeText, http.StatusForbidden, "Don't waste your time!")
            return req, resp
        }
        return req,nil
})

DstHostIs returns a ReqCondition, which is a function receiving a *http.Request and returning a boolean that checks if the request satisfies the condition (and that will be processed). DstHostIs("www.reddit.com") will return a ReqCondition that returns true when the request is directed to "www.reddit.com". The host equality check is case-insensitive, to reflect the behaviour of DNS resolvers, so even if the user types "www.rEdDit.com", the comparison will satisfy the condition. When the hour is between 8:00am and 5:59pm, we directly return a response in DoFunc(), so the remote destination will not receive the request and the client will receive the "Don't waste your time!" response.

Let's start

import "github.com/elazarl/goproxy"

There are some proxy usage examples in the examples folder, which cover the most common cases. Take a look at them and good luck!

Request & Response manipulation

There are 3 different types of handlers to manipulate the behavior of the proxy, as follows:

// handler called after receiving HTTP CONNECT from the client, and
// before proxy establishes connection with the destination host
httpsHandlers   []HttpsHandler

// handler called before proxy sends HTTP request to destination host
reqHandlers     []ReqHandler 

// handler called after proxy receives HTTP Response from destination host,
// and before proxy forwards the Response to the client
respHandlers    []RespHandler 

Depending on what you want to manipulate, the ways to add handlers to each of the previous lists are:

// Add handlers to httpsHandlers 
proxy.OnRequest(some ReqConditions).HandleConnect(YourHandlerFunc())

// Add handlers to reqHandlers
proxy.OnRequest(some ReqConditions).Do(YourReqHandlerFunc())

// Add handlers to respHandlers
proxy.OnResponse(some RespConditions).Do(YourRespHandlerFunc())

Example:

// This rejects the HTTPS request to *.reddit.com during HTTP CONNECT phase.
// Reddit URL check is case-insensitive because of (?i), so the block will work also if the user types something like rEdDit.com.
proxy.OnRequest(goproxy.ReqHostMatches(regexp.MustCompile("(?i)reddit.*:443$"))).HandleConnect(goproxy.AlwaysReject)

// Be careful about this example! It shows you a common error that you
// need to avoid.
// This will NOT reject the HTTPS request with URL ending with .gif because,
// if the scheme is HTTPS, the proxy will receive only URL.Hostname
// and URL.Port during the HTTP CONNECT phase.
proxy.OnRequest(goproxy.UrlMatches(regexp.MustCompile(`.*gif$`))).HandleConnect(goproxy.AlwaysReject)

// To fix the previous example, here there is the correct way to manipulate
// an HTTP request using URL.Path (target path) as a condition.
proxy.OnRequest(goproxy.UrlMatches(regexp.MustCompile(`.*gif$`))).Do(YourReqHandlerFunc())

Project Status

This project has been created 10 years ago, and has reached a stage of maturity. It can be safely used in production, and many projects already do that.

If there will be any breaking change in the future, a new version of the Go module will be released (e.g. v2).

Trusted, as a direct dependency, by:

Stripe Dependabot Go Git Google Grafana Fly.io Kubernetes / Minikube New Relic