middleware

package
v1.13.2 Latest Latest
Warning

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

Go to latest
Published: Feb 28, 2024 License: MIT Imports: 32 Imported by: 16

README

Middlewares

elton中将常用的中间件已经在middleware中实现,详细使用方法可参考middlewares

Documentation

Overview

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

Index

Constants

View Source
const (

	// LoggerCommon combined log format
	LoggerCombined = `{remote} {when-iso} "{method} {uri} {proto}" {status} {size-human} "{referer}" "{userAgent}"`
	// LoggerCommon common log format
	LoggerCommon = `{remote} {when-iso} "{method} {uri} {proto}" {status} {size-human}`
	// LoggerShort short log format
	LoggerShort = `{remote} {method} {uri} {proto} {status} {size-human} - {latency-ms} ms`
	// LoggerTiny tiny log format
	LoggerTiny = `{method} {url} {status} {size-human} - {latency-ms} ms`
)
View Source
const (
	// ErrProxyCategory proxy error category
	ErrProxyCategory = "elton-proxy"
	ProxyTargetKey   = "proxyTarget"
)
View Source
const (
	// HandleSuccess handle success
	HandleSuccess = iota
	// HandleFail handle fail
	HandleFail
)
View Source
const (
	// DefaultCompressMinLength min compress length(1KB)
	DefaultCompressMinLength = 1024
)
View Source
const (

	// ErrBasicAuthCategory basic auth error category
	ErrBasicAuthCategory = "elton-basic-auth"
)
View Source
const (
	// ErrBodyParserCategory body parser error category
	ErrBodyParserCategory = "elton-body-parser"
)
View Source
const (

	// ErrConcurrentLimiterCategory concurrent limiter error category
	ErrConcurrentLimiterCategory = "elton-concurrent-limiter"
)
View Source
const (
	// ErrErrorCategory error category of error handler
	ErrErrorCategory = "elton-error"
)
View Source
const (
	// ErrRCLCategory router concurrent limiter error category
	ErrRCLCategory = "elton-router-concurrent-limiter"
)
View Source
const (
	// ErrRecoverCategory recover error category
	ErrRecoverCategory = "elton-recover"
)
View Source
const ErrRendererCategory = "elton-renderer"
View Source
const (
	// ErrResponderCategory responder error category
	ErrResponderCategory = "elton-responder"
)
View Source
const (
	ErrResponseSizeLimiterCategory = "elton-response-size-limiter"
)
View Source
const (
	// ErrStaticServeCategory static serve error category
	ErrStaticServeCategory = "elton-static-serve"
)
View Source
const HeaderAge = "Age"
View Source
const HeaderXCache = "X-Cache"
View Source
const IgnoreCompression = -128
View Source
const MaxShortHeader = uint8(128)
View Source
const NoneMatchHeader = math.MaxUint8

Variables

