mel

package module
v0.0.0-...-1df630e 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: 26 Imported by: 6

README

mel

Documentation

Index

Constants

This section is empty.

Variables

View Source
var Methods = []string{
	"GET",
	"POST",
	"HEAD",
	"DELETE",
	"PUT",
	"OPTIONS",
	"TRACE",
	"PATCH",
}

Functions

func Dir

func Dir(root string, listDirectory bool) http.FileSystem

Dir returns a http.Filesystem that can be used by http.FileServer(). It is used interally in router.Static(). if listDirectory == true, then it works the same as http.Dir() otherwise it returns a filesystem that prevents http.FileServer() to list the directory files.

func IsDebugging

func IsDebugging() bool

IsDebugging returns true if the framework is running in debug mode. Use SetMode(gin.Release) to switch to disable the debug mode.

Types

type Array

type Array []interface{}

Array represents "array" in JSON.

type Context

type Context struct {
	Request *http.Request
	Writer  ResponseWriter

	Params

	Keys map[string]interface{}
	Errors

	*Mel
	// contains filtered or unexported fields
}

func (*Context) Abort

func (c *Context) Abort()

Abort prevents pending handlers from being called. Note that this will not stop the current handler. Let's say you have an authorization middleware that validates that the current request is authorized. If the authorization fails, call Abort to ensure the remaining handlers for this request are not called.

func (*Context) AbortWithError

func (c *Context) AbortWithError(code int, err error) *Error

AbortWithError calls `AbortWithStatus()` and `Error()` internally. This method stops the chain, writes the status code and pushes the specified error to `c.Errors`. See Context.Error() for more details.

func (*Context) AbortWithStatus

func (c *Context) AbortWithStatus(status int)

AbortWithStatus calls `Abort()` and writes the headers with the specified status code. For example, a failed attempt to authentificate a request could use: context.AbortWithStatus(401).

func (*Context) Bind

func (c *Context) Bind(obj interface{}) error

Bind checks the Content-Type to select a binding engine automatically, Depending the "Content-Type" header different bindings are used:

"application/json" --> JSON binding
"application/xml"  --> XML binding

otherwise --> returns an error It parses the request's body as JSON if Content-Type == "application/json" using JSON or XML as a JSON input. It decodes the json payload into the struct specified as a pointer. Like ParseBody() but this method also writes a 400 error if the json is not valid.

func (*Context) BindJSON

func (c *Context) BindJSON(obj interface{}) error

BindJSON is a shortcut for c.BindWith(obj, binding.JSON)

func (*Context) BindWith

func (c *Context) BindWith(obj interface{}, b binding.Binding) error

BindWith binds the passed struct pointer using the specified binding engine. See the binding package.

func (*Context) ClientIP

func (c *Context) ClientIP() string

ClientIP implements a best effort algorithm to return the real client IP. It parses X-Real-IP and X-Forwarded-For in order to work properly with reverse-proxies such as nginx or haproxy.

func (*Context) ContentType

func (c *Context) ContentType() string

ContentType returns the Content-Type header of the request.

func (*Context) Cookie

func (c *Context) Cookie(name string) (string, error)

func (*Context) Data

func (c *Context) Data(status int, contentType string, data []byte) error

func (*Context) Deadline

func (c *Context) Deadline() (deadline time.Time, ok bool)

func (*Context) Done

func (c *Context) Done() <-chan struct{}

func (*Context) Err

func (c *Context) Err() error

func (*Context) Error

func (c *Context) Error(err error) *Error

Error adds an error to the context. It's a good idea to call Error for each error that occurred during the resolution of a request. A middleware can be used to collect all the errors and push them to a database together, print a log, or append it in the HTTP response.

func (*Context) File

func (c *Context) File(filePath string)

func (*Context) Get

func (c *Context) Get(key string) (value interface{}, exists bool)

Get returns the value for the given key, i.e., (value, true). If the value does not exists it returns (nil, false).

func (*Context) GetPostForm

func (c *Context) GetPostForm(key string) (string, bool)

func (*Context) GetPostForms

