xmw

package
v1.0.9 Latest Latest
Warning

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

Go to latest
Published: Jul 19, 2023 License: MIT Imports: 23 Imported by: 0

Documentation

Overview

Example
router := xin.New()
router.Use(NewAccessLogger(os.Stdout, DefaultTextLogFormat).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)

Index

Examples

Constants

View Source
const (
	BestCompression    = gzip.BestCompression
	BestSpeed          = gzip.BestSpeed
	DefaultCompression = gzip.DefaultCompression
	NoCompression      = gzip.NoCompression
)

These constants are copied from the gzip package.

View Source
const (
	// LocaleParamName default parameter key name
	LocaleParamName = "__locale"

	// LocaleHeaderName default http header name
	LocaleHeaderName = "X-Accept-Language"

	// LocaleCookieName default cookie name
	LocaleCookieName = "WW_LOCALE"
)
View Source
const (
	TokenAttrKey    = "WW_TOKEN"
	TokenParamName  = "_token_"
	TokenHeaderName = "X-WW-TOKEN" //nolint: gosec
	TokenCookieName = "WW_TOKEN"
)
View Source
const AuthUserKey = "WW_USER"

AuthUserKey is the key for user credential authenticated saved in context

View Source
const DefaultJSONLogFormat = `` /* 147-byte string literal not displayed */

DefaultJSONLogFormat default log format

View Source
const DefaultLogTimeFormat = "2006-01-02T15:04:05.000"

DefaultLogTimeFormat default log time format

View Source
const DefaultTextLogFormat = "text:%t\t%S\t%T\t%L\t%c\t%r\t%A\t%m\t%h\t%u%n"

DefaultTextLogFormat default log format TIME STATUS LATENCY LENGTH CLIENT_IP REMOTE_ADDR LISTEN METHOD HOST URL

Variables

This section is empty.

Functions

func DigestAuthParams

func DigestAuthParams(auth string) map[string]string

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

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.DefaultTextLogFormat)

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) 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) 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) 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) 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

func NewLocalizer(locales ...string) *Localizer

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

func (ProxiedFlag) String

func (pf ProxiedFlag) String() string

String return level string

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) Handler

func (rl *RequestLimiter) Handler() xin.HandlerFunc

Handler returns the xin.HandlerFunc

type ResponseHeader

type ResponseHeader struct {
	Header map[string]string
}

ResponseHeader response header middleware

func NewResponseHeader

func NewResponseHeader(header map[string]string) *ResponseHeader

NewResponseHeader create a default ResponseHeader

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) 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

type UserProvider

type UserProvider interface {
	FindUser(username string) any
	GetPassword(user any) string
}

Jump to

Keyboard shortcuts

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