View Source
var (
	// ErrBasicAuthUnauthorized unauthorized err
	ErrBasicAuthUnauthorized = getBasicAuthError(errors.New("unAuthorized"), http.StatusUnauthorized)
	// ErrBasicAuthRequireValidateFunction require validate function
	ErrBasicAuthRequireValidateFunction = errors.New("require validate function")
)
View Source
var (
	// ErrSubmitTooFrequently submit too frequently
	ErrSubmitTooFrequently = &hes.Error{
		StatusCode: http.StatusBadRequest,
		Message:    "submit too frequently",
		Category:   ErrConcurrentLimiterCategory,
	}
	// ErrTooManyRequests too many request
	ErrTooManyRequests = &hes.Error{
		StatusCode: http.StatusTooManyRequests,
		Message:    "too many Requests",
		Category:   ErrConcurrentLimiterCategory,
	}
	// ErrNotAllowEmpty not allow empty
	ErrNotAllowEmpty = &hes.Error{
		StatusCode: http.StatusBadRequest,
		Message:    "empty value is not allowed",
		Category:   ErrConcurrentLimiterCategory,
	}
	ErrRequireLockFunction = errors.New("require lock function")
)
View Source
var (
	// ErrProxyTargetIsNil target is nil
	ErrProxyTargetIsNil = &hes.Error{
		Exception:  true,
		Message:    "target can not be nil",
		StatusCode: http.StatusBadRequest,
		Category:   ErrProxyCategory,
	}
	ErrProxyNoTargetFunction = errors.New("require target or targer picker")
)
View Source
var (
	ErrTemplateTypeInvalid = &hes.Error{
		Exception:  true,
		StatusCode: 500,
		Message:    "template type is invalid",
		Category:   ErrRendererCategory,
	}
	ErrFileAndTextNil = &hes.Error{
		Exception:  true,
		StatusCode: 500,
		Message:    "file and text can not be nil",
		Category:   ErrRendererCategory,
	}
)
View Source
var (
	// ErrStaticServeNotAllowQueryString not all query string
	ErrStaticServeNotAllowQueryString = getStaticServeError("static serve not allow query string", http.StatusBadRequest)
	// ErrStaticServeFsIsNil static fs is nil
	ErrStaticServeFsIsNil = getStaticServeError("static fs is nil", http.StatusBadRequest)
	// ErrStaticServeNotFound static file not found
	ErrStaticServeNotFound = getStaticServeError("static file not found", http.StatusNotFound)
	// ErrStaticServeOutOfPath file out of path
	ErrStaticServeOutOfPath = getStaticServeError("out of path", http.StatusBadRequest)
	// ErrStaticServeNotAllowAccessDot file include dot
	ErrStaticServeNotAllowAccessDot = getStaticServeError("static server not allow with dot", http.StatusBadRequest)
)
View Source
var (
	// DefaultCompressRegexp compress text, javascript, json and wasm
	DefaultCompressRegexp = regexp.MustCompile("text|javascript|json|wasm|font")
)
View Source
var DefaultShortHeaders = []string{
	"accept-charset",
	"accept-encoding",
	"accept-language",
	"accept-ranges",
	"accept",
	"access-control-allow-origin",
	"age",
	"allow",
	"authorization",
	"cache-control",
	"content-disposition",
	"content-encoding",
	"content-language",
	"content-length",
	"content-location",
	"content-range",
	"content-type",
	"cookie",
	"date",
	"etag",
	"expect",
	"expires",
	"from",
	"host",
	"if-match",
	"if-modified-since",
	"if-none-match",
	"if-range",
	"if-unmodified-since",
	"last-modified",
	"link",
	"location",
	"max-forwards",
	"proxy-authenticate",
	"proxy-authorization",
	"range",
	"referer",
	"refresh",
	"retry-after",
	"server",
	"set-cookie",
	"strict-transport-security",
	"transfer-encoding",
	"user-agent",
	"vary",
	"via",
	"www-authenticate",
}
View Source
var (
	ErrInvalidJSON = &hes.Error{
		Category:   ErrBodyParserCategory,
		Message:    "invalid json format",
		StatusCode: http.StatusBadRequest,
	}
)
View Source
var (
	// ErrInvalidResponse invalid response(body an status is nil)
	ErrInvalidResponse = &hes.Error{
		Exception:  true,
		StatusCode: 500,
		Message:    "invalid response",
		Category:   ErrResponderCategory,
	}
)
View Source
var (
	ErrRCLRequireLimiter = errors.New("require limiter")
)
View Source
var ErrResponseTooLarge = &hes.Error{
	Category:   ErrResponseSizeLimiterCategory,
	Message:    "body of response is too large",
	StatusCode: http.StatusInternalServerError,
}
View Source
var (
	ErrStatsNoFunction = errors.New("require on stats function")
)
View Source
var (
	ErrTrackerNoFunction = errors.New("require on track function")
)

Functions

func AcceptEncoding added in v0.5.3

func AcceptEncoding(c *elton.Context, encoding string) (bool, string)

AcceptEncoding check request accept encoding

func BrotliCompress added in v1.8.0

func BrotliCompress(buf []byte, level int) (*bytes.Buffer, error)

BrotliCompress compress data by brotli

func BrotliDecompress added in v1.8.0

func BrotliDecompress(buf []byte) (*bytes.Buffer, error)

BrotliDecompress decompress data of brotli

func DefaultJSONAndFormContentTypeValidate added in v0.4.4

func DefaultJSONAndFormContentTypeValidate(c *elton.Context) bool

DefaultJSONAndFormContentTypeValidate for validate json content type and form url encoded content type

func DefaultJSONContentTypeValidate added in v0.4.4

func DefaultJSONContentTypeValidate(c *elton.Context) bool

DefaultJSONContentTypeValidate for validate json content type

func GetCacheMaxAge added in v1.8.0

func GetCacheMaxAge(header http.Header) int

GetCacheMaxAge returns the age of cache, get value from cache-control(s-maxage or max-age)

func GzipCompress added in v1.8.0

func GzipCompress(buf []byte, level int) (*bytes.Buffer, error)

GzipCompress compress data by gzip

func GzipDecompress added in v1.8.0

func GzipDecompress(buf []byte) (*bytes.Buffer, error)

GzipDecompress decompress data of gzip

func IsPassCacheMethod added in v1.8.0

func IsPassCacheMethod(reqMethod string) bool

IsPassCacheMethod is the method pass cache

func MaxBytesReader added in v0.4.4