func (c *Context) GetPostForms(key string) ([]string, bool)

GetPostForms returns a slice of strings for a given form key, plus a boolean value whether at least one value exists for the given key.

func (*Context) GetQuery

func (c *Context) GetQuery(key string) (string, bool)

GetQuery returns the keyed url query value. If it exists, it returns `(value, true)` (even when the value is an empty string), othewise it returns `("", false)`.

    GET /?name=Manu&lastname=
    ("Manu", true) == c.GetQuery("name")
	   ("", false) == c.GetQuery("id")
	   ("", true) == c.GetQuery("lastname")

func (*Context) GetQuerys

func (c *Context) GetQuerys(key string) ([]string, bool)

GetQuerys returns a slice of strings for a given query key, plus a boolean value whether at least one value exists for the given key.

func (*Context) HTML

func (c *Context) HTML(status int, name string, obj interface{}) error

func (*Context) Header

func (c *Context) Header(key, value string)

Header sets the value associated with key in the header. If value == "", it removes the key in the header.

func (*Context) IsAborted

func (c *Context) IsAborted() bool

IsAborted returns true if the current context was aborted.

func (*Context) JSON

func (c *Context) JSON(status int, obj interface{}, indented ...bool) error

func (*Context) MustGet

func (c *Context) MustGet(key string) interface{}

MustGet returns the value for the given key if it exists, otherwise it panics.

func (*Context) Next

func (c *Context) Next()

Next executes the pending handlers in the chain inside the calling handler. It should be used only inside middleware.

func (*Context) Param

func (ctx *Context) Param(key string, defaults ...string) string

Param returns the value of the URL param.

func (*Context) ParamBool

func (ctx *Context) ParamBool(key string, defaults ...bool) bool

func (*Context) ParamEscape

func (ctx *Context) ParamEscape(key string, defaults ...string) string

func (*Context) ParamFloat32

func (ctx *Context) ParamFloat32(key string, defaults ...float32) float32

func (*Context) ParamFloat64

func (ctx *Context) ParamFloat64(key string, defaults ...float64) float64

func (*Context) ParamInt

func (ctx *Context) ParamInt(key string, defaults ...int) int

func (*Context) ParamInt32

func (ctx *Context) ParamInt32(key string, defaults ...int32) int32

func (*Context) ParamInt64

func (ctx *Context) ParamInt64(key string, defaults ...int64) int64

func (*Context) ParamStrings

func (ctx *Context) ParamStrings(key string, defaults ...[]string) []string

func (*Context) ParamUint

func (ctx *Context) ParamUint(key string, defaults ...uint) uint

func (*Context) ParamUint32

func (ctx *Context) ParamUint32(key string, defaults ...uint32) uint32

func (*Context) ParamUint64

func (ctx *Context) ParamUint64(key string, defaults ...uint64) uint64

func (*Context) PostForm

func (c *Context) PostForm(key string, defaultValue ...string) string

func (*Context) PostForms

func (c *Context) PostForms(key string) []string

PostForms returns a slice of strings for a given form key.

func (*Context) Query

func (c *Context) Query(key string, defaultValue ...string) string

Query returns the keyed url query value if it exists. If the key does not exist, it returns the defaultValue string, or an empty string (no defaultValue specified).

    GET /?name=Manu&lastname=
    c.Query("name") == "Manu"
    c.Query("lastname") == ""
    c.Query("id") == ""
	   c.Query("name", "unknown") == "Manu"
	   c.Query("lastname", "none") == ""
	   c.Query("id", "none") == "none"

func (*Context) Querys

func (c *Context) Querys(key string) []string

Querys returns a slice of strings for a given query key. The length of the slice depends on the number of params with the given key.

func (*Context) Redirect

func (c *Context) Redirect(code int, location string)

Redirect returns a HTTP redirect to the specific location.

func (*Context) SSE

func (c *Context) SSE(name string, message interface{}) error

SSE writes a Server-Sent Event into the body stream.

func (*Context) Set

func (c *Context) Set(key string, value interface{})

Set stores a new key/value pair exclusivelly for this context. It also lazy initializes c.Keys if it was not used previously.

