Documentation
¶
Index ¶
- Constants
- func DigestAuthParams(auth string) map[string]string
- func MaxBytesReader(c *xin.Context, r io.ReadCloser, n int64) io.ReadCloser
- 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 MaxBytesError
- type ProxiedFlag
- type RequestLimiter
- type ResponseHeader
- type TokenProtector
- type UserProvider
Examples ¶
Constants ¶
const ( BestCompression = gzip.BestCompression BestSpeed = gzip.BestSpeed DefaultCompression = gzip.DefaultCompression NoCompression = 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 = `` /* 147-byte string literal not displayed */
AccessLogJSONFormat default log format
const AccessLogTextFormat = "text:%t\t%S\t%T\t%L\t%c\t%r\t%A\t%m\t%h\t%u%n"
AccessLogTextFormat default log format TIME STATUS LATENCY LENGTH CLIENT_IP REMOTE_ADDR LISTEN METHOD HOST URL
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.
func MaxBytesReader ¶
func MaxBytesReader(c *xin.Context, r io.ReadCloser, n int64) io.ReadCloser
Types ¶
type AccessLogger ¶
type AccessLogger struct {
// contains filtered or unexported fields
}
AccessLogger access loger for XIN
Example ¶
router := xin.New()
router.Use(NewAccessLogger(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 log middleware for xin access logger Equals: NewAccessLogger(xin.Logger.Outputer("XINA", log.LevelTrace), xmw.AccessLogTextFormat)
func NewAccessLogger ¶
func NewAccessLogger(outputer io.Writer, format string) *AccessLogger
NewAccessLogger create a log middleware for xin access logger Access Log Format: text:... json:...
%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
%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
%L - Response body length
%H{name} - Response header
%n: EOL(Windows: "\r\n", Other: "\n")
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) SetFormat ¶
func (al *AccessLogger) SetFormat(format string)
SetFormat set the access al format
func (*AccessLogger) SetOutput ¶
func (al *AccessLogger) SetOutput(w io.Writer)
SetOutput set the access al output 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("XIND", 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) 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 MaxBytesError ¶
type MaxBytesError struct {
Limit int64
}
MaxBytesError is returned by MaxBytesReader when its read limit is exceeded.
func (*MaxBytesError) Error ¶
func (e *MaxBytesError) Error() string
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
}
RequestLimiter http request limit middleware
func NewRequestLimiter ¶
func NewRequestLimiter(maxBodySize int64) *RequestLimiter
NewRequestLimiter create a default RequestLimiter
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