parapet

package module
v0.10.0 Latest Latest
Warning

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

Go to latest
Published: Apr 24, 2021 License: MIT Imports: 19 Imported by: 19

README

parapet

Build Status codecov Go Report Card GoDoc

Reverse Proxy Framework

Example

package main

import (
	"log"

	"github.com/moonrhythm/parapet"
	"github.com/moonrhythm/parapet/pkg/body"
	"github.com/moonrhythm/parapet/pkg/compress"
	"github.com/moonrhythm/parapet/pkg/headers"
	"github.com/moonrhythm/parapet/pkg/healthz"
	"github.com/moonrhythm/parapet/pkg/host"
	"github.com/moonrhythm/parapet/pkg/hsts"
	"github.com/moonrhythm/parapet/pkg/location"
	"github.com/moonrhythm/parapet/pkg/logger"
	"github.com/moonrhythm/parapet/pkg/ratelimit"
	"github.com/moonrhythm/parapet/pkg/redirect"
	"github.com/moonrhythm/parapet/pkg/requestid"
	"github.com/moonrhythm/parapet/pkg/upstream"
)

func main() {
	s := parapet.New()
	s.Use(logger.Stdout())
	s.Use(requestid.New())
	s.Use(ratelimit.FixedWindowPerSecond(60))
	s.Use(ratelimit.FixedWindowPerMinute(300))
	s.Use(ratelimit.FixedWindowPerHour(2000))
	s.Use(body.LimitRequest(15 * 1024 * 1024)) // 15 MiB
	s.Use(body.BufferRequest())
	s.Use(compress.Gzip())
	s.Use(compress.Br())
	
	// sites
	s.Use(example())
	s.Use(mysite())
	s.Use(wordpress())
	
	// health check
	{
		l := location.Exact("/healthz")
		l.Use(logger.Disable())
		l.Use(healthz.New())
		s.Use(l)
	}
	
	s.Addr = ":8080"
	err := s.ListenAndServe()
	if err != nil {
		log.Fatal(err)
	}
}

func example() parapet.Middleware {
	h := host.New("example.com", "www.example.com")
	h.Use(ratelimit.FixedWindowPerSecond(20))
	h.Use(redirect.HTTPS())
	h.Use(hsts.Preload())
	h.Use(redirect.NonWWW())
	h.Use(upstream.New(upstream.NewRoundRobinLoadBalancer([]*upstream.Target{
		{Host: "example.default.svc.cluster.local:8080", Transport: &upstream.HTTPTransport{}},
		{Host: "example1.default.svc.cluster.local:8080", Transport: &upstream.H2CTransport{}},
		{Host: "myexamplebackuphost.com", Transport: &upstream.HTTPSTransport{}},
	})))
	
	return h
}

func mysite() parapet.Middleware {
	var hs parapet.Middlewares
	
	{
		h := host.New("mysiteaaa.io", "www.mysiteaaa.io")
		h.Use(ratelimit.FixedWindowPerSecond(15))
		h.Use(redirect.HTTPS())
		h.Use(hsts.Preload())
		h.Use(redirect.WWW())
		h.Use(headers.DeleteResponse(
			"Server",
			"x-goog-generation",
			"x-goog-hash",
			"x-goog-meta-goog-reserved-file-mtime",
			"x-goog-metageneration",
			"x-goog-storage-class",
			"x-goog-stored-content-encoding",
			"x-goog-stored-content-length",
			"x-guploader-uploadid",
		))
		h.Use(upstream.SingleHost("storage.googleapis.com", &upstream.HTTPSTransport{}))
	
		hs.Use(h)
	}
	
	{
		h := host.New("mail.mysiteaaa.io")
		h.Use(redirect.HTTPS())
		h.Use(hsts.Preload())
		h.Use(redirect.To("https://mail.google.com/a/mysiteaaa.io", 302))
	
		hs.Use(h)
	}
	
	return hs
}

func wordpress() parapet.Middleware {
	h := host.New("myblogaaa.com", "www.myblogaaa.com")
	h.Use(ratelimit.FixedWindowPerMinute(150))
	h.Use(redirect.HTTPS())
	h.Use(hsts.Preload())
	h.Use(redirect.NonWWW())
	
	backend := upstream.SingleHost("wordpress.default.svc.cluster.local", &upstream.HTTPTransport{})
	
	l := location.RegExp(`\.(js|css|svg|png|jp(e)?g|gif)$`)
	l.Use(headers.SetResponse("Cache-Control", "public, max-age=31536000"))
	l.Use(backend)
	h.Use(l)
	
	h.Use(backend)
	
	return h
}