func MaxBytesReader(r io.ReadCloser, n int64) *maxBytesReader

func NewBasicAuth added in v0.5.0

func NewBasicAuth(config BasicAuthConfig) elton.Handler

NewBasicAuth create a basic auth middleware, it will throw an error if the the validate function is nil.

func NewBodyParser added in v0.4.4

func NewBodyParser(config BodyParserConfig) elton.Handler

NewBodyParser returns a new body parser middleware. If limit < 0, it will be no limit for the body data. If limit = 0, it will use the default limit(50KB) for the body data. JSON content type validate is the default content validate function.

func NewCache added in v1.8.0

func NewCache(config CacheConfig) elton.Handler

NewCache return a new cache middleware.

func NewCompress added in v0.5.3

func NewCompress(config CompressConfig) elton.Handler

NewCompress return a new compress middleware. It will use 'text|javascript|json|wasm|font' as default content type checker for compress. It will throw a panic if the compressors is empty.

func NewConcurrentLimiter added in v0.5.2

func NewConcurrentLimiter(config ConcurrentLimiterConfig) elton.Handler

NewConcurrentLimiter returns a new concurrent limiter middleware. It will throw a panic if Lock function is nil.

func NewDefaultBasicAuth added in v1.2.0

func NewDefaultBasicAuth(account, password string) elton.Handler

NewDefaultBasicAuth returns a new basic auth middleware, it will check the account and password, it will returns an error if check failed

func NewDefaultBodyParser added in v0.4.4

func NewDefaultBodyParser() elton.Handler

NewDefaultBodyParser returns a new default body parser, which include gzip and json decoder. The body size is limited to 50KB.

func NewDefaultCache added in v1.8.0

func NewDefaultCache(store CacheStore) elton.Handler

NewDefaultCache return a new cache middleware with brotli compress

func NewDefaultCompress added in v0.5.3

func NewDefaultCompress() elton.Handler

NewDefaultCompress return a new compress middleware, it include gzip compress

func NewDefaultETag added in v0.5.0

func NewDefaultETag() elton.Handler

NewDefaultETag returns a default ETag middleware, it will use sha1 to generate etag.

func NewDefaultError

func NewDefaultError() elton.Handler

NewDefaultError return a new error handler, it will convert the error to hes.Error and response. JSON will be used is client's request accept header support application/json, otherwise text will be used.

func NewDefaultFresh added in v0.5.0

func NewDefaultFresh() elton.Handler

NewDefaultFresh returns a default fresh middleware, it will return 304 modified if the data is not modified.

func NewDefaultResponder

func NewDefaultResponder() elton.Handler

NewDefaultResponder returns a new default responder middleware, it will use json.Marshal and application/json for response.

func NewDefaultStaticServe added in v0.5.0

func NewDefaultStaticServe(config StaticServeConfig) elton.Handler

NewDefaultStaticServe returns a new default static server middleware using FS

func NewETag added in v0.5.0

func NewETag(config ETagConfig) elton.Handler

NewETag returns a default ETag middleware.

func NewEmbedStaticFS added in v1.3.0

func NewEmbedStaticFS(fs embed.FS, prefix string) *embedStaticFS

NewEmbedStaticFS returns a new embed static fs

func NewEncodingStaticServe added in v1.13.2

func NewEncodingStaticServe(config StaticServeConfig, selector EncodingFsSelector) elton.Handler

func NewError

func NewError(config ErrorConfig) elton.Handler

NewError return a new error handler.

func NewFresh added in v0.5.0

func NewFresh(config FreshConfig) elton.Handler

NewFresh returns a fresh middleware.

func NewGlobalConcurrentLimiter added in v1.0.5

func NewGlobalConcurrentLimiter(config GlobalConcurrentLimiterConfig) elton.Handler

NewGlobalConcurrentLimiter returns a new global concurrent limiter, it use for global processing request limit.

func NewLogger added in v0.5.1

func NewLogger(config LoggerConfig) elton.Handler

NewLogger returns a new logger middleware, it can log the field of query string, header, cookie and context. It will throw a panic if the Format is empty. It will throw a panic if the OnLog function is nil.

func NewLruStore added in v1.11.3

func NewLruStore(size int) *lruStore

NewLruStore creates a lru store

func NewPeekLruStore added in v1.11.3

func NewPeekLruStore(size int) *lruStore

NewPeekLruStore creates a lru store use peek

func NewPrefixURL added in v1.9.3

func NewPrefixURL(prefix ...string) elton.PreHandler

NewPrefixURL returns a new prefix url handler, it will replace the prefix of url as ""

func NewProxy added in v0.5.0

func NewProxy(config ProxyConfig) elton.Handler

