proxy

package module
v1.5.6 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 11, 2023 License: MIT Imports: 25 Imported by: 12

README

Proxy - Make Reverse Proxy easier to use

PkgGoDev Build Status Go Report Card Coverage Status GitHub issues Release

Installation

To install the package, run:

go get -u github.com/go-zoox/proxy

Quick Start

package main

import (
	"fmt"
	"net/http"

	"github.com/go-zoox/proxy"
)

func main() {
	fmt.Println("Starting proxy at http://127.0.0.1:9999 ...")

	http.ListenAndServe(":9999", proxy.New(&proxy.Config{
		OnRequest: func(req *http.Request) error {
			req.URL.Host = "127.0.0.1:8080"
			return nil
		},
	}))
}

// visit http://127.0.0.1:9999/ip => http://127.0.0.1:8080/ip
// curl -v http://127.0.0.1:9999/ip

Best Practice

1. Single Host => All traffic to a single target with path
package main

import (
	"fmt"
	"net/http"

	"github.com/go-zoox/proxy"
)

func main() {
	target := "https://httpbin.org"

	fmt.Println("Starting proxy at http://127.0.0.1:9999 ...")
	http.ListenAndServe(":9999", proxy.NewSingleHost(target))
}
2. Single Host => All traffic to a single target with rewrite
package main

import (
	"fmt"
	"net/http"

	"github.com/go-zoox/proxy"
	"github.com/go-zoox/proxy/utils/rewriter"
)

func main() {
	target := "https://httpbin.org"

	fmt.Println("Starting proxy at http://127.0.0.1:9999 ...")
	http.ListenAndServe(":9999", proxy.NewSingleHost(target, &proxy.SingleHostConfig{
		Rewrites: rewriter.Rewriters{
			{
				From: "/api/ip",
				To:   "/ip",
			},
			{
				From: "/api/headers",
				To:   "/headers",
			},
			{
				From: "/api/v2/(.*)",
				To:   "/$1",
			},
		},
	}))
}
3. Multiple Hosts => All traffic to multiple targets
package main

import (
	"fmt"
	"net/http"

	"github.com/go-zoox/proxy"
)

func main() {
	fmt.Println("Starting proxy at http://127.0.0.1:9999 ...")
	
	http.ListenAndServe(":9999", proxy.NewMultiHosts(&proxy.MultiHostsConfig{
		Routes: []proxy.MultiHostsRoute{
			{
				Host: "httpbin1.go-zoox.work",
				Backend: proxy.MultiHostsRouteBackend{
					ServiceProtocol: "https",
					ServiceName:     "httpbin.zcorky.com",
					ServicePort:     443,
				},
			},
			{
				Host: "httpbin2.go-zoox.work",
				Backend: proxy.MultiHostsRouteBackend{
					ServiceProtocol: "https",
					ServiceName:     "httpbin.org",
					ServicePort:     443,
				},
			},
		},
	}))
}

Inspiration

  • Go httputil.ReverseProxy

License

GoZoox is released under the MIT License.

Documentation

Index

Constants

This section is empty.

Variables

View Source
var Version = "1.5.6"

Version is the version of this package.

Functions

func CreateOnHTMLRewriteResponse added in v1.2.1

func CreateOnHTMLRewriteResponse(fn func(origin []byte, res *http.Response) ([]byte, error)) func(*http.Response) error

CreateOnHTMLRewriteResponse create a function to rewrite html response

func CreateOnInjectScriptsResponse added in v1.2.1

func CreateOnInjectScriptsResponse(fn func(origin []byte, res *http.Response) string) func(*http.Response) error

CreateOnInjectScriptsResponse create a function to inject scripts

func NewHTTPError

func NewHTTPError(status int, message string) error

NewHTTPError creates a new HTTPError.

func ParseHostPort

func ParseHostPort(rawHost string) (string, string)

ParseHostPort parses host and port from a string in the form host[:port].

Types

type BufferPool

type BufferPool interface {
	Get() []byte
	Put([]byte)
}

A BufferPool is an interface for getting and returning temporary byte slices for use by io.CopyBuffer.

type Config

type Config struct {
	// IsAnonymouse is a flag to indicate whether the proxy is anonymouse.
	//	which means the proxy will not add headers:
	//		X-Forwarded-For
	//		X-Forwarded-Proto
	//		X-Forwarded-Host
	//		X-Forwarded-Port
	// Default is false.
	IsAnonymouse bool

	// OnContext is a function that will be called before the request is sent.
	OnContext func(ctx context.Context) (context.Context, error)

	// OnRequest is a function that will be called before the request is sent.
	OnRequest func(req, inReq *http.Request) error

	// OnResponse is a function that will be called after the response is received.
	OnResponse func(res *http.Response, inReq *http.Request) error

	// OnError is a function that will be called when an error occurs.
	OnError func(err error, rw http.ResponseWriter, req *http.Request)
}

Config is the configuration for the Proxy.

type HTTPError

type HTTPError struct {
	// contains filtered or unexported fields
}

HTTPError is an error that wraps an HTTP status code.

func (*HTTPError) Error

