proxy

package module
v2.2.3 Latest Latest
Warning

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

Go to latest
Published: Jan 26, 2024 License: MIT Imports: 12 Imported by: 10

README

fasthttp-reverse-proxy

Go Report Card GoReportCard

reverse http proxy handler based on fasthttp.

Features

  • HTTP reverse proxy based fasthttp

    • it's faster than golang standard httputil.ReverseProxy library.
    • implemented by fasthttp.HostClient
    • support balance distribute based rounddobin
    • HostClient object pool with an overlay of fasthttp connection pool.
  • WebSocket reverse proxy.

Get started

HTTP (with balancer option)
var (
	proxyServer = proxy.NewReverseProxy("localhost:8080")

	// use with balancer
	// weights = map[string]proxy.Weight{
	// 	"localhost:8080": 20,
	// 	"localhost:8081": 30,
	// 	"localhost:8082": 50,
	// }
	// proxyServer = proxy.NewReverseProxy("", proxy.WithBalancer(weights))

)

// ProxyHandler ... fasthttp.RequestHandler func
func ProxyHandler(ctx *fasthttp.RequestCtx) {
	// all proxy to localhost
	proxyServer.ServeHTTP(ctx)
}

func main() {
	if err := fasthttp.ListenAndServe(":8081", ProxyHandler); err != nil {
		log.Fatal(err)
	}
}
Websocket
var (
	proxyServer *proxy.WSReverseProxy
	once        sync.Once
)

// ProxyHandler ... fasthttp.RequestHandler func
func ProxyHandler(ctx *fasthttp.RequestCtx) {
	once.Do(func() {
		var err error
		proxyServer, err = proxy.NewWSReverseProxyWith(
			proxy.WithURL_OptionWS("ws://localhost:8080/echo"),
			// [OPTIONAL]: you can override path from `WithURL_OptionWS`
			//             by providing WithDynamicPath_OptionWS.
			proxy.WithDynamicPath_OptionWS(true, proxy.DefaultOverrideHeader),
		)
		if err != nil {
			panic(err)
		}
	})

	switch string(ctx.Path()) {
	case "/echo":
		// [OPTIONAL]: you can override path from `WithURL_OptionWS`
		//             by providing proxy.DefaultOverrideHeader (or any custom) header  
		// ctx.Request.Header.Set(proxy.DefaultOverrideHeader, "/real_echo")
		proxyServer.ServeHTTP(ctx)
	case "/":
		fasthttp.ServeFileUncompressed(ctx, "./index.html")
	default:
		ctx.Error("Unsupported path", fasthttp.StatusNotFound)
	}
}

func main() {
	log.Println("serving on: 8081")
	if err := fasthttp.ListenAndServe(":8081", ProxyHandler); err != nil {
		log.Fatal(err)
	}
}

Usages

Contrast

References

Thanks

JetBrains

Documentation

Overview

Package proxy of reverse handler based fasthttp this lib ref to: Issue: https://github.com/valyala/fasthttp/issues/64 Code: https://golang.org/src/net/http/httputil/reverseproxy.go Pool Ref: https://github.com/fatih/pool/blob/master/channel.

Index

Constants

This section is empty.

Variables

View Source
var (
	// DefaultUpgrader specifies the parameters for upgrading an HTTP
	// connection to a WebSocket connection.
	DefaultUpgrader = &websocket.FastHTTPUpgrader{
		ReadBufferSize:  1024,
		WriteBufferSize: 1024,
	}

	// DefaultDialer is a dialer with all fields set to the default zero values.
	DefaultDialer = websocket.DefaultDialer

	// DefaultOverrideHeader is a default header value for using in dymanic path feature
	DefaultOverrideHeader = "PROXY-OVERRIDE-PATH"
)

Functions

This section is empty.

Types

type Factory

type Factory func(string) (*ReverseProxy, error)

Factory the generator to creat ReverseProxy

type IBalancer

type IBalancer interface {
	Distribute() int
}

IBalancer .

func NewBalancer

func NewBalancer(ws []W) IBalancer

NewBalancer constructs a IBalancer instance which implements roundrobin algorithm.

type Option

type Option interface {
	// contains filtered or unexported methods
}

Option to define all options to reverse http proxy.

func WithAddress added in v2.2.3

func WithAddress(addresses ...string) Option

WithAddress generate address options

func WithBalancer

func WithBalancer(addrWeights map[string]Weight) Option

WithBalancer generate balancer options

func WithDebug added in v2.2.3

func WithDebug() Option

func WithDisablePathNormalizing added in v2.2.3

func WithDisablePathNormalizing(isDisablePathNormalizing bool) Option