NewProxy returns a new proxy middleware, it can proxy the request to other server. It will throw a panic if Target and TargetPicker function is nil. It will throw a panic if Rewrites config is not a regexp.

func NewRCL added in v0.5.2

func NewRCL(config RCLConfig) elton.Handler

NewRCL returns a router concurrent limiter middleware. It will throw panic if Limiter is nil.

func NewRecover added in v0.5.0

func NewRecover() elton.Handler

NewRecover return a recover middleware, it can recover from panic, and then emit an `elton-recover` error. Suggest to graceful close the elton instance for recover error.

func NewRenderer added in v1.6.0

func NewRenderer(config RendererConfig) elton.Handler

NewRenderer returns a new renderer middleware. It will render the template with data, and set response data as html.

func NewResponder

func NewResponder(config ResponderConfig) elton.Handler

NewResponder returns a new responder middleware. If will use json.Marshal as default marshal function. If will use application/json as default content type.

func NewResponseSizeLimiter added in v1.4.0

func NewResponseSizeLimiter(config ResponseSizeLimiterConfig) elton.Handler

NewResponseSizeLimiter returns a new response size limiter

func NewStaticServe added in v0.5.0

func NewStaticServe(staticFile StaticFile, config StaticServeConfig) elton.Handler

NewStaticServe returns a new static serve middleware, suggest to set the MaxAge and SMaxAge for cache control for better performance. It will return an error if DenyDot is true and filename is start with '.'. It will return an error if DenyQueryString is true and the query string is not empty.

func NewStats added in v0.5.0

func NewStats(config StatsConfig) elton.Handler

NewStats returns a new stats middleware, it will throw a panic if the OnStats is nil.

func NewTarFS added in v1.13.1

func NewTarFS(file string) *tarFS

NewTarFS returns a new tar static fs

func NewTracker added in v0.5.0

func NewTracker(config TrackerConfig) elton.Handler

NewTracker returns a new tracker middleware, it will throw a panic if OnTrack function is nil.

func SetShortHeaders added in v1.8.0

func SetShortHeaders(names []string)

SetShortHeaders sets the short header of http header

func ZstdCompress added in v1.12.0

func ZstdCompress(buf []byte, level int) (*bytes.Buffer, error)

ZstdCompressor compress data by zstd

func ZstdDecompress added in v1.12.0

func ZstdDecompress(buf []byte) (*bytes.Buffer, error)

ZstdDecompress decompress data of zstd

Types

type BasicAuthConfig added in v0.5.0

type BasicAuthConfig struct {
	Realm    string
	Validate BasicAuthValidate
	Skipper  elton.Skipper
}

BasicAuthConfig basic auth config

type BasicAuthValidate added in v0.5.0

type BasicAuthValidate func(username string, password string, c *elton.Context) (bool, error)

BasicAuthValidate validate function

type BodyContentTypeValidate added in v0.4.4

type BodyContentTypeValidate func(c *elton.Context) bool

BodyContentTypeValidate body content type check validate function

type BodyDecoder added in v0.4.4

type BodyDecoder interface {
	// body decode function
	Decode(c *elton.Context, originalData []byte) (data []byte, err error)
	// validate function
	Validate(c *elton.Context) bool
}

BodyDecoder body decoder

func NewFormURLEncodedDecoder added in v0.4.4

func NewFormURLEncodedDecoder() BodyDecoder

NewFormURLEncodedDecoder returns a new url encoded decoder, it only support application/x-www-form-urlencoded

func NewGzipDecoder added in v0.4.4

func NewGzipDecoder() BodyDecoder

NewGzipDecoder returns a new gzip decoder

func NewJSONDecoder added in v0.4.4

func NewJSONDecoder() BodyDecoder

NewJSONDecoder returns a new json decoder, it only support application/json

type BodyParserConfig added in v0.4.4

type BodyParserConfig struct {
	// Limit the limit size of body
	Limit int
	// InitCap the initial capacity of buffer
	InitCap int
	// Decoders decode list
	Decoders            []BodyDecoder
	Skipper             elton.Skipper
	ContentTypeValidate BodyContentTypeValidate
	// OnBeforeDecode before decode event
	OnBeforeDecode func(*elton.Context) error
}

BodyParserConfig body parser config

func (*BodyParserConfig) AddDecoder added in v0.4.4

func (conf *BodyParserConfig) AddDecoder(decoder BodyDecoder)

AddDecoder to body parser config

type BrCompressor added in v1.8.0

type BrCompressor struct {
	Level     int
	MinLength int
}

BrCompressor brotli compress

func (*BrCompressor) Accept added in v1.8.0

func (b *BrCompressor) Accept(c *elton.Context, bodySize int) (acceptable bool, encoding string)