func (*Context) SetCookie

func (c *Context) SetCookie(cookie *Cookie)

func (*Context) Status

func (c *Context) Status(status int)

func (*Context) Stream

func (c *Context) Stream(step func(w io.Writer) bool)

func (*Context) Text

func (c *Context) Text(status int, format string, data ...interface{}) error

func (*Context) Value

func (c *Context) Value(key interface{}) interface{}

func (*Context) XML

func (c *Context) XML(status int, obj interface{}) error

func (*Context) YAML

func (c *Context) YAML(status int, obj interface{}) error
type Cookie struct {
	Name     string
	Value    string
	Path     string
	Domain   string
	MaxAge   int
	Secure   bool
	HttpOnly bool
}

Cookie represents an HTTP cookie as sent in the Set-Cookie header of an HTTP response or the Cookie header of an HTTP request. Fields are a subset of http.Cookie fields.

type Error

type Error struct {
	Err  error
	Type ErrorType
	Meta interface{}
}

func (*Error) Error

func (msg *Error) Error() string

Error implements the error interface

func (*Error) IsType

func (msg *Error) IsType(t ErrorType) bool

func (*Error) JSON

func (msg *Error) JSON() interface{}

func (*Error) MarshalJSON

func (msg *Error) MarshalJSON() ([]byte, error)

MarshalJSON implements the json.Marshaller interface

type ErrorType

type ErrorType uint64
const (
	ErrorTypeAny     ErrorType = (1 << 64) - 1
	ErrorTypeBind    ErrorType = 1 << 63 // used when c.Bind() fails
	ErrorTypeRender  ErrorType = 1 << 62 // used when c.Render() fails
	ErrorTypePrivate ErrorType = 1 << 0
	ErrorTypePublic  ErrorType = 1 << 1
)

type Errors

type Errors []*Error

func (Errors) ByType

func (errs Errors) ByType(t ErrorType) Errors

ByType returns a readonly copy filtered by the type. Example, ByType(gin.ErrorTypePublic) returns a slice of errors with type=ErrorTypePublic

func (Errors) Errors

func (errs Errors) Errors() []string

Errors returns a slice of all the error messages. Example:

c.Error(errors.New("first"))
c.Error(errors.New("second"))
c.Error(errors.New("third"))
c.Errors.Errors() // == []string{"first", "second", "third"}

func (Errors) JSON

func (errs Errors) JSON() interface{}

func (Errors) Last

func (errs Errors) Last() *Error

Last returns the last error in the errs. It returns nil if the errs is empty.

func (Errors) MarshalJSON

func (errs Errors) MarshalJSON() ([]byte, error)

func (Errors) String

func (errs Errors) String() string

type Handler

type Handler func(*Context)

type Map

type Map map[string]interface{}

type Mel

type Mel struct {
	*Router

	RedirectTrailingSlash  bool
	RedirectFixedPath      bool
	HandleMethodNotAllowed bool
	ForwardedByClientIP    bool

	Template *template.Template
	// contains filtered or unexported fields
}

func New

func New() *Mel

func (*Mel) GetVar

func (mel *Mel) GetVar(key string) (value interface{}, exists bool)

GetVar returns the value for the given key, i.e., (value, true). If the value does not exists it returns (nil, false).

func (*Mel) LoadTemplateGlob

func (mel *Mel) LoadTemplateGlob(pattern string)

func (*Mel) LoadTemplates

func (mel *Mel) LoadTemplates(files ...string)

func (*Mel) MustGetVar

func (mel *Mel) MustGetVar(key string) interface{}

MustGetVar returns the value for the given key if it exists, otherwise it panics.

func (*Mel) NoMethod

func (mel *Mel) NoMethod(handlers ...Handler)

NoMethod sets handlers for requests that match a route for another HTTP method. It return a 405 code by default.

func (*Mel) NoRoute

func (mel *Mel) NoRoute(handlers ...Handler)

NoRoute sets handlers for requests that match no route. It return a 404 code by default.

func (*Mel) Run

func (mel *Mel) Run(addrs ...string) (err error)