WithDisablePathNormalizing sets whether disable path normalizing.

func WithMaxConnDuration added in v2.2.3

func WithMaxConnDuration(d time.Duration) Option

WithMaxConnDuration sets maxConnDuration of hostClient, which means keep-alive connections are closed after this duration.

func WithTLS

func WithTLS(certFile, keyFile string) Option

WithTLS build tls.Config with server certFile and keyFile. tlsConfig is nil as default

func WithTLSConfig

func WithTLSConfig(config *tls.Config) Option

func WithTimeout

func WithTimeout(d time.Duration) Option

WithTimeout specify the timeout of each request

type OptionWS added in v2.2.0

type OptionWS interface {
	// contains filtered or unexported methods
}

OptionWS to define all options to reverse web socket proxy.

func WithDebug_OptionWS added in v2.2.3

func WithDebug_OptionWS() OptionWS

WithDebug_OptionWS is used to enable debug mode.

func WithDialer_OptionWS added in v2.2.0

func WithDialer_OptionWS(dialer *websocket.Dialer) OptionWS

WithDialer_OptionWS use specified dialer

func WithDynamicPath_OptionWS added in v2.2.3

func WithDynamicPath_OptionWS(t bool, header ...string) OptionWS

WithDynamicPath_OptionWS enable/disable dynamic path overriding explicitly WithDynamicPath_OptionWS(true)

func WithForwardHeadersHandlers_OptionWS added in v2.2.0

func WithForwardHeadersHandlers_OptionWS(handler forwardHeaderHandler) OptionWS

WithForwardHeadersHandlers_OptionWS allows users to customize forward headers.

func WithURL_OptionWS added in v2.2.0

func WithURL_OptionWS(u string) OptionWS

WithURL_OptionWS specify the url to backend websocket server. WithURL_OptionWS("ws://YOUR_WEBSOCKET_HOST:PORT/AND/PATH")

func WithUpgrader_OptionWS added in v2.2.0

func WithUpgrader_OptionWS(upgrader *websocket.FastHTTPUpgrader) OptionWS

WithUpgrader_OptionWS use specified upgrader.

type Pool

type Pool interface {
	// Get returns a new ReverseProxy from the pool.
	Get(string) (*ReverseProxy, error)

	// Put Reseting the ReverseProxy puts it back to the Pool.
	Put(*ReverseProxy) error

	// Close closes the pool and all its connections. After Close() the pool is
	// no longer usable.
	Close()

	// Len returns the current number of connections of the pool.
	Len() int
}

Pool interface ... this interface ref to: https://github.com/fatih/pool/blob/master/pool.go

func NewChanPool

func NewChanPool(initialCap, maxCap int, factory Factory) (Pool, error)

NewChanPool to new a pool with some params

type Proxier

type Proxier interface {
	ServeHTTP(ctx *fasthttp.RequestCtx)
	// ?
	SetClient(addr string) Proxier

	// Reset .
	Reset()

	// Close .
	Close()
}

Proxier can be HTTP or WebSocket proxier TODO:

type ReverseProxy

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

ReverseProxy reverse handler using fasthttp.HostClient

func NewReverseProxyWith added in v2.2.3

func NewReverseProxyWith(options ...Option) (*ReverseProxy, error)

NewReverseProxyWith create an ReverseProxy with options

func (*ReverseProxy) Close

func (p *ReverseProxy) Close()

Close ... clear and release

func (*ReverseProxy) Reset

func (p *ReverseProxy) Reset()

Reset ...

func (*ReverseProxy) ServeHTTP

func (p *ReverseProxy) ServeHTTP(ctx *fasthttp.RequestCtx)

ServeHTTP ReverseProxy to serve ref to: https://golang.org/src/net/http/httputil/reverseproxy.go#L169

func (*ReverseProxy) SetClient

func (p *ReverseProxy) SetClient(addr string) *ReverseProxy

SetClient ...

type W

type W interface {
	Weight() int
}

W is an interface which should be implemented by the type which will be used in balancer.

type WSReverseProxy

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

WSReverseProxy . refer to https://github.com/koding/websocketproxy

func NewWSReverseProxyWith added in v2.2.0

func NewWSReverseProxyWith(options ...OptionWS) (*WSReverseProxy, error)

NewWSReverseProxyWith constructs a new WSReverseProxy with options.

func (*WSReverseProxy) ServeHTTP

func (w *WSReverseProxy) ServeHTTP(ctx *fasthttp.RequestCtx)

ServeHTTP WSReverseProxy to serve

type Weight

type Weight uint

Weight .

func (Weight) Weight

func (w Weight) Weight() int

Jump to

Keyboard shortcuts

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