Accept check accept econding

func (*BrCompressor) Compress added in v1.8.0

func (b *BrCompressor) Compress(buf []byte, levels ...int) (*bytes.Buffer, error)

Compress brotli compress

func (*BrCompressor) Pipe added in v1.8.0

func (b *BrCompressor) Pipe(c *elton.Context) (err error)

Pipe brotli pipe

type CacheBrCompressor added in v1.8.0

type CacheBrCompressor struct {
	Level         int
	MinLength     int
	ContentRegexp *regexp.Regexp
}

func NewCacheBrCompressor added in v1.8.0

func NewCacheBrCompressor() *CacheBrCompressor

func (*CacheBrCompressor) Compress added in v1.8.0

func (br *CacheBrCompressor) Compress(buffer *bytes.Buffer) (*bytes.Buffer, CompressionType, error)

func (*CacheBrCompressor) Decompress added in v1.8.0

func (br *CacheBrCompressor) Decompress(data *bytes.Buffer) (*bytes.Buffer, error)

func (*CacheBrCompressor) GetCompression added in v1.8.0

func (br *CacheBrCompressor) GetCompression() CompressionType

func (*CacheBrCompressor) GetEncoding added in v1.8.0

func (br *CacheBrCompressor) GetEncoding() string

func (*CacheBrCompressor) IsValid added in v1.8.0

func (br *CacheBrCompressor) IsValid(contentType string, length int) bool

type CacheCompressor added in v1.8.0

type CacheCompressor interface {
	// decompress function
	Decompress(buffer *bytes.Buffer) (data *bytes.Buffer, err error)
	// get encoding of compressor
	GetEncoding() (encoding string)
	// is valid for compress
	IsValid(contentType string, length int) (valid bool)
	// compress function
	Compress(buffer *bytes.Buffer) (data *bytes.Buffer, compressionType CompressionType, err error)
	// get compression type
	GetCompression() CompressionType
}

type CacheConfig added in v1.8.0

type CacheConfig struct {
	// Skipper skipper function
	Skipper elton.Skipper
	// Store cache store
	Store CacheStore
	// HitForPassTTL hit for pass ttl
	HitForPassTTL time.Duration
	// Compressor cache compressor
	Compressor CacheCompressor
	// GetKey get the key for request
	GetKey func(*elton.Context) string
	// Marshal marshal function for cache, if BodyBuffer is nil,
	// the body will be marshaled to body buffer. The default marshal function will be json.Marshal
	Marshal func(interface{}) ([]byte, error)
	// IgnoreHeaders ignore the headers for cache
	IgnoreHeaders []string
}

type CacheGzipCompressor added in v1.8.0

type CacheGzipCompressor struct {
	Level         int
	MinLength     int
	ContentRegexp *regexp.Regexp
}

func NewCacheGzipCompressor added in v1.8.0

func NewCacheGzipCompressor() *CacheGzipCompressor

func (*CacheGzipCompressor) Compress added in v1.8.0

func (g *CacheGzipCompressor) Compress(buffer *bytes.Buffer) (*bytes.Buffer, CompressionType, error)

func (*CacheGzipCompressor) Decompress added in v1.8.0

func (g *CacheGzipCompressor) Decompress(data *bytes.Buffer) (*bytes.Buffer, error)

func (*CacheGzipCompressor) GetCompression added in v1.8.0

func (g *CacheGzipCompressor) GetCompression() CompressionType

func (*CacheGzipCompressor) GetEncoding added in v1.8.0

func (g *CacheGzipCompressor) GetEncoding() string

func (*CacheGzipCompressor) IsValid added in v1.8.0

func (g *CacheGzipCompressor) IsValid(contentType string, length int) bool

type CacheResponse added in v1.8.0

type CacheResponse struct {
	Status CacheStatus
	// 创建时间
	CreatedAt uint32
	// 状态码
	StatusCode int
	// 响应头
	Header http.Header
	// 响应数据压缩类型
	Compression CompressionType
	// 响应数据
	Body *bytes.Buffer
}

数据结构[状态(1字节), 创建时间(4字节), 状态码(2字节), 请求头长度(4字节), 请求头内容(N字节), 压缩类型(1字节) 响应内容(N字节)]

func NewCacheResponse added in v1.8.0

func NewCacheResponse(data []byte) *CacheResponse

NewCacheResponse create a new cache response

func (*CacheResponse) Bytes added in v1.8.0

func (cp *CacheResponse) Bytes(ignoreHeaders ...string) []byte

Bytes converts the cache response to bytes

func (*CacheResponse) GetBody added in v1.8.0

func (cp *CacheResponse) GetBody(acceptEncoding string, compressor CacheCompressor) (*bytes.Buffer, string, error)