func (h *HTTPError) Error() string

Error returns the error message.

func (*HTTPError) Status

func (h *HTTPError) Status() int

Status returns the HTTP status code.

type MultiHostsConfig added in v1.4.0

type MultiHostsConfig struct {
	Routes []MultiHostsRoute `json:"routes"`
}

MultiHostsConfig ...

type MultiHostsRoute added in v1.4.0

type MultiHostsRoute struct {
	Host    string                 `json:"host"`
	Backend MultiHostsRouteBackend `json:"backend"`
}

MultiHostsRoute ...

type MultiHostsRouteBackend added in v1.4.0

type MultiHostsRouteBackend struct {
	ServiceProtocol string `json:"service_protocol"`
	ServiceName     string `json:"service_name"`
	ServicePort     int64  `json:"service_port"`
	// Request
	Rewriters rewriter.Rewriters `json:"rewriters"`
	Headers   http.Header        `json:"headers"`
	//
	ResponseHeaders http.Header `json:"response_headers"`
}

MultiHostsRouteBackend ...

type Proxy

type Proxy struct {
	OnContext func(ctx context.Context) (context.Context, error)
	//
	OnRequest  func(req, originReq *http.Request) error
	OnResponse func(res *http.Response, originReq *http.Request) error
	OnError    func(err error, rw http.ResponseWriter, req *http.Request)

	// IsAnonymouse is a flag to indicate whether the proxy is anonymouse.
	//	which means the proxy will not add headers:
	//		X-Forwarded-For
	//		X-Forwarded-Proto
	//		X-Forwarded-Host
	//		X-Forwarded-Port
	// Default is false.
	IsAnonymouse bool

	// Transport is the transport used to make requests to the Origin.
	Transport http.RoundTripper
	// contains filtered or unexported fields
}

Proxy is a Powerful HTTP Proxy, inspired by Go Reverse Proxy.

func New

func New(cfg *Config) *Proxy

New creates a new Proxy.

func NewMultiHosts added in v1.4.0

func NewMultiHosts(cfg *MultiHostsConfig) *Proxy

NewMultiHosts ...

func NewSingleHost added in v1.5.0

func NewSingleHost(target string, cfg ...*SingleHostConfig) *Proxy

NewSingleHost creates a new Single Host Proxy. target is the URL of the host you wish to proxy to. cfg is the configuration for the SingleHost.

  • Rewrites is the rewriters for the SingleHost.
  • Scheme overrides the scheme of target.
  • Query is the query of the SingleHost.
  • RequestHeaders is the request headers of the SingleHost.
  • ResponseHeaders is the response headers of the SingleHost.
  • OnRequest is the hook that is called before the request is sent.
  • OnResponse is the hook that is called after the response is received.
  • IsAnonymouse is a flag to indicate whether the proxy is anonymouse. which means the proxy will not add headers: X-Forwarded-For X-Forwarded-Proto X-Forwarded-Host X-Forwarded-Port Default is false.
  • ChangeOrigin is a flag to indicate whether the proxy will change the origin. which means the proxy will change the origin to target. Default is false.
  • OnError is the hook that is called when an error occurs.

Example:

// All requests will be redirected to https://httpbin.org
NewSingleHost("https://httpbin.org")

// All requests will be redirected to https://httpbin.org/ip
NewSingleHost("https://httpbin.org/ip")

// All requests will be redirected to https://httpbin.org with Rewrites
 NewSingleHost("https://httpbin.org", &SingleHostConfig{
 	Rewrites: rewriter.Rewriters{
 		{ From: "/api/get", To: "/get" },
	  { From: "/api/post", To: "/post" },
 	  { From: "/api/v2/(.*)", To: "/$1" },
 	},
 	Query: url.Values{
 		"foo": []string{"bar"},
 	},
 	RequestHeaders: http.Header{
 		headers.Host: []string{"httpbin.org"},
 	},
 	ResponseHeaders: http.Header{
 		headers.Server: []string{"go-zoox_proxy"},
 	},
 	OnRequest: func(req *http.Request) error {
 		// do something
 		return nil
 	},
 	OnResponse: func(res *http.Response) error {
 		// do something
 		return nil
 	},
 	IsAnonymouse: true,
 	ChangeOrigin: true,
 	OnError: func(err error, rw http.ResponseWriter, req *http.Request) {
 		// do something
 	},
 })

func (*Proxy) ServeHTTP

func (r *Proxy) ServeHTTP(rw http.ResponseWriter, inReq *http.Request)

ServeHTTP is the entry point for the proxy.

type SingleHostConfig added in v1.5.0

type SingleHostConfig struct {
	Rewrites        rewriter.Rewriters
	Scheme          string
	Query           url.Values
	RequestHeaders  http.Header
	ResponseHeaders http.Header
	OnRequest       func(req *http.Request) error
	OnResponse      func(res *http.Response) error
	//
	IsAnonymouse bool
	ChangeOrigin bool
	//
	OnError func(err error, rw http.ResponseWriter, req *http.Request)
}

SingleHostConfig is the configuration for SingleTarget.

Directories

Path Synopsis
example
utils

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL