Documentation
¶
Index ¶
- Constants
- Variables
- func CORS(opts CORSOption) func(http.Handler) http.Handler
- func Compress(level int, types ...string) func(next http.Handler) http.Handler
- func GetReqID(ctx context.Context) string
- func Helmet(opt HelmetOption) func(http.Handler) http.Handler
- func NextRequestID() uint64
- func RealIP(h http.Handler) http.Handler
- func RequestID(next http.Handler) http.Handler
- func RequestSize(bytes int64) func(http.Handler) http.Handler
- type CDP
- type CORSOption
- type CSP
- type Compressor
- type Embedder
- type EncoderFunc
- type HelmetOption
- type Opener
- type OriginValidator
- type Referrer
- type Resource
- type TransportSecurity
- type XFrame
Constants ¶
const ( YearDuration = 365 * 24 * 60 * 60 // OpenerSameOrigin is default if no value supplied OpenerSameOrigin Opener = "same-origin" OpenerSameOriginAllowPopups Opener = "same-origin-allow-popups" OpenerUnsafeNone Opener = "unsafe-none" // EmbedderDefault is default if no value supplied EmbedderRequireCorp Embedder = "require-corp" EmbedderCredentialLess Embedder = "credentialless" EmbedderUnsafeNone Embedder = "unsafe-none" // ResourceDefault default value will be "same-origin" ResourceSameOrigin Resource = "same-origin" ResourceSameSite Resource = "same-site" ResourceCrossOrigin Resource = "cross-origin" NoReferrer Referrer = "no-referrer" NoReferrerWhenDowngrade Referrer = "no-referrer-when-downgrade" SameOrigin Referrer = "same-origin" Origin Referrer = "origin" StrictOrigin Referrer = "strict-origin" OriginWhenCrossOrigin Referrer = "origin-when-cross-origin" StrictOriginWhenCrossOrigin Referrer = "strict-origin-when-cross-origin" UnsafeUrl Referrer = "unsafe-url" // CDPNone is default if no value supplied CDPNone CDP = "none" CDPMasterOnly CDP = "master-only" CDPByContentType CDP = "by-content-type" CDPAll CDP = "all" // XFrameSameOrigin is default if no value supplied XFrameSameOrigin XFrame = "sameorigin" XFrameDeny XFrame = "deny" )
const RequestIDKey ctxKeyRequestID = 0
RequestIDKey is the key that holds the unique request ID in a request context.
Variables ¶
var RequestIDHeader = "X-Request-Id"
RequestIDHeader is the name of the HTTP Header which contains the request id. Exported so that it can be changed by developers
Functions ¶
func CORS ¶
func CORS(opts CORSOption) func(http.Handler) http.Handler
CORS provides Cross-Origin Resource Sharing middleware. Example:
import (
"net/http"
"gitserver.in/patialtech/mux/middleware"
"gitserver.in/patialtech/mux"
)
func main() {
r := mux.NewRouter()
r.Use(middleware.CORS(middleware.CORSOption{
AllowedOrigins: []string{"*"},
MaxAge: 60,
}))
r.Get("/", func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("hello there"))
})
r.Serve(func(srv *http.Server) error {
srv.Addr = ":3001"
slog.Info("listening on http://localhost" + srv.Addr)
return srv.ListenAndServe()
})
}
func Compress ¶ added in v1.1.0
Compress is a middleware that compresses response body of a given content types to a data format based on Accept-Encoding request header. It uses a given compression level.
NOTE: make sure to set the Content-Type header on your response otherwise this middleware will not compress the response body. For ex, in your handler you should set w.Header().Set("Content-Type", http.DetectContentType(yourBody)) or set it manually.
Passing a compression level of 5 is sensible value
func GetReqID ¶ added in v1.2.0
GetReqID returns a request ID from the given context if one is present. Returns the empty string if a request ID cannot be found.
func Helmet ¶
func Helmet(opt HelmetOption) func(http.Handler) http.Handler
Helmet headers to secure server response
func NextRequestID ¶ added in v1.2.0
func NextRequestID() uint64
NextRequestID generates the next request ID in the sequence.
func RealIP ¶ added in v1.2.0
RealIP is a middleware that sets a http.Request's RemoteAddr to the results of parsing either the True-Client-IP, X-Real-IP or the X-Forwarded-For headers (in that order).
This middleware should be inserted fairly early in the middleware stack to ensure that subsequent layers (e.g., request loggers) which examine the RemoteAddr will see the intended value.
You should only use this middleware if you can trust the headers passed to you (in particular, the three headers this middleware uses), for example because you have placed a reverse proxy like HAProxy or nginx in front of chi. If your reverse proxies are configured to pass along arbitrary header values from the client, or if you use this middleware without a reverse proxy, malicious clients will be able to make you very sad (or, depending on how you're using RemoteAddr, vulnerable to an attack of some sort).
func RequestID ¶ added in v1.2.0
RequestID is a middleware that injects a request ID into the context of each request. A request ID is a string of the form "host.example.com/random-0001", where "random" is a base62 random string that uniquely identifies this go process, and where the last number is an atomically incremented request counter.
Types ¶
type CORSOption ¶
type CORSOption struct {
// AllowedOrigins list, including "*" will allow all
AllowedOrigins []string
// AllowedHeaders are a list of headers clients are allowed to use with.
// default: []string{"Accept", "Accept-Language", "Content-Language", "Origin"}
AllowedHeaders []string
// AllowedMethods are a list of methods clients are allowed to use.
//
// default: []string{"HEAD", "GET", "POST"}
AllowedMethods []string
ExposedHeaders []string
// MaxAge in seconds, max allowed value is 600
MaxAge uint
AllowCredentials bool
}
CORSOption represents a functional option for configuring the CORS middleware.
type CSP ¶
type CSP struct {
// default-src, default value will be 'self'
DefaultSrc []string
// script-src, default value will be 'self'
ScriptSrc []string
// script-src-attr, default value will be 'none'
ScriptSrcAttr []string
// style-src, default value will be 'self' https: 'unsafe-inline'
StyleSrc []string
// img-src, default value will be 'self' data:
ImgSrc []string
// object-src, default value will be 'none'
ObjectSrc []string
// base-uri, default value will be 'self'
BaseUri []string
// font-src, default value will be 'self' https: data:
FontSrc []string
// form-action, default value will be 'self'
FormAction []string
// frame-ancestors, default value will be 'self'
FrameAncestors []string
UpgradeInsecureRequests bool
}
CSP is Content-Security-Policy settings
https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy/Sources
type Compressor ¶ added in v1.1.0
type Compressor struct {
// contains filtered or unexported fields
}
Compressor represents a set of encoding configurations.
func NewCompressor ¶ added in v1.1.0
func NewCompressor(level int, types ...string) *Compressor
NewCompressor creates a new Compressor that will handle encoding responses.
The level should be one of the ones defined in the flate package. The types are the content types that are allowed to be compressed.
func (*Compressor) Handler ¶ added in v1.1.0
func (c *Compressor) Handler(next http.Handler) http.Handler
Handler returns a new middleware that will compress the response based on the current Compressor.
func (*Compressor) SetEncoder ¶ added in v1.1.0
func (c *Compressor) SetEncoder(encoding string, fn EncoderFunc)
SetEncoder can be used to set the implementation of a compression algorithm.
The encoding should be a standardised identifier. See: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Accept-Encoding
For example, add the Brotli algorithm:
import brotli_enc "gopkg.in/kothar/brotli-go.v0/enc"
compressor := middleware.NewCompressor(5, "text/html")
compressor.SetEncoder("br", func(w io.Writer, level int) io.Writer {
params := brotli_enc.NewBrotliParams()
params.SetQuality(level)
return brotli_enc.NewBrotliWriter(params, w)
})
type EncoderFunc ¶ added in v1.1.0
An EncoderFunc is a function that wraps the provided io.Writer with a streaming compression algorithm and returns it.
In case of failure, the function should return nil.
type HelmetOption ¶
type HelmetOption struct {
StrictTransportSecurity *TransportSecurity
XFrameOption XFrame
CrossOriginEmbedderPolicy Embedder
CrossOriginOpenerPolicy Opener
CrossOriginResourcePolicy Resource
CrossDomainPolicies CDP
ReferrerPolicy []Referrer
ContentSecurityPolicy CSP
OriginAgentCluster bool
DisableXDownload bool
DisableDNSPrefetch bool
DisableSniffMimeType bool
XssProtection bool
}
type OriginValidator ¶
OriginValidator takes an origin string and returns whether that origin is allowed.