GetBody returns the data match accept encoding

func (*CacheResponse) SetBody added in v1.8.0

func (cp *CacheResponse) SetBody(c *elton.Context, compressor CacheCompressor) error

SetBody sets body to http response, it will be matched accept-encoding

type CacheStatus added in v1.8.0

type CacheStatus uint8
const (
	// StatusUnknown unknown status
	StatusUnknown CacheStatus = iota
	// StatusHitForPass hit-for-pass status
	StatusHitForPass
	// StatusHit hit cache status
	StatusHit
)

type CacheStore added in v1.8.0

type CacheStore interface {
	Get(ctx context.Context, key string) ([]byte, error)
	Set(ctx context.Context, key string, data []byte, ttl time.Duration) error
}

type CacheZstdCompressor added in v1.12.0

type CacheZstdCompressor struct {
	Level         int
	MinLength     int
	ContentRegexp *regexp.Regexp
}

func NewCacheZstdCompressor added in v1.12.0

func NewCacheZstdCompressor() *CacheZstdCompressor

func (*CacheZstdCompressor) Compress added in v1.12.0

func (z *CacheZstdCompressor) Compress(buffer *bytes.Buffer) (*bytes.Buffer, CompressionType, error)

func (*CacheZstdCompressor) Decompress added in v1.12.0

func (z *CacheZstdCompressor) Decompress(data *bytes.Buffer) (*bytes.Buffer, error)

func (*CacheZstdCompressor) GetCompression added in v1.12.0

func (z *CacheZstdCompressor) GetCompression() CompressionType

func (*CacheZstdCompressor) GetEncoding added in v1.12.0

func (z *CacheZstdCompressor) GetEncoding() string

func (*CacheZstdCompressor) IsValid added in v1.12.0

func (z *CacheZstdCompressor) IsValid(contentType string, length int) bool

type CompressConfig added in v0.5.3

type CompressConfig struct {
	// Checker check the data is compressable
	Checker *regexp.Regexp
	// Compressors compressor list
	Compressors []Compressor
	// Skipper skipper function
	Skipper elton.Skipper
	// DynamicLevel return dynamic level
	DynamicLevel func(c *elton.Context, bodySize int, encoding string) int
	// OnBeforeCompress before compress event
	OnBeforeCompress func(c *elton.Context) error
}

Config compress config

func NewCompressConfig added in v0.5.3

func NewCompressConfig(compressors ...Compressor) CompressConfig

NewCompressConfig returns a compress config with multi-compressor

func (*CompressConfig) AddCompressor added in v0.5.3

func (conf *CompressConfig) AddCompressor(compressor Compressor)

AddCompressor to the compress config

type CompressionType added in v1.8.0

type CompressionType uint8
const (
	// not compress
	CompressionNone CompressionType = iota
	// gzip compress
	CompressionGzip
	// br compress
	CompressionBr
	// zstd compress
	CompressionZstd
)

type Compressor added in v0.5.3

type Compressor interface {
	// Accept accept check function
	Accept(c *elton.Context, bodySize int) (acceptable bool, encoding string)
	// Compress compress function
	Compress([]byte, ...int) (*bytes.Buffer, error)
	// Pipe pipe function
	Pipe(*elton.Context) error
}

Compressor compressor interface

type ConcurrentLimiterConfig added in v0.5.2

type ConcurrentLimiterConfig struct {
	// KeyGenerator generate custom key
	KeyGenerator KeyGenerator
	// Keys keys for generate lock id
	Keys []string
	// Lock lock function
	Lock    ConcurrentLimiterLock
	Skipper elton.Skipper
	// NotAllowEmpty if value is empty, will return error
	NotAllowEmpty bool
}

Config concurrent limiter config

type ConcurrentLimiterLock added in v0.5.2

type ConcurrentLimiterLock func(string, *elton.Context) (bool, func(), error)

ConcurrentLimiterLock lock the key

type ETagConfig added in v0.5.0

type ETagConfig struct {
	Skipper elton.Skipper
}

ETagConfig ETag config

type EncodingFsSelector added in v1.13.2

type EncodingFsSelector func(*elton.Context) (string, StaticFile)

type ErrorConfig

type ErrorConfig struct {
	Skipper      elton.Skipper
	ResponseType string
}

ErrorConfig error handler config

type FS added in v0.5.0

type FS struct {
}

FS file system

func (*FS) Exists added in v0.5.0

func (fs *FS) Exists(file string) bool

Exists check the file exists

func (*FS) Get added in v0.5.0

func (fs *FS) Get(file string) ([]byte, error)

Get get the file's content

func (*FS) NewReader added in v0.5.0

