melware

package module
v0.0.0-...-5787b36 Latest Latest
Warning

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

Go to latest
Published: Jul 2, 2018 License: Apache-2.0 Imports: 25 Imported by: 2

README

melware

Documentation

Index

Constants

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

Key for storing config object into a Mel instance.

Variables

This section is empty.

Functions

func DB

func DB(mel *mel.Mel) *sql.DB

func DBConfig

func DBConfig(mel *mel.Mel) *viper.Viper

func DefaultLogger

func DefaultLogger() mel.Handler

DefaultLogger instances a log middleware that will write the logs to os.Stdout.

func Favicon

func Favicon(path string, maxAge ...int) mel.Handler

func Gzip

func Gzip(level int) mel.Handler

func Logger

func Logger(out io.Writer, notlogged ...string) mel.Handler

Logger instances a log middleware with the specified io.Writer. Example: os.Stdout, a file opened in write mode, a socket...

func Logrus

func Logrus(logger *logrus.Logger, timeFormat string, utc bool) mel.Handler

Logrus returns a middleware that logs requests using logrus. Requests with errors are logged using logrus.Error(). Requests without errors are logged using logrus.Info(). The timeFormat specifies the time format string, e.g., time.RFC3339. The utc determines whether to use UTC time zone or local.

func Recovery

func Recovery() mel.Handler

Recovery returns a middleware that recovers from any panics and writes a 500 if there was one.

func RecoveryWithWriter

func RecoveryWithWriter(out io.Writer) mel.Handler

func Zap

func Zap(logger *zap.SugaredLogger) mel.Handler

Logrus returns a middleware that logs requests using logrus. Requests with errors are logged using logrus.Error(). Requests without errors are logged using logrus.Info(). The timeFormat specifies the time format string, e.g., time.RFC3339. The utc determines whether to use UTC time zone or local.

Types

type Config

type Config struct {
	*viper.Viper
}

func GetConfig

func GetConfig(mel *mel.Mel) *Config

GetConfig returns the config for a Mel instance. If the config doesn't exist in Mel, create a new one and put it into Mel. The config object inherently has all the methods of viper.Viper.

func (*Config) ReadDirs

func (c *Config) ReadDirs(configName string, dirs ...string) error

ReadDirs reads config from a found file named as configName in several directories.

func (*Config) ReadFile

func (c *Config) ReadFile(configFile string) error

ReadFile reads config from the specified file.

type Cors

type Cors struct {
	// AllowedOrigins is a list of origins a cross-domain request can be executed from.
	// If the special "*" value is present in the list, all origins will be allowed.
	// An origin may contain a wildcard (*) to replace 0 or more characters
	// (i.e.: http://*.domain.com). Usage of wildcards implies a small performance penalty.
	// Only one wildcard can be used per origin.
	// Default value is ["*"]
	AllowedOrigins []string
	// AllowOriginFunc is a custom function to validate the origin. It take the origin
	// as argument and returns true if allowed or false otherwise. If this option is
	// set, the content of AllowedOrigins is ignored.
	AllowOriginFunc func(origin string) bool
	// AllowedMethods is a list of methods the client is allowed to use with
	// cross-domain requests. Default value is simple methods (HEAD, GET and POST).
	AllowedMethods []string
	// AllowedHeaders is list of non simple headers the client is allowed to use with
	// cross-domain requests.
	// If the special "*" value is present in the list, all headers will be allowed.
	// Default value is [] but "Origin" is always appended to the list.
	AllowedHeaders []string
	// ExposedHeaders indicates which headers are safe to expose to the API of a CORS
	// API specification
	ExposedHeaders []string
	// AllowCredentials indicates whether the request can include user credentials like
	// cookies, HTTP authentication or client side SSL certificates.
	AllowCredentials bool
	// MaxAge indicates how long (in seconds) the results of a preflight request
	// can be cached
	MaxAge int
	// OptionsPassthrough instructs preflight to let other potential next handlers to
	// process the OPTIONS method. Turn this on if your application handles OPTIONS.
	OptionsPassthrough bool
	// Debugging flag adds additional output to debug server side CORS issues
	Debug bool

	*cors.Cors
}

func CorsAllowAll

func CorsAllowAll() *Cors

func (*Cors) Middleware

func (c *Cors) Middleware() mel.Handler

type Gorm

type Gorm struct {
	*viper.Viper
	*gorm.DB
}

func NewGorm

func NewGorm(mel *mel.Mel) *Gorm

type JWT

type JWT struct {
	// Realm specifies the realm name to display to the user.
	// Optional.
	Realm string

	// SigningAlgorithm specifies signing algorithm.
	// Optional. Default is HS256.
	SigningAlgorithm string

	// Key specifies the secret key used for signing.
	// Required.
	Key []byte

	// Timeout specifies the duration that a token is valid.
	// Optional. Defaults to one hour.
	Timeout time.Duration

	// MaxRefresh specifies the maximum duration in which the client can refresh its token.
	// Optional. Defaults to 0 meaning not refreshable.
	MaxRefresh time.Duration

	// Authenticate specifies the callback that should perform the authentication
	// of the user based on request context.
	// Must return nil error on success, error on failure.
	// Required. Optional return user id, if so, user id will be stored in Claim Array.
	Authenticate func(c *mel.Context) (string, error)

	// Authorize specifies the callback that should perform the authorization
	// of the authenticated user.
	// Must return true on success, false on failure.
	// Optional. Default to always return success.
	Authorize func(userID string, c *mel.Context) bool

	// PayloadFunc specifies the callback that will be called during login.
	// It is useful for adding additional payload data to the token.
	// The data is then made available during requests via ExtractClaims(PayloadKey).
	// Note that the payload is not encrypted.
	// Optional. By default no additional payload will be added.
	PayloadFunc func(userID string) map[string]interface{}

	// Unauthorized specifies the unauthorized function.
	Unauthorized func(*mel.Context, int, string)

	// TokenBearer is a string in the form of "<source>:<name>"
	// that is used to extract token from the request.
	// Optional. Default to "header:Authorization".
	// Possible values:
	// - "header:<name>"
	// - "query:<name>"
	// - "cookie:<name>"
	TokenBearer string

	// PayloadKey specifies the key when puts JWT payload into Context.
	// Optional. Default to "JWT_PAYLOAD".
	PayloadKey string
	// contains filtered or unexported fields
}

JWT provides a Json-Web-Token authentication implementation. On failure, a 401 HTTP response is returned. On success, the wrapped middleware is called, and the userID is made available as c.Get("userID").(string). Users can get a token by posting a json request to LoginHandler. The token then needs to be passed in the Authentication header.

func (*JWT) ExtractClaims

func (j *JWT) ExtractClaims(c *mel.Context) jwt.MapClaims

ExtractClaims extracts the JWT claims.

func (*JWT) LoginHandler

func (j *JWT) LoginHandler() mel.Handler

LoginHandler can be used by clients to get a jwt token. Reply will be of the form {"token": "TOKEN"}.

func (*JWT) Middleware

func (j *JWT) Middleware() mel.Handler

Middleware returns a middleware that authorizes tokens.

func (*JWT) RefreshHandler

func (j *JWT) RefreshHandler(c *mel.Context)

RefreshHandler can be used to refresh a token. The token still needs to be valid on refresh. Shall be put under an endpoint that is using the Middleware. Reply will be of the form {"token": "TOKEN"}.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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