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
- Variables
- func AcceptEncoding(c *elton.Context, encoding string) (bool, string)
- func BrotliCompress(buf []byte, level int) (*bytes.Buffer, error)
- func BrotliDecompress(buf []byte) (*bytes.Buffer, error)
- func DefaultJSONAndFormContentTypeValidate(c *elton.Context) bool
- func DefaultJSONContentTypeValidate(c *elton.Context) bool
- func GetCacheMaxAge(header http.Header) int
- func GzipCompress(buf []byte, level int) (*bytes.Buffer, error)
- func GzipDecompress(buf []byte) (*bytes.Buffer, error)
- func IsPassCacheMethod(reqMethod string) bool
- func MaxBytesReader(r io.ReadCloser, n int64) *maxBytesReader
- func NewBasicAuth(config BasicAuthConfig) elton.Handler
- func NewBodyParser(config BodyParserConfig) elton.Handler
- func NewCache(config CacheConfig) elton.Handler
- func NewCompress(config CompressConfig) elton.Handler
- func NewConcurrentLimiter(config ConcurrentLimiterConfig) elton.Handler
- func NewDefaultBasicAuth(account, password string) elton.Handler
- func NewDefaultBodyParser() elton.Handler
- func NewDefaultCache(store CacheStore) elton.Handler
- func NewDefaultCompress() elton.Handler
- func NewDefaultETag() elton.Handler
- func NewDefaultError() elton.Handler
- func NewDefaultFresh() elton.Handler
- func NewDefaultResponder() elton.Handler
- func NewDefaultStaticServe(config StaticServeConfig) elton.Handler
- func NewETag(config ETagConfig) elton.Handler
- func NewEmbedStaticFS(fs embed.FS, prefix string) *embedStaticFS
- func NewEncodingStaticServe(config StaticServeConfig, selector EncodingFsSelector) elton.Handler
- func NewError(config ErrorConfig) elton.Handler
- func NewFresh(config FreshConfig) elton.Handler
- func NewGlobalConcurrentLimiter(config GlobalConcurrentLimiterConfig) elton.Handler
- func NewLogger(config LoggerConfig) elton.Handler
- func NewLruStore(size int) *lruStore
- func NewPeekLruStore(size int) *lruStore
- func NewPrefixURL(prefix ...string) elton.PreHandler
- func NewProxy(config ProxyConfig) elton.Handler
- func NewRCL(config RCLConfig) elton.Handler
- func NewRecover() elton.Handler
- func NewRenderer(config RendererConfig) elton.Handler
- func NewResponder(config ResponderConfig) elton.Handler
- func NewResponseSizeLimiter(config ResponseSizeLimiterConfig) elton.Handler
- func NewStaticServe(staticFile StaticFile, config StaticServeConfig) elton.Handler
- func NewStats(config StatsConfig) elton.Handler
- func NewTarFS(file string) *tarFS
- func NewTracker(config TrackerConfig) elton.Handler
- func SetShortHeaders(names []string)
- func ZstdCompress(buf []byte, level int) (*bytes.Buffer, error)
- func ZstdDecompress(buf []byte) (*bytes.Buffer, error)
- type BasicAuthConfig
- type BasicAuthValidate
- type BodyContentTypeValidate
- type BodyDecoder
- type BodyParserConfig
- type BrCompressor
- type CacheBrCompressor
- func (br *CacheBrCompressor) Compress(buffer *bytes.Buffer) (*bytes.Buffer, CompressionType, error)
- func (br *CacheBrCompressor) Decompress(data *bytes.Buffer) (*bytes.Buffer, error)
- func (br *CacheBrCompressor) GetCompression() CompressionType
- func (br *CacheBrCompressor) GetEncoding() string
- func (br *CacheBrCompressor) IsValid(contentType string, length int) bool
- type CacheCompressor
- type CacheConfig
- type CacheGzipCompressor
- func (g *CacheGzipCompressor) Compress(buffer *bytes.Buffer) (*bytes.Buffer, CompressionType, error)
- func (g *CacheGzipCompressor) Decompress(data *bytes.Buffer) (*bytes.Buffer, error)
- func (g *CacheGzipCompressor) GetCompression() CompressionType
- func (g *CacheGzipCompressor) GetEncoding() string
- func (g *CacheGzipCompressor) IsValid(contentType string, length int) bool
- type CacheResponse
- type CacheStatus
- type CacheStore
- type CacheZstdCompressor
- func (z *CacheZstdCompressor) Compress(buffer *bytes.Buffer) (*bytes.Buffer, CompressionType, error)
- func (z *CacheZstdCompressor) Decompress(data *bytes.Buffer) (*bytes.Buffer, error)
- func (z *CacheZstdCompressor) GetCompression() CompressionType
- func (z *CacheZstdCompressor) GetEncoding() string
- func (z *CacheZstdCompressor) IsValid(contentType string, length int) bool
- type CompressConfig
- type CompressionType
- type Compressor
- type ConcurrentLimiterConfig
- type ConcurrentLimiterLock
- type ETagConfig
- type EncodingFsSelector
- type ErrorConfig
- type FS
- type FreshConfig
- type GlobalConcurrentLimiterConfig
- type GzipCompressor
- type HTTPHeader
- type HTTPHeaders
- type KeyGenerator
- type LoggerConfig
- type LoggerTag
- type OnLog
- type OnStats
- type OnTrack
- type ProxyConfig
- type ProxyDone
- type ProxyTargetPicker
- type RCLConfig
- type RCLLimiter
- type RCLLocalLimiter
- type RenderData
- type RendererConfig
- type ResponderConfig
- type ResponseSizeLimiterConfig
- type StaticFile
- type StaticServeConfig
- type StatsConfig
- type StatsInfo
- type TrackerConfig
- type TrackerInfo
- type ZstdCompressor
Constants ¶
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` )
const ( // ErrProxyCategory proxy error category ErrProxyCategory = "elton-proxy" ProxyTargetKey = "proxyTarget" )
const ( // HandleSuccess handle success HandleSuccess = iota // HandleFail handle fail HandleFail )
const (
// DefaultCompressMinLength min compress length(1KB)
DefaultCompressMinLength = 1024
)
const (
// ErrBasicAuthCategory basic auth error category
ErrBasicAuthCategory = "elton-basic-auth"
)
const (
// ErrBodyParserCategory body parser error category
ErrBodyParserCategory = "elton-body-parser"
)
const (
// ErrConcurrentLimiterCategory concurrent limiter error category
ErrConcurrentLimiterCategory = "elton-concurrent-limiter"
)
const (
// ErrErrorCategory error category of error handler
ErrErrorCategory = "elton-error"
)
const (
// ErrRCLCategory router concurrent limiter error category
ErrRCLCategory = "elton-router-concurrent-limiter"
)
const (
// ErrRecoverCategory recover error category
ErrRecoverCategory = "elton-recover"
)
const ErrRendererCategory = "elton-renderer"
const (
// ErrResponderCategory responder error category
ErrResponderCategory = "elton-responder"
)
const (
ErrResponseSizeLimiterCategory = "elton-response-size-limiter"
)
const (
// ErrStaticServeCategory static serve error category
ErrStaticServeCategory = "elton-static-serve"
)
const HeaderAge = "Age"
const HeaderXCache = "X-Cache"
const IgnoreCompression = -128
const MaxShortHeader = uint8(128)
const NoneMatchHeader = math.MaxUint8
Variables ¶
var ( errors.New("unAuthorized"), http.StatusUnauthorized) // ErrBasicAuthRequireValidateFunction require validate function ErrBasicAuthRequireValidateFunction = errors.New("require validate function") )ErrBasicAuthUnauthorized = getBasicAuthError(
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") )
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") )
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, } )
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) )
var ( // DefaultCompressRegexp compress text, javascript, json and wasm DefaultCompressRegexp = regexp.MustCompile("text|javascript|json|wasm|font") )
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",
}
var ( ErrInvalidJSON = &hes.Error{ Category: ErrBodyParserCategory, Message: "invalid json format", StatusCode: http.StatusBadRequest, } )
var ( // ErrInvalidResponse invalid response(body an status is nil) ErrInvalidResponse = &hes.Error{ Exception: true, StatusCode: 500, Message: "invalid response", Category: ErrResponderCategory, } )
var (
ErrRCLRequireLimiter = errors.New("require limiter")
)
var ErrResponseTooLarge = &hes.Error{ Category: ErrResponseSizeLimiterCategory, Message: "body of response is too large", StatusCode: http.StatusInternalServerError, }
var (
ErrStatsNoFunction = errors.New("require on stats function")
)
var (
ErrTrackerNoFunction = errors.New("require on track function")
)
Functions ¶
func AcceptEncoding ¶ added in v0.5.3
AcceptEncoding check request accept encoding
func BrotliCompress ¶ added in v1.8.0
BrotliCompress compress data by brotli
func BrotliDecompress ¶ added in v1.8.0
BrotliDecompress decompress data of brotli
func DefaultJSONAndFormContentTypeValidate ¶ added in v0.4.4
DefaultJSONAndFormContentTypeValidate for validate json content type and form url encoded content type
func DefaultJSONContentTypeValidate ¶ added in v0.4.4
DefaultJSONContentTypeValidate for validate json content type
func GetCacheMaxAge ¶ added in v1.8.0
GetCacheMaxAge returns the age of cache, get value from cache-control(s-maxage or max-age)
func GzipCompress ¶ added in v1.8.0
GzipCompress compress data by gzip
func GzipDecompress ¶ added in v1.8.0
GzipDecompress decompress data of gzip
func IsPassCacheMethod ¶ added in v1.8.0
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
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
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
NewDefaultCompress return a new compress middleware, it include gzip compress
func NewDefaultETag ¶ added in v0.5.0
NewDefaultETag returns a default ETag middleware, it will use sha1 to generate etag.
func NewDefaultError ¶
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
NewDefaultFresh returns a default fresh middleware, it will return 304 modified if the data is not modified.
func NewDefaultResponder ¶
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
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
NewRCL returns a router concurrent limiter middleware. It will throw panic if Limiter is nil.
func NewRecover ¶ added in v0.5.0
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
ZstdCompressor compress data by 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
BasicAuthValidate validate function
type BodyContentTypeValidate ¶ added in v0.4.4
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
BrCompressor brotli compress
type CacheBrCompressor ¶ added in v1.8.0
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 (*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
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
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 (*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
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 CacheZstdCompressor ¶ added in v1.12.0
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 (*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
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
ConcurrentLimiterLock lock the key
type ETagConfig ¶ added in v0.5.0
ETagConfig ETag config
type EncodingFsSelector ¶ added in v1.13.2
type EncodingFsSelector func(*elton.Context) (string, StaticFile)
type ErrorConfig ¶
ErrorConfig error handler config
type FS ¶ added in v0.5.0
type FS struct { }
FS file system
type FreshConfig ¶ added in v0.5.0
FreshConfig fresh config
type GlobalConcurrentLimiterConfig ¶ added in v1.0.5
GlobalConcurrentLimiterConfig
type GzipCompressor ¶ added in v0.5.3
GzipCompressor gzip compress
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 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 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 ProxyTargetPicker ¶ added in v0.5.0
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 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 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
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
Source Files ¶
- basic_auth.go
- body_parser.go
- brotli.go
- cache.go
- cache_compressor.go
- compress.go
- concurrent_limiter.go
- error.go
- etag.go
- fresh.go
- gzip.go
- http_header.go
- logger.go
- lru_store.go
- prefix_url.go
- proxy.go
- recover.go
- renderer.go
- responder.go
- response_size_limiter.go
- router_concurrent_limiter.go
- static_embed.go
- static_serve.go
- stats.go
- tracker.go
- zstd.go