func (fs *FS) NewReader(file string) (io.Reader, error)

NewReader new a reader for file

func (*FS) Stat added in v0.5.0

func (fs *FS) Stat(file string) os.FileInfo

Stat get stat of file

type FreshConfig added in v0.5.0

type FreshConfig struct {
	Skipper elton.Skipper
}

FreshConfig fresh config

type GlobalConcurrentLimiterConfig added in v1.0.5

type GlobalConcurrentLimiterConfig struct {
	Skipper elton.Skipper
	Max     uint32
}

GlobalConcurrentLimiterConfig

type GzipCompressor added in v0.5.3

type GzipCompressor struct {
	Level     int
	MinLength int
}

GzipCompressor gzip compress

func (*GzipCompressor) Accept added in v0.5.3

func (g *GzipCompressor) Accept(c *elton.Context, bodySize int) (bool, string)

Accept accept gzip encoding

func (*GzipCompressor) Compress added in v0.5.3

func (g *GzipCompressor) Compress(buf []byte, levels ...int) (*bytes.Buffer, error)

Compress compress data by gzip

func (*GzipCompressor) Pipe added in v0.5.3

func (g *GzipCompressor) Pipe(c *elton.Context) error

Pipe compress by pipe

type HTTPHeader added in v1.8.0

type HTTPHeader []byte

http头,[type, data]

func NewHTTPHeader added in v1.8.0

func NewHTTPHeader(name string, values []string) HTTPHeader

NewHTTPHeader new a http header

func (HTTPHeader) Header added in v1.8.0

func (h HTTPHeader) Header() (string, []string)

Header converts bytes to http header(string:[]string)

type HTTPHeaders added in v1.8.0

type HTTPHeaders []byte

http头列表,使用字节0分隔[HTTPHeader 0 HTTPHeader]

func NewHTTPHeaders added in v1.8.0

func NewHTTPHeaders(header http.Header, ignoreHeaders ...string) HTTPHeaders

NewHTTPHeaders new a http headers

func (HTTPHeaders) Header added in v1.8.0

func (hs HTTPHeaders) Header() http.Header

Header convert to http.Header

type KeyGenerator added in v1.7.0

type KeyGenerator func(*elton.Context) (string, error)

type LoggerConfig added in v0.5.1

type LoggerConfig struct {
	// DefaultFill default fill for empty value
	DefaultFill string
	Format      string
	OnLog       OnLog
	Skipper     elton.Skipper
}

LoggerConfig logger config

type LoggerTag added in v0.5.1

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

LoggerTag logger tag

type OnLog added in v0.5.1

type OnLog func(string, *elton.Context)

OnLog on log function

type OnStats added in v0.5.0

type OnStats func(*StatsInfo, *elton.Context)

OnStats on stats function

type OnTrack added in v0.5.0

type OnTrack func(*TrackerInfo, *elton.Context)

OnTrack on track function

type ProxyConfig added in v0.5.0

type ProxyConfig struct {
	// Done proxy done callback
	Done         ProxyDone
	Target       *url.URL
	Rewrites     []string
	Host         string
	Transport    http.RoundTripper
	TargetPicker ProxyTargetPicker
	Skipper      elton.Skipper
}

Config proxy config

type ProxyDone added in v0.5.0

type ProxyDone func(*elton.Context)

ProxyDone http proxy done callback

type ProxyTargetPicker added in v0.5.0

type ProxyTargetPicker func(c *elton.Context) (*url.URL, ProxyDone, error)

ProxyTargetPicker target picker function

type RCLConfig added in v0.5.2

type RCLConfig struct {
	Skipper elton.Skipper
	Limiter RCLLimiter
}

Config router concurrent limiter config

type RCLLimiter added in v0.5.2

type RCLLimiter interface {
	IncConcurrency(route string) (current uint32, max uint32)
	DecConcurrency(route string)
	GetConcurrency(route string) (current uint32)
}

RCLLimiter limiter interface

type RCLLocalLimiter added in v0.5.2

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

LocalLimiter local limiter

func NewLocalLimiter added in v0.5.2

func NewLocalLimiter(data map[string]uint32) *RCLLocalLimiter

NewLocalLimiter returns a new local limiter, it's useful for limit concurrency for process.

func (*RCLLocalLimiter) DecConcurrency added in v0.5.2

func (l *RCLLocalLimiter) DecConcurrency(key string)

DecConcurrency dec 1

func (*RCLLocalLimiter) GetConcurrency added in v0.5.2

func (l *RCLLocalLimiter) GetConcurrency(key string) uint32

GetConcurrency value

func (*RCLLocalLimiter) IncConcurrency added in v0.5.2

func (l *RCLLocalLimiter) IncConcurrency(key string) (uint32, uint32)