Run attaches `mel` to a http.Server and starts listening and serving HTTP requests. Note: this method will block the calling goroutine indefinitely unless an error happens.

func (*Mel) RunTLS

func (mel *Mel) RunTLS(addr string, certFile string, keyFile string) (err error)

RunTLS attaches `mel` to a http.Server and starts listening and serving HTTPS (secure) requests. Note: this method will block the calling goroutine indefinitely unless an error happens.

func (*Mel) RunUnix

func (mel *Mel) RunUnix(file string) (err error)

RunUnix attaches `mel` to a http.Server and starts listening and serving HTTP requests through the specified unix socket (ie. a file). Note: this method will block the calling goroutine indefinitely unless an error happens.

func (*Mel) ServeHTTP

func (mel *Mel) ServeHTTP(w http.ResponseWriter, req *http.Request)

ServerHTTP implements the http.Handler interface.

func (*Mel) SetTemplate

func (mel *Mel) SetTemplate(template *template.Template)

func (*Mel) SetVar

func (mel *Mel) SetVar(key string, value interface{})

SetVar stores a new key/value pair exclusivelly for this app. It also lazy initializes mel.vars if it was not used previously.

func (*Mel) Use

func (mel *Mel) Use(middleware ...Handler)

Use attachs global middlewares to the app. The middlewares attached through Use() will be included in the handlers chain for every single request. Even 404, 405, static files... For example, this is the right place for a logger or error management middleware.

type Object

type Object map[string]interface{}

Object represents "object" in JSON.

type Param

type Param struct {
	Key   string
	Value string
}

Param is a single URL parameter, consisting of a key and a value.

type Params

type Params []Param

Params is a Param-slice, as returned by the router. The slice is ordered, the first URL parameter is also the first slice value. It is therefore safe to read values by the index.

func (*Params) Bool

func (p *Params) Bool(key string) (bool, error)

func (*Params) Escape

func (p *Params) Escape(key string) (string, error)

func (*Params) Float32

func (p *Params) Float32(key string) (float32, error)

func (*Params) Float64

func (p *Params) Float64(key string) (float64, error)

func (*Params) Get

func (p *Params) Get(key string) string

func (*Params) Int

func (p *Params) Int(key string) (int, error)

func (*Params) Int32

func (p *Params) Int32(key string) (int32, error)

func (*Params) Int64

func (p *Params) Int64(key string) (int64, error)

func (*Params) MustBool

func (p *Params) MustBool(key string, defaults ...bool) bool

func (*Params) MustEscape

func (p *Params) MustEscape(key string, defaults ...string) string

func (*Params) MustFloat32

func (p *Params) MustFloat32(key string, defaults ...float32) float32

func (*Params) MustFloat64

func (p *Params) MustFloat64(key string, defaults ...float64) float64

func (*Params) MustInt

func (p *Params) MustInt(key string, defaults ...int) int

func (*Params) MustInt32

func (p *Params) MustInt32(key string, defaults ...int32) int32

func (*Params) MustInt64

func (p *Params) MustInt64(key string, defaults ...int64) int64

func (*Params) MustString

func (p *Params) MustString(key string, defaults ...string) string

func (*Params) MustStrings

func (p *Params) MustStrings(key string, defaults ...[]string) []string

func (*Params) MustUint

func (p *Params) MustUint(key string, defaults ...uint) uint

func (*Params) MustUint32

func (p *Params) MustUint32(key string, defaults ...uint32) uint32

func (*Params) MustUint64

func (p *Params) MustUint64(key string, defaults ...uint64) uint64

func (*Params) Set

func (p *Params) Set(key, value string)

func (*Params) String

func (p *Params) String(key string) (string, error)

func (*Params) Strings

func (p *Params) Strings(key string) ([]string, error)

func (*Params) Uint

func (p *Params) Uint(key string) (uint, error)

func (*Params) Uint32

func (p *Params) Uint32(key string) (uint32, error)

func (*Params) Uint64

func (p *Params) Uint64(key string) (uint64, error)

type ResponseWriter

