Documentation
¶
Index ¶
- Constants
- func DigestAuthParams(auth string) map[string]string
- type AccessLogCtx
- type AccessLogJSONWriter
- type AccessLogMultiWriter
- type AccessLogTextWriter
- type AccessLogWriter
- type AccessLogger
- type BasicAuth
- type DigestAuth
- type HTTPDumper
- type HTTPGziper
- func (z *HTTPGziper) Disable(disabled bool)
- func (z *HTTPGziper) Handle(c *xin.Context)
- func (z *HTTPGziper) Handler() xin.HandlerFunc
- func (z *HTTPGziper) IgnorePathPrefix(ps ...string)
- func (z *HTTPGziper) IgnorePathRegexp(ps ...string)
- func (z *HTTPGziper) SetHTTPVersion(major, minor int)
- func (z *HTTPGziper) SetMimeTypes(mts ...string)
- func (z *HTTPGziper) SetProxied(ps ...string)
- func (z *HTTPGziper) Vary(vary bool)
- type Localizer
- type OriginAccessController
- type ProxiedFlag
- type RequestLimiter
- type ResponseHeader
- type TokenProtector
- type UserProvider
Examples ¶
Constants ¶
const ( GzipBestCompression = gzip.BestCompression GzipBestSpeed = gzip.BestSpeed GzipDefaultCompression = gzip.DefaultCompression GzipNoCompression = gzip.NoCompression )
These constants are copied from the gzip package.
const ( // LocaleParamName default parameter key name LocaleParamName = "__locale" // LocaleHeaderName default http header name LocaleHeaderName = "X-Accept-Language" // LocaleCookieName default cookie name LocaleCookieName = "WW_LOCALE" )
const ( TokenAttrKey = "WW_TOKEN" TokenParamName = "_token_" TokenHeaderName = "X-WW-TOKEN" //nolint: gosec TokenCookieName = "WW_TOKEN" )
const AccessLogJSONFormat = `` /* 177-byte string literal not displayed */
AccessLogJSONFormat default json log format
const AccessLogTextFormat = "text:%t\t%S\t%T\t%B\t%c\t%r\t%m\t%h\t%u\t%h{User-Agent}%n"
AccessLogTextFormat default text log format TIME STATUS LATENCY SIZE CLIENT_IP REMOTE_ADDR METHOD HOST URL HEADER(User-Agent)
const AccessLogTimeFormat = "2006-01-02T15:04:05.000"
AccessLogTimeFormat default log time format
const AuthUserKey = "WW_USER"
AuthUserKey is the key for user credential authenticated saved in context
Variables ¶
This section is empty.
Functions ¶
func DigestAuthParams ¶
DigestAuthParams parses Authorization header from the http.Request. Returns a map of auth parameters or nil if the header is not a valid parsable Digest auth header.
Types ¶
type AccessLogCtx ¶ added in v1.0.12
type AccessLogJSONWriter ¶ added in v1.0.12
type AccessLogJSONWriter struct {
// contains filtered or unexported fields
}
AccessLogJSONWriter format(json-style) and write access log
func NewAccessLogJSONWriter ¶ added in v1.0.12
func NewAccessLogJSONWriter(writer io.Writer, format string) *AccessLogJSONWriter
NewAccessLogJSONWriter create json style writer for AccessLogger
func (*AccessLogJSONWriter) SetFormat ¶ added in v1.0.12
func (aljw *AccessLogJSONWriter) SetFormat(format string)
SetFormat set the access alw format
func (*AccessLogJSONWriter) SetOutput ¶ added in v1.0.12
func (aljw *AccessLogJSONWriter) SetOutput(w io.Writer)
SetOutput set the access log writer
func (*AccessLogJSONWriter) Write ¶ added in v1.0.12
func (aljw *AccessLogJSONWriter) Write(alc *AccessLogCtx)
Write write the access log
type AccessLogMultiWriter ¶ added in v1.0.12
type AccessLogMultiWriter struct {
Writers []AccessLogWriter
}
AccessLogMultiWriter write log to multiple writers.
func NewAccessLogMultiWriter ¶ added in v1.0.12
func NewAccessLogMultiWriter(ws ...AccessLogWriter) *AccessLogMultiWriter
NewAccessLogMultiWriter create a multi writer
func (*AccessLogMultiWriter) Write ¶ added in v1.0.12
func (mw *AccessLogMultiWriter) Write(alc *AccessLogCtx)
Write write the access log to multiple writers.
type AccessLogTextWriter ¶ added in v1.0.12
type AccessLogTextWriter struct {
// contains filtered or unexported fields
}
AccessLogTextWriter format(text) and write access log
func NewAccessLogTextWriter ¶ added in v1.0.12
func NewAccessLogTextWriter(writer io.Writer, format string) *AccessLogTextWriter
NewAccessLogTextWriter create text style writer for AccessLogger
func (*AccessLogTextWriter) SetFormat ¶ added in v1.0.12
func (altw *AccessLogTextWriter) SetFormat(format string)
SetFormat set the access alw format
func (*AccessLogTextWriter) SetOutput ¶ added in v1.0.12
func (altw *AccessLogTextWriter) SetOutput(w io.Writer)
SetOutput set the access log writer
func (*AccessLogTextWriter) Write ¶ added in v1.0.12
func (altw *AccessLogTextWriter) Write(alc *AccessLogCtx)
Write write the access log
type AccessLogWriter ¶ added in v1.0.12
type AccessLogWriter interface {
Write(*AccessLogCtx)
}
AccessLogWriter access log writer for XIN
%t{format} - Request start time, if {format} is omitted, '2006-01-02T15:04:05.000' is used.
%c - Client IP ([X-Forwarded-For, X-Real-Ip] or RemoteIP())
%r - Remote IP:Port (%a)
%u - Request URL
%p - Request protocol
%m - Request method (GET, POST, etc.)
%q - Query string (prepended with a '?' if it exists)
%h - Request host
%h{name} - Request header
%A - Server listen address
%T - Time taken to process the request, in milliseconds
%S - HTTP status code of the response
%B - Response body length (%L)
%H - Local hostname
%H{name} - Response header
%n: EOL(Windows: "\r\n", Other: "\n")
func NewAccessLogWriter ¶ added in v1.0.12
func NewAccessLogWriter(writer io.Writer, format string) AccessLogWriter
NewAccessLogWriter create a text or json access log writer text:... -> AccessLogTextWriter json:... -> AccessLogJSONWriter
type AccessLogger ¶
type AccessLogger struct {
// contains filtered or unexported fields
}
AccessLogger access logger middleware for XIN
Example ¶
router := xin.New()
router.Use(NewAccessLogger(NewAccessLogWriter(os.Stdout, AccessLogTextFormat)).Handler())
router.Any("/example", func(c *xin.Context) {
c.String(http.StatusOK, c.Request.URL.String())
})
server := &http.Server{
Addr: "127.0.0.1:8888",
Handler: router,
}
go func() {
server.ListenAndServe()
}()
time.Sleep(time.Millisecond * 100)
req, _ := http.NewRequest("GET", "http://127.0.0.1:8888/example?a=100", nil)
client := &http.Client{Timeout: time.Second * 1}
client.Do(req)
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
server.Shutdown(ctx)
func DefaultAccessLogger ¶
func DefaultAccessLogger(xin *xin.Engine) *AccessLogger
DefaultAccessLogger create a access logger middleware for XIN Equals: NewAccessLogger(NewAccessLogTextWriter(xin.Logger.GetOutputer("XAL", log.LevelTrace), AccessLogTextFormat))
func NewAccessLogger ¶
func NewAccessLogger(writer AccessLogWriter) *AccessLogger
NewAccessLogger create a log middleware for xin access logger
func (*AccessLogger) Disable ¶
func (al *AccessLogger) Disable(disabled bool)
Disable disable the logger or not
func (*AccessLogger) Handle ¶ added in v1.0.10
func (al *AccessLogger) Handle(c *xin.Context)
Handle process xin request
func (*AccessLogger) Handler ¶
func (al *AccessLogger) Handler() xin.HandlerFunc
Handler returns the HandlerFunc
func (*AccessLogger) SetWriter ¶ added in v1.0.12
func (al *AccessLogger) SetWriter(alw AccessLogWriter)
SetWriter set the access logger writer
type BasicAuth ¶
type BasicAuth struct {
UserProvider UserProvider
AuthUserKey string
Realm string
}
BasicAuth basic http authenticator
func NewBasicAuth ¶
func NewBasicAuth(up UserProvider) *BasicAuth
func (*BasicAuth) Handler ¶
func (ba *BasicAuth) Handler() xin.HandlerFunc
Handler returns the xin.HandlerFunc
type DigestAuth ¶
type DigestAuth struct {
UserProvider UserProvider
AuthUserKey string
Realm string
Opaque string
NonceExpires time.Duration
}
DigestAuth digest http authenticator
func NewDigestAuth ¶
func NewDigestAuth(up UserProvider) *DigestAuth
func (*DigestAuth) Handle ¶ added in v1.0.10
func (da *DigestAuth) Handle(c *xin.Context)
Handle process xin request
func (*DigestAuth) Handler ¶
func (da *DigestAuth) Handler() xin.HandlerFunc
Handler returns the xin.HandlerFunc
type HTTPDumper ¶
type HTTPDumper struct {
// contains filtered or unexported fields
}
HTTPDumper dump http request and response
Example ¶
router := xin.New()
router.Use(NewHTTPDumper(os.Stdout).Handler())
router.Any("/example", func(c *xin.Context) {
c.String(http.StatusOK, c.Request.URL.String())
})
server := &http.Server{
Addr: "127.0.0.1:8888",
Handler: router,
}
go func() {
server.ListenAndServe()
}()
time.Sleep(time.Millisecond * 100)
req, _ := http.NewRequest("GET", "http://127.0.0.1:8888/example?a=100", nil)
client := &http.Client{Timeout: time.Second * 1}
client.Do(req)
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
server.Shutdown(ctx)
func DefaultHTTPDumper ¶
func DefaultHTTPDumper(xin *xin.Engine) *HTTPDumper
DefaultHTTPDumper create a middleware for xin http dumper Equals: NewHTTPDumper(xin.Logger.Outputer("XHD", log.LevelTrace))
func NewHTTPDumper ¶
func NewHTTPDumper(outputer io.Writer) *HTTPDumper
NewHTTPDumper create a middleware for xin http dumper
func (*HTTPDumper) Disable ¶
func (hd *HTTPDumper) Disable(disabled bool)
Disable disable the dumper or not
func (*HTTPDumper) Handle ¶ added in v1.0.10
func (hd *HTTPDumper) Handle(c *xin.Context)
Handle process xin request
func (*HTTPDumper) Handler ¶
func (hd *HTTPDumper) Handler() xin.HandlerFunc
Handler returns the xin.HandlerFunc
func (*HTTPDumper) SetMaxlength ¶ added in v1.0.12
func (hd *HTTPDumper) SetMaxlength(maxlength int64)
SetMaxlength set the maxlength of request/resonse that the dumper should dump
func (*HTTPDumper) SetOutput ¶
func (hd *HTTPDumper) SetOutput(w io.Writer)
SetOutput set the access log output writer
type HTTPGziper ¶
type HTTPGziper struct {
// contains filtered or unexported fields
}
HTTPGziper Compresses responses using the “gzip” method
Example ¶
router := xin.Default()
router.Use(DefaultHTTPGziper().Handler())
router.GET("/", func(c *xin.Context) {
c.String(200, strings.Repeat("This is a Test!\n", 1000))
})
server := &http.Server{
Addr: "127.0.0.1:8888",
Handler: router,
}
go func() {
server.ListenAndServe()
}()
time.Sleep(time.Millisecond * 100)
req, _ := http.NewRequest("GET", "http://127.0.0.1:8888/", nil)
client := &http.Client{Timeout: time.Second * 1}
client.Do(req)
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
server.Shutdown(ctx)
func DefaultHTTPGziper ¶
func DefaultHTTPGziper() *HTTPGziper
DefaultHTTPGziper create a default zipper = NewHTTPGziper(DefaultCompression, 1024)
func NewHTTPGziper ¶
func NewHTTPGziper(compressLevel, minLength int) *HTTPGziper
NewHTTPGziper create a zipper proxied: ProxiedAny vary: true minLength: 1024
func (*HTTPGziper) Disable ¶
func (z *HTTPGziper) Disable(disabled bool)
Disable disable the gzip compress or not
func (*HTTPGziper) Handle ¶ added in v1.0.10
func (z *HTTPGziper) Handle(c *xin.Context)
Handle process xin request
func (*HTTPGziper) Handler ¶
func (z *HTTPGziper) Handler() xin.HandlerFunc
Handler returns the xin.HandlerFunc
func (*HTTPGziper) IgnorePathPrefix ¶
func (z *HTTPGziper) IgnorePathPrefix(ps ...string)
IgnorePathPrefix ignore URL path prefix
func (*HTTPGziper) IgnorePathRegexp ¶
func (z *HTTPGziper) IgnorePathRegexp(ps ...string)
IgnorePathRegexp ignore URL path regexp
func (*HTTPGziper) SetHTTPVersion ¶
func (z *HTTPGziper) SetHTTPVersion(major, minor int)
SetHTTPVersion Sets the minimum HTTP Proto version of a request required to compress a response.
func (*HTTPGziper) SetMimeTypes ¶
func (z *HTTPGziper) SetMimeTypes(mts ...string)
SetMimeTypes Enables gzipping of responses for the specified MIME types. The special value "*" matches any MIME type. Default:
text/html text/plain text/xml text/css text/javascript text/json text/comma-separated-values text/tab-separated-values application/xml application/xhtml+xml application/rss+xml application/atom_xml application/json application/javascript application/x-javascript
func (*HTTPGziper) SetProxied ¶
func (z *HTTPGziper) SetProxied(ps ...string)
SetProxied Enables or disables gzipping of responses for proxied requests depending on the request and response. The fact that the request is proxied is determined by the presence of the “Via” request header field. The directive accepts multiple parameters: off
disables compression for all proxied requests, ignoring other parameters;
any (Default)
enables compression for all proxied requests.
auth
enables compression if a request header includes the “Authorization” field;
expired
enables compression if a response header includes the “Expires” field with a value that disables caching;
no-cache
enables compression if a response header includes the “Cache-Control” field with the “no-cache” parameter;
no-store
enables compression if a response header includes the “Cache-Control” field with the “no-store” parameter;
private
enables compression if a response header includes the “Cache-Control” field with the “private” parameter;
no_last_modified
enables compression if a response header does not include the “Last-Modified” field;
no_etag
enables compression if a response header does not include the “ETag” field;
func (*HTTPGziper) Vary ¶
func (z *HTTPGziper) Vary(vary bool)
Vary Enables or disables inserting the “Vary: Accept-Encoding” response header field. Default: true
type Localizer ¶
type Localizer struct {
Locales []string
LocaleParamName string
LocaleHeaderName string
LocaleCookieName string
FromAcceptLanguage bool
}
Localizer localizer middleware
Example ¶
router := xin.Default()
router.Use(NewLocalizer("en", "ja", "zh").Handler())
router.GET("/", func(c *xin.Context) {
c.String(200, c.Locale)
})
server := &http.Server{
Addr: "127.0.0.1:8888",
Handler: router,
}
go func() {
server.ListenAndServe()
}()
time.Sleep(time.Millisecond * 100)
req, _ := http.NewRequest("GET", "http://127.0.0.1:8888/", nil)
req.Header.Add("Accept-Languages", "ja;zh")
client := &http.Client{Timeout: time.Second * 1}
res, _ := client.Do(req)
raw, _ := io.ReadAll(res.Body)
fmt.Println(string(raw))
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
server.Shutdown(ctx)
func NewLocalizer ¶
NewLocalizer create a default Localizer
func (*Localizer) Handler ¶
func (ll *Localizer) Handler() xin.HandlerFunc
Handler returns the xin.HandlerFunc
type OriginAccessController ¶ added in v1.0.12
OriginAccessController Access-Control-Allow-Origin response header middleware see https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Origin if Origins contains the request header 'origin', set the Access-Control-Allow-Origin response header. if the request method is OPTIONS, also set the status code to 200.
func NewOriginAccessController ¶ added in v1.0.12
func NewOriginAccessController(origins ...string) *OriginAccessController
NewOriginAccessController create a default OriginAccessController
func (*OriginAccessController) Handle ¶ added in v1.0.12
func (ll *OriginAccessController) Handle(c *xin.Context)
Handle process xin request
func (*OriginAccessController) Handler ¶ added in v1.0.12
func (ll *OriginAccessController) Handler() xin.HandlerFunc
Handler returns the xin.HandlerFunc
func (*OriginAccessController) SetOrigins ¶ added in v1.0.12
func (ll *OriginAccessController) SetOrigins(origins ...string)
SetOrigins set allowed origins
type ProxiedFlag ¶
type ProxiedFlag int
ProxiedFlag Proxied flag
const ( ProxiedAny ProxiedFlag = 1 << iota ProxiedAuth ProxiedExpired ProxiedNoCache ProxiedNoStore ProxiedPrivate ProxiedNoLastModified ProxiedNoETag ProxiedOff = 0 )
Proxied option flags
type RequestLimiter ¶
type RequestLimiter struct {
MaxBodySize int64
DrainBody bool // drain request body if we are under apache, otherwise the apache will return 502 Bad Gateway
BodyTooLarge func(c *xin.Context, maxBodySize int64)
}
RequestLimiter http request limit middleware
func NewRequestLimiter ¶
func NewRequestLimiter(maxBodySize int64, bodyTooLarge ...func(c *xin.Context, maxBodySize int64)) *RequestLimiter
NewRequestLimiter create a default RequestLimiter middleware
func (*RequestLimiter) Handle ¶ added in v1.0.10
func (rl *RequestLimiter) Handle(c *xin.Context)
Handle process xin request
func (*RequestLimiter) Handler ¶
func (rl *RequestLimiter) Handler() xin.HandlerFunc
Handler returns the xin.HandlerFunc
type ResponseHeader ¶
ResponseHeader response header middleware
func NewResponseHeader ¶
func NewResponseHeader(header map[string]string) *ResponseHeader
NewResponseHeader create a default ResponseHeader
func (*ResponseHeader) Handle ¶ added in v1.0.10
func (rh *ResponseHeader) Handle(c *xin.Context)
Handle process xin request
func (*ResponseHeader) Handler ¶
func (rh *ResponseHeader) Handler() xin.HandlerFunc
Handler returns the xin.HandlerFunc
type TokenProtector ¶
type TokenProtector struct {
Cryptor cpt.Cryptor
Expires time.Duration
AttrKey string
ParamName string
HeaderName string
CookieName string
CookieMaxAge time.Duration
CookieDomain string
CookiePath string
CookieSecure bool
CookieHttpOnly bool
// contains filtered or unexported fields
}
TokenProtector token protector for CSRF
func NewTokenProtector ¶
func NewTokenProtector(secret string) *TokenProtector
NewTokenProtector create a default TokenProtector default methods: DELETE, PATCH, POST, PUT
func (*TokenProtector) Handle ¶ added in v1.0.10
func (tp *TokenProtector) Handle(c *xin.Context)
Handle process xin request
func (*TokenProtector) Handler ¶
func (tp *TokenProtector) Handler() xin.HandlerFunc
Handler returns the xin.HandlerFunc
func (*TokenProtector) RefreshToken ¶
func (tp *TokenProtector) RefreshToken(c *xin.Context) string
func (*TokenProtector) SetMethods ¶
func (tp *TokenProtector) SetMethods(ms ...string)
SetMethods Set the http methods to protect default methods: DELETE, PATCH, POST, PUT
func (*TokenProtector) SetSecret ¶ added in v1.0.12
func (tp *TokenProtector) SetSecret(secret string)
SetSecret Set the Cryptor secret