IncConcurrency inc 1

type RenderData added in v1.6.0

type RenderData struct {
	File         string
	Text         string
	TemplateType string
	Data         interface{}
}

type RendererConfig added in v1.6.0

type RendererConfig struct {
	Skipper  elton.Skipper
	ViewPath string
	Parsers  elton.TemplateParsers
}

type ResponderConfig

type ResponderConfig struct {
	Skipper elton.Skipper
	// Marshal custom marshal function
	Marshal func(v interface{}) ([]byte, error)
	// ContentType response's content type
	ContentType string
}

Config responder config

type ResponseSizeLimiterConfig added in v1.4.0

type ResponseSizeLimiterConfig struct {
	Skipper elton.Skipper
	MaxSize int
}

type StaticFile added in v0.5.0

type StaticFile interface {
	Exists(string) bool
	Get(string) ([]byte, error)
	Stat(string) os.FileInfo
	NewReader(string) (io.Reader, error)
}

StaticFile static file

type StaticServeConfig added in v0.5.0

type StaticServeConfig struct {
	// 静态文件目录
	Path string
	// http cache control max age
	MaxAge time.Duration
	// http cache control s-maxage
	SMaxAge time.Duration
	// http cache control immutable
	Immutable bool
	// http response header
	Header map[string]string
	// 禁止query string(因为有时静态文件为CDN回源,避免生成各种重复的缓存)
	DenyQueryString bool
	// 是否禁止文件路径以.开头(因为这些文件有可能包括重要信息)
	DenyDot bool
	// 是否使用strong eTag
	EnableStrongETag bool
	// 禁止生成ETag
	DisableETag bool
	// 禁止生成 last-modifed
	DisableLastModified bool
	// 如果404,是否调用next执行后续的中间件(默认为不执行,返回404错误)
	NotFoundNext bool
	// 符合该正则则设置为no cache
	NoCacheRegexp *regexp.Regexp
	// 响应前的处理(只针对读取到buffer的文件)
	BeforeResponse func(string, []byte) ([]byte, error)
	// 目录默认文件
	IndexFile string
	Skipper   elton.Skipper
}

StaticServeConfig static serve config

type StatsConfig added in v0.5.0

type StatsConfig struct {
	OnStats OnStats
	Skipper elton.Skipper
}

StatsConfig stats config

type StatsInfo added in v0.5.0

type StatsInfo struct {
	// ctx id
	CID string `json:"cid,omitempty"`
	// real ip
	IP string `json:"ip,omitempty"`
	// http request method
	Method string `json:"method,omitempty"`
	// route of elton
	Route string `json:"route,omitempty"`
	// http request uri
	URI string `json:"uri,omitempty"`
	// http status code
	Status int `json:"status,omitempty"`
	// latency of processing
	Latency time.Duration `json:"latency,omitempty"`
	Type    int           `json:"type,omitempty"`
	// bytes of request body
	RequestBodySize int `json:"requestBodySize"`
	// bytes of response body
	Size int `json:"size,omitempty"`
	// request connecting count of elton
	Connecting uint32 `json:"connecting,omitempty"`
}

StatsInfo stats's info

type TrackerConfig added in v0.5.0

type TrackerConfig struct {
	// On Track function
	OnTrack OnTrack
	// mask regexp
	Mask *regexp.Regexp
	// max length for filed
	MaxLength int
	Skipper   elton.Skipper
}

TrackerConfig tracker config

type TrackerInfo added in v0.5.0

type TrackerInfo struct {
	CID     string                 `json:"cid,omitempty"`
	Query   map[string]string      `json:"query,omitempty"`
	Params  map[string]string      `json:"params,omitempty"`
	Form    map[string]interface{} `json:"form,omitempty"`
	Latency time.Duration          `json:"latency,omitempty"`
	Result  int                    `json:"result,omitempty"`
	Err     error                  `json:"err,omitempty"`
}

TrackerInfo tracker info

type ZstdCompressor added in v1.12.0

type ZstdCompressor struct {
	Level     int
	MinLength int
}

ZstdCompressor zstd compress

func (*ZstdCompressor) Accept added in v1.12.0

func (z *ZstdCompressor) Accept(c *elton.Context, bodySize int) (bool, string)

Accept accept zstd encoding

func (*ZstdCompressor) Compress added in v1.12.0

func (z *ZstdCompressor) Compress(buf []byte, levels ...int) (*bytes.Buffer, error)

Compress compress data by zstd

func (*ZstdCompressor) Pipe added in v1.12.0

func (z *ZstdCompressor) Pipe(c *elton.Context) error

Pipe compress by pipe

Jump to

Keyboard shortcuts

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