Documentation ¶
Index ¶
- func NiceRecovery(f func(c *gin.Context, err interface{})) gin.HandlerFunc
- func NiceRecoveryWithWriter(f func(c *gin.Context, err interface{}), out io.Writer) gin.HandlerFunc
- type CsrfConfig
- type GZipConfig
- type Gin
- type GinJwt
- type GinTemplate
- type GinZap
- type PerClientQps
- type Route
- type RouteDefinition
- type SessionConfig
- type SystemInfo
- type SystemLogin
- type TemplateDefintion
- type UserInfo
- type UserLogin
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func NiceRecovery ¶ added in v1.0.6
func NiceRecovery(f func(c *gin.Context, err interface{})) gin.HandlerFunc
NiceRecovery replaces default recovery, with custom content, to be called via gin.New() right after object init
Credit: code based and revised from github.com/ekyoung/gin-nice-recovery
func NiceRecoveryWithWriter ¶ added in v1.0.6
NiceRecoveryWithWriter replaces default recovery, with custom content, to be called via gin.New() right after object init
Credit: code based and revised from github.com/ekyoung/gin-nice-recovery
Types ¶
type CsrfConfig ¶ added in v1.0.6
type CsrfConfig struct { Secret string ErrorFunc func(c *gin.Context) TokenGetter func(c *gin.Context) string }
CsrfConfig defines csrf protection middleware options
Secret = (required) csrf secret key used for csrf protection ErrorFunc = (required) csrf invalid token error handler TokenGetter = (optional) csrf get token action override from default (in case implementation not using default keys)
default gets token from: - FormValue("_csrf") - Url.Query().Get("_csrf") - Header.Get("X-CSRF-TOKEN") - Header.Get("X-XSRF-TOKEN")
type GZipConfig ¶ added in v1.0.6
type GZipConfig struct { Compression gingzipcompression.GinGZipCompression ExcludedExtensions []string ExcludedPaths []string ExcludedPathsRegex []string }
GZipConfig defines options for the GZip middleware
func (*GZipConfig) GetGZipCompression ¶ added in v1.0.6
func (gz *GZipConfig) GetGZipCompression() int
GetGZipCompression returns gzip compression value
func (*GZipConfig) GetGZipExcludedExtensions ¶ added in v1.0.6
func (gz *GZipConfig) GetGZipExcludedExtensions() gzip.Option
GetGZipExcludedExtensions return gzip option for excluded extensions if any
func (*GZipConfig) GetGZipExcludedPaths ¶ added in v1.0.6
func (gz *GZipConfig) GetGZipExcludedPaths() gzip.Option
GetGZipExcludedPaths return gzip option for excluded paths if any
func (*GZipConfig) GetGZipExcludedPathsRegex ¶ added in v1.0.6
func (gz *GZipConfig) GetGZipExcludedPathsRegex() gzip.Option
GetGZipExcludedPathsRegex return gzip option for excluded paths refex if any
type Gin ¶
type Gin struct { // web server descriptive name (used for display and logging only) Name string // web server port to run gin web server Port uint // web server tls certificate pem and key file path TlsCertPemFile string TlsCertKeyFile string // web server routes to handle // string = routeGroup path if defined, otherwise, if * refers to base Routes map[string][]*RouteDefinition // define the session middleware for the gin engine SessionMiddleware *SessionConfig // define the csrf middleware for the gin engine CsrfMiddleware *CsrfConfig // define html template renderer HtmlTemplateRenderer *GinTemplate // contains filtered or unexported fields }
Gin struct provides a wrapper for gin-gonic based web server operations
Name = (required) web server descriptive display name Port = (required) tcp port that this web server will run on TlsCertPemFile / TlsCertKeyFile = (optional) when both are set, web server runs secured mode using tls cert; path to pem and key file Routes = (required) map of http route handlers to be registered, middleware to be configured,
for gin engine or route groups, key = * indicates base gin engine routes, otherwise key refers to routeGroup to be created
SessionMiddleware = (optional) defines the cookie or redis session middleware to setup for the gin engine CsrfMiddleware = (optional) defines the csrf middleware to setup for the gin engine (requires SessionMiddleware setup)
func NewServer ¶
func NewServer(name string, port uint, releaseMode bool, customRecovery bool, zaplogger ...*GinZap) *Gin
NewServer returns a gin-gongic web server wrapper ready for setup
customRecovery = indicates if the gin engine default recovery will be replaced, with one that has more custom render
if gin default logger is to be replaced, it must be replaced via zaplogger parameter, zaplogger must be fully setup and passed into NewServer in order for zaplogger replacement to be effective, zaplogger will not be setup after gin object is created
func (*Gin) AuthMiddleware ¶ added in v1.0.6
AuthMiddleware returns the GinJwt struct object built by NewAuthMiddleware, prepare the necessary field values and handlers via this method's return object access
func (*Gin) NewAuthMiddleware ¶ added in v1.0.6
func (g *Gin) NewAuthMiddleware(realm string, identityKey string, signingSecretKey string, authenticateBinding ginbindtype.GinBindType)
NewAuthMiddleware will create a new jwt auth middleware with basic info provided, then this new middleware is set into Gin wrapper internal var, this middleware's additional fields and handlers must then be defined by accessing the AuthMiddleware func, once middleware's completely prepared, then call the RunServer which automatically builds the auth middleware for use
type GinJwt ¶ added in v1.0.6
type GinJwt struct { // Realm name to display to the user. Required. Realm string // IdentityKey defines the key used for storing identity info in jwt claim IdentityKey string // Secret key used for signing. Required. SigningSecretKey string // HS256, HS384, HS512, RS256, RS384 or RS512 Optional, default is HS256. SigningAlgorithm ginjwtsignalgorithm.GinJwtSignAlgorithm // Private key file for asymmetric algorithms PrivateKeyFile string // Public key file for asymmetric algorithms PublicKeyFile string // Duration that a jwt token is valid. Optional, defaults to one hour. (aka Timeout) TokenValidDuration time.Duration // This field allows clients to refresh their token until MaxRefresh has passed. // Note that clients can refresh their token in the last moment of MaxRefresh. // This means that the maximum validity timespan for a token is TokenTime + MaxRefresh. // Optional, defaults to 0 meaning not refreshable. TokenMaxRefreshDuration time.Duration // SendAuthorization allow return authorization header for every request SendAuthorization bool // Disable abort() of context. DisableAbort bool // TokenLookup is a string in the form of "<source>:<name>" that is used to extract token from the request. // Optional. Default value "header:Authorization". // Possible values: // - "header:<name>" // - "query:<name>" // - "cookie:<name>" // - "param:<name>" // TokenLookup: "header: Authorization, query: token, cookie: jwt", // TokenLookup: "query:token", // TokenLookup: "cookie:token", TokenLookup string // TokenHeadName is a string in the header. Default value is "Bearer" // "Bearer" TokenHeadName string // ----------------------------------------------------------------------------------------------------------------- // cookie setup // ----------------------------------------------------------------------------------------------------------------- SendCookie bool CookieMaxAge time.Duration SecureCookie *bool CookieHTTPOnly *bool CookieDomain string CookieName string CookieSameSite *http.SameSite // AuthenticateBindingType defines the binding type to use for login form field data AuthenticateBindingType ginbindtype.GinBindType // LoginRoutePath defines the relative path to the middleware's built-in LoginHandler, // this route path is setup as POST with the gin engine LoginRoutePath string // LogoutRoutePath defines the relative path to the middleware's built-in LogoutHandler, // this route path is setup as POST with the gin engine LogoutRoutePath string // RefreshTokenRoutePath defines the relative path to the middleware's built-in RefreshHandler, // this route path is setup as GET with the gin engine RefreshTokenRoutePath string // AuthenticateHandler func is called by Authenticator, // receives loginFields for authentication use, // if authentication succeeds, returns the loggedInCredential object // (which typically is a user object containing user information logged in) AuthenticateHandler func(loginFields interface{}) (loggedInCredential interface{}) // AddClaimsHandler func is called during Authenticator action upon success, // so that this handler when coded can insert jwt additional payload data // // loggedInCredential = the returning loggedInCredential from LoginHandler // identityKeyValue = string value for the named identityKey defined within the struct AddClaimsHandler func(loggedInCredential interface{}) (identityKeyValue string, claims map[string]interface{}) // GetIdentityHandler func is called when IdentityHandler is triggered, // field values from claims will be parsed and returned via object by the implementation code GetIdentityHandler func(claims jwt.MapClaims) interface{} // Callback function to handle custom login response LoginResponseHandler func(c *gin.Context, statusCode int, token string, expires time.Time) // Callback function to handle custom logout response LogoutResponseHandler func(c *gin.Context, statusCode int) // Callback function to handle custom token refresh response RefreshTokenResponseHandler func(c *gin.Context, statusCode int, token string, expires time.Time) // AuthorizerHandler func is called during authorization after authentication, // to validate if the current credential has access rights to certain parts of the target site, // the loggedInCredential is the object that LoginHandler returns upon successful authentication, // return value of true indicates authorization success, // return value of false indicates authorization failure AuthorizerHandler func(loggedInCredential interface{}, c *gin.Context) bool // this handler will return the unauthorized message content to caller, // such as via c.JSON, c.HTML, etc as dictated by the handler implementation process // // c *gin.Context = context used to return the unauthorized access content // code / message = unauthorized code and message as given by the web server to respond back to the caller UnauthorizedHandler func(c *gin.Context, code int, message string) // TimeFunc provides the current time. // override it to use another time value. // useful for testing or if server uses a different time zone than the tokens. TimeHandler func() time.Time // NoRouteHandler is called when no route situation is encountered NoRouteHandler func(claims jwt.MapClaims, c *gin.Context) // HTTP Status messages for when something in the JWT middleware fails. // Check error (e) to determine the appropriate error message. MiddlewareErrorEvaluator func(e error, c *gin.Context) string // contains filtered or unexported fields }
GinJwt struct encapsulates gin authentication and authorization related services, along with jwt handling
*** Basic Setup *** Realm = (required) Realm name to display to the user IdentityKey = (required) IdentityKey defines the key used for storing identity info in jwt claim SigningSecretKey = (required) Secret key used for signing SigningAlgorithm = (required) HS256, HS384, HS512, RS256, RS384 or RS512 Optional, default is HS256 PrivateKeyFile = (optional) Private key file for asymmetric algorithms PublicKeyFile = (optional) Public key file for asymmetric algorithms TokenValidDuration = (required) Duration that a jwt token is valid. Optional, defaults to one hour. (aka Timeout) TokenMaxRefreshDuration = (required) This field allows clients to refresh their token until MaxRefresh has passed,
Note that clients can refresh their token in the last moment of MaxRefresh, This means that the maximum validity timespan for a token is TokenTime + MaxRefresh, Optional, defaults to 0 meaning not refreshable
SendAuthorization = (optional) SendAuthorization allow return authorization header for every request, default = false DisableAbort = (optional) Disable abort() of context, default = false TokenLookup = (optional) TokenLookup is a string in the form of "<source>:<name>" that is used to extract token from the request,
Optional. Default value = "header: Authorization", Possible values: - "header:<name>" - "query:<name>" - "cookie:<name>" - "param:<name>" Examples: TokenLookup: "header: Authorization, query: token, cookie: jwt", TokenLookup: "query:token", TokenLookup: "cookie:token",
TokenHeadName = (optional) TokenHeadName is a string in the header. Default value = "Bearer"
*** Cookie Setup *** SendCookie = (optional) Optionally return the token as a cookie, default = false CookieHttpOnly = (optional) Allow cookies to be accessed client side for development, default = true SecureCookie = (optional) Allow insecure cookies for development over http, default = true CookieMaxAge = (optional) Duration that a cookie is valid. Optional, by default = Timeout value CookieDomain = (optional) Allow cookie domain change for development, default = "" CookieName = (optional) CookieName allow cookie name change for development, default = "" CookieSameSite = (optional) CookieSameSite allow use http.SameSite cookie param, default = SameSiteDefaultMode
values = default, lax, strict, none
*** Authentication Setup *** AuthenticateBindingType = (required) AuthenticateBindingType defines the binding type to use for login form field data LoginRoutePath = (required) LoginRoutePath defines the relative path to the gin jwt middleware's built-in LoginHandler action, sets up as POST LogoutRoutePath = (optional) LogoutRoutePath defines the relative path to the gin jwt middleware's built-in LogoutHandler action, sets up as POST RefreshTokenRoutePath = (optional) RefreshTokenRoutePath defines the relative path to the middleware's built-in RefreshHandler action, sets up as GET AuthenticateHandler = (required) AuthenticateHandler func is called by Authenticator,
receives loginFields for authentication use, if authentication succeeds, returns the loggedInCredential object (which typically is a user object containing user information logged in)
AddClaimsHandler = (optional) LoggedInMapClaimsHandler func is called during Authenticator action upon success,
so that this handler when coded can insert jwt additional payload data, - loggedInCredential = the returning loggedInCredential from LoginHandler, - identityKeyValue = string value for the named identityKey defined within the struct
GetIdentityHandler = (optional) GetIdentityHandler func is called when IdentityHandler is triggered,
field values from claims will be parsed and returned via object by the implementation code
LoginResponseHandler = (optional) Callback function to handle custom login response LogoutResponseHandler = (optional) Callback function to handle custom logout response RefreshTokenResponseHandler = (optional) Callback function to handle custom token refresh response
*** Authorization Setup *** AuthorizerHandler = (optional) AuthorizerHandler func is called during authorization after authentication,
to validate if the current credential has access rights to certain parts of the target site, the loggedInCredential is the object that LoginHandler returns upon successful authentication, - return value of true indicates authorization success, - return value of false indicates authorization failure
UnauthorizedHandler = (optional) UnauthorizedHandler func is called when the authorization is not authorized,
this handler will return the unauthorized message content to caller, such as via c.JSON, c.HTML, etc as dictated by the handler implementation process, - c *gin.Context = context used to return the unauthorized access content - code / message = unauthorized code and message as given by the web server to respond back to the caller
*** Other Handlers *** TimeHandler = (optional) TimeHandler provides the current time,
override it to use another time value, useful for testing or if server uses a different time zone than the tokens, default = time.Now()
NoRouteHandler = (optional) Defines the route handler to execute when no route is encountered MiddlewareErrorEvaluator = (optional) HTTP Status messages for when something in the JWT middleware fails,
Check error (e) to determine the appropriate error message
func NewGinJwtMiddleware ¶ added in v1.0.6
func NewGinJwtMiddleware(realm string, identityKey string, signingSecretKey string, authenticateBindingType ginbindtype.GinBindType) *GinJwt
NewGinJwtMiddleware helper method returns a GinJwt struct object ready for setup and use
Realm = (required) Realm name to display to the user IdentityKey = (required) IdentityKey defines the key used for storing identity info in jwt claim SigningSecretKey = (required) Secret key used for signing AuthenticateBindingType = (required) AuthenticateBindingType defines the binding type to use for login form field data
func (*GinJwt) AuthMiddleware ¶ added in v1.0.6
func (j *GinJwt) AuthMiddleware() gin.HandlerFunc
AuthMiddleware returns the GinJwt Middleware HandlerFunc, so that it can perform jwt related auth services, for all route path defined within the same router group
For example:
ginJwt := <Gin Jwt Struct Object Obtained> authGroup := g.Group("/auth") authGroup.Use(ginJwt.AuthMiddleware()) authGroup.GET("/hello", ...) // route path within this auth group now secured by AuthMiddleware
func (*GinJwt) BuildGinJwtMiddleware ¶ added in v1.0.6
BuildGinJwtMiddleware sets up auth jwt middleware for gin web server, including adding login, logout, refreshtoken, and other routes where applicable
type GinTemplate ¶ added in v1.0.6
type GinTemplate struct { TemplateBaseDir string Templates []TemplateDefintion // contains filtered or unexported fields }
GinTemplate defines the struct for working with html template renderer
func NewTemplate ¶ added in v1.0.6
func NewTemplate(templateBaseDir string, templateLayoutPath string, templatePagePath string) *GinTemplate
NewTemplate creates new html template render worker object
templateBaseDir = (required) base directory that contains template files templateLayoutPath = (required) relative page layout folder path, layout defines site theme and common base pages
- to use page parts, use {{ template "xyz" }}
- see golang html page template rules for more information
templatePagePath = (optional) relative page part folder path, pages define portion of html to be inserted into layout themes
- to define page part with named template, use {{ define "xyz" }} {{ end }}
- see golang html page template rules for more information
notes
- c.HTML name = page html name, such as home.html, if there is no page name, then use layout name
- if c.HTML name cannot find target in renderer, error 500 will be encountered
- layout file should not contain page parts may not be rendered in c.HTML call
- basic info about html templates = https://blog.gopheracademy.com/advent-2017/using-go-templates/
func (*GinTemplate) LoadHtmlTemplates ¶ added in v1.0.6
func (t *GinTemplate) LoadHtmlTemplates() error
LoadHtmlTemplates will load html templates and set renderer into struct internal var
func (*GinTemplate) SetHtmlRenderer ¶ added in v1.0.6
func (t *GinTemplate) SetHtmlRenderer(g *Gin) error
SetHtmlRenderer will set the existing html renderer into gin engine's HTMLRender property
type GinZap ¶ added in v1.0.6
type GinZap struct { LogName string OutputToConsole bool TimeFormat string // default = time.RFC3339 TimeUtc bool // default = false PanicStack bool // default = false // contains filtered or unexported fields }
GinZap struct defines logger middleware for use with Gin, using Zap logging package, CREDIT:this code is based and modified from github.com/gin-contrib/zap
LogName = (required) specifies the log name being written to OutputToConsole = (required) specifies if logger writes to console or disk TimeFormat = (optional) default = time.RFC3339 TimeUtc = (optional) default = false PanicStack = (optional) when panic, log to include stack
func NewGinZapMiddleware ¶ added in v1.0.6
NewGinZapMiddleware returns a newly created GinZap struct object
func (*GinZap) Init ¶ added in v1.0.6
Init will initialize zap logger and prep ginzap struct object for middleware use
func (*GinZap) NormalLogger ¶ added in v1.0.6
func (z *GinZap) NormalLogger() gin.HandlerFunc
NormalLogger returns a gin.HandlerFunc (middleware) that logs requests using uber-go/zap.
Requests with errors are logged using zap.Error(). Requests without errors are logged using zap.Info().
func (*GinZap) PanicLogger ¶ added in v1.0.6
func (z *GinZap) PanicLogger() gin.HandlerFunc
PanicLogger returns a gin.HandlerFunc (middleware)
this logger recovers from any panics and logs requests using uber-go/zap
All errors are logged using zap.Error()
type PerClientQps ¶ added in v1.0.6
PerClientQps defines options for the PerClientQps based rate limit middleware
type Route ¶
type Route struct { // relative path to the endpoint for the route to handle RelativePath string // http method such as GET, POST, PUT, DELETE Method ginhttpmethod.GinHttpMethod // input value binding to be performed Binding ginbindtype.GinBindType // actual handler method to be triggered, // bindingInput if any, is the binding resolved object passed into the handler method Handler func(c *gin.Context, bindingInput interface{}) }
Route struct defines each http route handler endpoint
RelativePath = (required) route path such as /HelloWorld, this is the path to trigger the route handler Method = (required) GET, POST, PUT, DELETE Binding = (optional) various input data binding to target type option Handler = (required) function handler to be executed per method defined (actual logic goes inside handler)
- gin.Context Value Return Helpers: a) c.String(), c.HTML(), c.JSON(), c.JSONP(), c.PureJSON(), c.AsciiJSON(), c.SecureJSON(), c.XML(), c.YAML(), c.ProtoBuf(), c.Redirect(), c.Data(), c.DataFromReader(), c.Render()
type RouteDefinition ¶ added in v1.0.5
type RouteDefinition struct { Routes []*Route CorsMiddleware *cors.Config MaxLimitMiddleware *int PerClientQpsMiddleware *PerClientQps GZipMiddleware *GZipConfig UseAuthMiddleware bool CustomMiddleware []gin.HandlerFunc }
RouteDefinition struct contains per route group or gin engine's handlers and middleware
Note:
- route definition's map key = * means gin engine; key named refers to Route Group
Routes = (required) one or more route handlers defined for current route group or base engine CorsMiddleware = (optional) current cors middleware to use if setup for current route group or base engine MaxLimitMiddleware = (optional) current max rate limit middleware, controls how many concurrent handlers can process actions for the current route group or base engine PerClientQpsMiddleware = (optional) to enable per client Ip QPS limiter middleware, all 3 options must be set UseAuthMiddleware = (optional) to indicate if this route group uses auth middleware CustomMiddleware = (optional) slice of additional custom HandleFunc middleware
type SessionConfig ¶ added in v1.0.6
type SessionConfig struct { SecretKey string SessionNames []string RedisMaxIdleConnections int RedisHostAndPort string }
SessionConfig defines redis or cookie session configuration options
SecretKey = (required) for redis or cookie session, the secret key to use SessionNames = (required) for redis or cookie session, defined session names to use by middleware RedisMaxIdleConnections = (optional) for redis session, maximum number of idle connections to keep for redis client RedisHostAndPort = (optional) the redis endpoint host name and port, in host:port format (if not set, then cookie session is assumed)
To Use Sessions in Handler:
[Single Session] session := sessions.Default(c) v := session.Get("xyz") session.Set("xyz", xyz) session.Save() [Multiple Sessions] sessionA := sessions.DefaultMany(c, "a") sessionB := sessions.DefaultMany(c, "b") sessionA.Get("xyz") sessionA.Set("xyz", xyz) sessionA.Save()
type SystemInfo ¶ added in v1.0.6
SystemInfo is a helper struct for use in authentication, authorization, and identity, this struct represents a common use case for system based identity info, however, any other custom struct can be used instead as desired
type SystemLogin ¶ added in v1.0.6
type SystemLogin struct { AccessID string `form:"accessid" json:"accessid" binding:"required"` SecretKey string `form:"secretkey" json:"secretkey" binding:"required"` }
SystemLogin is a helper struct for use in authentication, this struct represents a common use case for system based login request data, however, any other custom struct can be used instead as desired
type TemplateDefintion ¶ added in v1.0.6
TemplateDefinition defines an unit of template render target
type UserInfo ¶ added in v1.0.6
UserInfo is a helper struct for use in authentication, authorization and identity, this struct represents a common use case for user based identity info, however, any other custom struct can be used instead as desired
type UserLogin ¶ added in v1.0.6
type UserLogin struct { Username string `form:"username" json:"username" binding:"required"` Password string `form:"password" json:"password" binding:"required"` }
UserLogin is a helper struct for use in authentication, this struct represents a common use case for user based login request data, however, any other custom struct can be used instead as desired