License

MIT

Documentation

Index

Constants

This section is empty.

Variables

View Source
var ServerContextKey = serverContextKey{}

ServerContextKey is the context key that store *parapet.Server

Functions

func GenerateSelfSignCertificate added in v0.7.2

func GenerateSelfSignCertificate(opt SelfSign) (cert tls.Certificate, err error)

GenerateSelfSignCertificate generates new self sign certificate

Types

type Block

type Block interface {
	Middleware
	Use(Middleware)
}

Block is the middleware block

type Conditional added in v0.5.0

type Conditional func(r *http.Request) bool

Conditional returns condition for given request

func TrustCIDRs added in v0.5.0

func TrustCIDRs(s []string) Conditional

TrustCIDRs trusts given CIDR list

func Trusted added in v0.5.0

func Trusted() Conditional

Trusted trusts all remotes

type Handler added in v0.7.1

type Handler http.HandlerFunc

Handler wraps http handler func with parapet's middleware

func (Handler) ServeHTTP added in v0.7.1

func (h Handler) ServeHTTP(w http.ResponseWriter, r *http.Request)

func (Handler) ServeHandler added in v0.7.1

func (h Handler) ServeHandler(_ http.Handler) http.Handler

type Middleware

type Middleware interface {
	ServeHandler(http.Handler) http.Handler
}

Middleware is the http middleware

type MiddlewareFunc

type MiddlewareFunc func(http.Handler) http.Handler

MiddlewareFunc is the adapter type for Middleware

func (MiddlewareFunc) ServeHandler

func (f MiddlewareFunc) ServeHandler(h http.Handler) http.Handler

ServeHandler calls f

type Middlewares

type Middlewares []Middleware

Middlewares type

func (Middlewares) ServeHandler

func (ms Middlewares) ServeHandler(h http.Handler) http.Handler

ServeHandler implements middleware interface

func (*Middlewares) Use

func (ms *Middlewares) Use(m Middleware)

Use uses middleware

type SelfSign added in v0.7.2

type SelfSign struct {
	CommonName string
	Hosts      []string
	NotBefore  time.Time
	NotAfter   time.Time
}

SelfSign options

type Server

type Server struct {
	Addr               string
	Handler            http.Handler
	ReadTimeout        time.Duration
	ReadHeaderTimeout  time.Duration
	WriteTimeout       time.Duration
	IdleTimeout        time.Duration
	TCPKeepAlivePeriod time.Duration
	GraceTimeout       time.Duration
	WaitBeforeShutdown time.Duration
	ErrorLog           *log.Logger
	TrustProxy         Conditional
	H2C                bool
	ReusePort          bool
	ConnState          func(conn net.Conn, state http.ConnState)
	TLSConfig          *tls.Config
	// contains filtered or unexported fields
}

Server is the parapet server

func New

func New() *Server

New creates new middleware server default config

This server should not expose to the internet but run behind reverse proxy

func NewBackend

func NewBackend() *Server

NewBackend creates new backend server default config

This server use to run behind parapet server or run behind other reverse proxy

func NewFrontend

func NewFrontend() *Server

NewFrontend creates new frontend server default config

func (*Server) ListenAndServe

func (s *Server) ListenAndServe() error

ListenAndServe starts web server

func (*Server) ModifyConnection added in v0.6.0

func (s *Server) ModifyConnection(f func(conn net.Conn) net.Conn)

ModifyConnection modifies connection before send to http

func (*Server) RegisterOnShutdown added in v0.1.2

func (s *Server) RegisterOnShutdown(f func())

RegisterOnShutdown calls f when server received SIGTERM

func (*Server) Serve

func (s *Server) Serve(l net.Listener) error

Serve serves incoming connections

func (*Server) ServeHTTP

func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request)

func (*Server) Shutdown

func (s *Server) Shutdown() error

Shutdown gracefully shutdowns server

func (*Server) Use

func (s *Server) Use(m Middleware)

Use uses middleware

Jump to

Keyboard shortcuts

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