type ResponseWriter interface {
	http.ResponseWriter
	http.Flusher
	http.Hijacker
	http.CloseNotifier

	// Reset resets the embedded http.ResponseWriter.
	Reset(writer http.ResponseWriter)

	// Status returns the HTTP response status code,
	// or 0 if the response has not been written.
	// If status was passed in, reset the HTTP response status.
	Status(status ...int) int

	// Written returns whether or not the response has been written.
	Written() bool

	// WriteString writes the string into the response body.
	WriteString(string) (int, error)

	// Size returns the number of bytes already written into the response http body.
	Size() int
}

ResponseWriter is a wrapper around http.ResponseWriter that provides extra information about the response.

type Route

type Route struct {
	// contains filtered or unexported fields
}

type RouteKind

type RouteKind uint8
const (
	FuncRoute       RouteKind = iota // func ()
	FuncRepReqRoute                  // func (http.ResponseWriter, *http.Request)
	FuncRepRoute                     // func (http.ResponseWriter)
	FuncReqRoute                     // func (*http.Request)
	FuncCtxRoute                     // func (*mel.Context)
)

type Router

type Router struct {
	RoutesGroup

	AllowCustomMethod   bool
	RemoveTrailingSlash bool
	// contains filtered or unexported fields
}

func NewRouter

func NewRouter() *Router

func (*Router) Match

func (r *Router) Match(method, path string) (*Route, Params, bool)

func (*Router) PrintTrees

func (r *Router) PrintTrees()

func (*Router) Register

func (r *Router) Register(methods interface{}, path string, target interface{}, handlers ...Handler)

type RoutesGroup

type RoutesGroup struct {
	BasePath string
	Handlers []Handler
	// contains filtered or unexported fields
}

RoutesGroup is used internally to configure router. A RoutesGroup is associated with a prefix and an array of handlers (middleware).

func (*RoutesGroup) Any

func (group *RoutesGroup) Any(relativePath string, handlers ...interface{})

Any registers a route that matches all the HTTP methods.

func (*RoutesGroup) Delete

func (group *RoutesGroup) Delete(relativePath string, handlers ...interface{})

func (*RoutesGroup) Get

func (group *RoutesGroup) Get(relativePath string, handlers ...interface{})

func (*RoutesGroup) Group

func (group *RoutesGroup) Group(relativePath string, handlers ...Handler) *RoutesGroup

Group creates a new router group. You should add all the routes that have common middlwares or the same path prefix.

func (*RoutesGroup) Handle

func (group *RoutesGroup) Handle(httpMethod, relativePath string, handlers ...interface{})

Handle registers a new request handle and middleware with the given path and method. The last handler should be the real handler, the other ones should be middleware that can and should be shared among different routes.

This function is intended for bulk loading and to allow the usage of less frequently used, non-standardized or custom methods (e.g. for internal communication with a proxy).

func (*RoutesGroup) Head

func (group *RoutesGroup) Head(relativePath string, handlers ...interface{})

func (*RoutesGroup) Options

func (group *RoutesGroup) Options(relativePath string, handlers ...interface{})

func (*RoutesGroup) Patch

func (group *RoutesGroup) Patch(relativePath string, handlers ...interface{})

func (*RoutesGroup) Post

func (group *RoutesGroup) Post(relativePath string, handlers ...interface{})

func (*RoutesGroup) Put

func (group *RoutesGroup) Put(relativePath string, handlers ...interface{})

func (*RoutesGroup) StaticDir

func (group *RoutesGroup) StaticDir(relativePath, root string)

StaticDir serves files from the given file system root. router.StaticDir("/static", "/var/www")

func (*RoutesGroup) StaticFile

func (group *RoutesGroup) StaticFile(relativePath, filePath string)

StaticFile registers a single route in order to server a single file of the local filesystem. router.StaticFile("favicon.ico", "./resources/favicon.ico")

func (*RoutesGroup) Trace

func (group *RoutesGroup) Trace(relativePath string, handlers ...interface{})

func (*RoutesGroup) Use

func (group *RoutesGroup) Use(middlewares ...Handler)

Use adds middleware to the group.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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