Documentation ¶
Index ¶
- Constants
- Variables
- func AddFuncMap(key string, fn interface{}) error
- func ConsoleColorPrint(color, format string, values ...interface{})
- func ConsolePrint(format string, values ...interface{})
- func ConsolePrintError(format string, values ...interface{})
- func ConsolePrintSuccess(format string, values ...interface{})
- func ConsolePrintWarn(format string, values ...interface{})
- func DisableConsoleColor()
- func ExecuteTemplate(wr io.Writer, name string, data interface{}) error
- func ForceConsoleColor()
- func HasTemplateExt(paths string) bool
- func IsDebugging() bool
- func LoadTemplates(dir string) error
- func Mode() string
- func SetMode(value string)
- type Context
- func (c *Context) Abort()
- func (c *Context) AbortWithStatus(code int)
- func (c *Context) ClientIP() string
- func (c *Context) Cookie(name string) (string, error)
- func (c *Context) Data(code int, data []byte)
- func (c *Context) DefaultPostForm(key, defaultValue string) string
- func (c *Context) DefaultQuery(key, defaultValue string) string
- func (c *Context) Fail(code int, err string)
- func (c *Context) FormFile(name string) (*multipart.FileHeader, error)
- func (c *Context) Get(key string) (value interface{}, exists bool)
- func (c *Context) GetInt(key string) (i int)
- func (c *Context) GetInt64(key string) (i64 int64)
- func (c *Context) GetPostForm(key string) (string, bool)
- func (c *Context) GetPostFormArray(key string) ([]string, bool)
- func (c *Context) GetQuery(key string) (string, bool)
- func (c *Context) GetQueryArray(key string) ([]string, bool)
- func (c *Context) GetString(key string) (s string)
- func (c *Context) HTML(code int, name string, data interface{})
- func (c *Context) Header(key, value string)
- func (c *Context) IsAborted() bool
- func (c *Context) IsAjax() bool
- func (c *Context) IsUpload() bool
- func (c *Context) JSON(code int, obj interface{})
- func (c *Context) MultipartForm() (*multipart.Form, error)
- func (c *Context) Next()
- func (c *Context) Param(key string) string
- func (c *Context) PostForm(key string) string
- func (c *Context) PostFormArray(key string) []string
- func (c *Context) Query(key string) string
- func (c *Context) QueryArray(key string) []string
- func (c *Context) Redirect(status int, localurl string)
- func (c *Context) RequestBody() []byte
- func (c *Context) Set(key string, value interface{})
- func (c *Context) SetCookie(name, value string, maxAge int, path, domain string, secure, httpOnly bool)
- func (c *Context) SetSameSite(samesite http.SameSite)
- func (c *Context) ShouldBindJSON(obj interface{}) error
- func (c *Context) ShouldBindWith(obj interface{}, b binding.Binding) error
- func (c *Context) Status(code int)
- func (c *Context) String(code int, format string, values ...interface{})
- func (c *Context) WriteHeaderNow()
- type Engine
- type Error
- type ErrorType
- type H
- type HandlerFunc
- func ErrorLogger() HandlerFunc
- func ErrorLoggerT(typ ErrorType) HandlerFunc
- func Logger() HandlerFunc
- func LoggerWithConfig(conf LoggerConfig) HandlerFunc
- func LoggerWithFormatter(f LogFormatter) HandlerFunc
- func LoggerWithWriter(out io.Writer, notlogged ...string) HandlerFunc
- func Recovery() HandlerFunc
- func RecoveryWithWriter(out io.Writer) HandlerFunc
- type LogFormatter
- type LogFormatterParams
- type LoggerConfig
- type RouterGroup
- func (group *RouterGroup) ANY(pattern string, handler HandlerFunc)
- func (group *RouterGroup) DELETE(pattern string, handler HandlerFunc)
- func (group *RouterGroup) GET(pattern string, handler HandlerFunc)
- func (group *RouterGroup) Group(prefix string) *RouterGroup
- func (group *RouterGroup) HEAD(pattern string, handler HandlerFunc)
- func (group *RouterGroup) Handle(httpMethod, relativePath string, handler HandlerFunc)
- func (group *RouterGroup) OPTIONS(pattern string, handler HandlerFunc)
- func (group *RouterGroup) PATCH(pattern string, handler HandlerFunc)
- func (group *RouterGroup) POST(pattern string, handler HandlerFunc)
- func (group *RouterGroup) PUT(pattern string, handler HandlerFunc)
- func (group *RouterGroup) Static(relativePath, root string)
- func (group *RouterGroup) StaticFS(relativePath string, fs http.FileSystem)
- func (group *RouterGroup) Use(middlewares ...HandlerFunc)
Constants ¶
const ( ConsoleFrontColorWhite string = "\u001B[30m" ConsoleFrontColorRed string = "\u001B[31m" ConsoleFrontColorGreen string = "\u001B[32m" ConsoleFrontColorYellow string = "\u001B[33m" ConsoleFrontColorBlue string = "\u001B[34m" ConsoleFrontColorPink string = "\u001B[35m" ConsoleFrontColorCyan string = "\u001B[36m" ConsoleFrontColorBlack string = "\u001B[37m" ConsoleFrontColorReset string = "\u001B[0m" )
const ( DevMode = "dev" TestMode = "test" ProdMode = "prod" )
const EnvGigMode = "GIG_MODE"
const VERSION = "0.0.1"
VERSION represent beego web framework version.
Variables ¶
var DefaultErrorWriter io.Writer = os.Stderr
DefaultErrorWriter is the default io.Writer used by Gin to debug errors
var DefaultWriter io.Writer = os.Stdout
DefaultWriter is the default io.Writer used by Gin for debug output and middleware output like Logger() or Recovery(). Note that both Logger and Recovery provides custom ways to configure their output io.Writer. To support coloring in Windows use:
import "github.com/mattn/go-colorable" gin.DefaultWriter = colorable.NewColorableStdout()
var ( // HTTPMETHOD list the supported http methods. HTTPMETHODS = map[string]bool{ "GET": true, "POST": true, "PUT": true, "DELETE": true, "PATCH": true, "OPTIONS": true, "HEAD": true, } )
支持的Methods
Functions ¶
func AddFuncMap ¶
AddFuncMap let user to register a func in the template.
func ConsoleColorPrint ¶ added in v0.0.3
func ConsoleColorPrint(color, format string, values ...interface{})
ConsoleColorPrint
func ConsolePrint ¶ added in v0.0.3
func ConsolePrint(format string, values ...interface{})
ConsolePrint
func ConsolePrintError ¶ added in v0.0.3
func ConsolePrintError(format string, values ...interface{})
ConsolePrintError
func ConsolePrintSuccess ¶ added in v0.0.3
func ConsolePrintSuccess(format string, values ...interface{})
ConsolePrintSuccess
func ConsolePrintWarn ¶ added in v0.0.3
func ConsolePrintWarn(format string, values ...interface{})
ConsolePrintWarn
func DisableConsoleColor ¶
func DisableConsoleColor()
DisableConsoleColor disables color output in the console.
func ExecuteTemplate ¶
ExecuteViewPathTemplate applies the template with name and from specific viewPath to the specified data object, writing the output to wr. A template will be executed safely in parallel.
func ForceConsoleColor ¶
func ForceConsoleColor()
ForceConsoleColor force color output in the console.
func HasTemplateExt ¶
HasTemplateExt return this path contains supported template extension of gig or not.
func LoadTemplates ¶
BuildTemplate will build all template files in a directory. it makes gig can render any template file in view directory.
Types ¶
type Context ¶
type Context struct { // HttpWriter Writer http.ResponseWriter // HttpRequest Request *http.Request // 路由参数 Params map[string]string // 响应状态码 StatusCode int // Errors is a list of errors attached to all the handlers/middlewares who used this context. Errors errorMsgs // 给每个请求的Context存储元数据 Keys map[string]interface{} // 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 (ex: the password does not match), call Abort to ensure the remaining handlers for this request are not called.
func (*Context) AbortWithStatus ¶
AbortWithStatus calls `Abort()` and writes the headers with the specified status code. For example, a failed attempt to authenticate a request could use: context.AbortWithStatus(401).
func (*Context) Cookie ¶
Cookie returns the named cookie provided in the request or ErrNoCookie if not found. And return the named cookie is unescaped. If multiple cookies match the given name, only one cookie will be returned.
func (*Context) DefaultPostForm ¶
DefaultPostForm 解析Post方式提交的Form表单参数, 失败时返回默认值
func (*Context) DefaultQuery ¶
DefaultQuery 获取Query参数,如果获取失败,返回默认值
func (*Context) FormFile ¶
func (c *Context) FormFile(name string) (*multipart.FileHeader, error)
FormFile 获取上传的第一个文件
func (*Context) GetPostForm ¶
GetPostForm 获取PostForm参数
func (*Context) GetPostFormArray ¶
GetPostFormArray 获取PostForm参数slice
func (*Context) GetQueryArray ¶
GetQueryArray 获取参数key对应的参数Slice
func (*Context) MultipartForm ¶
MultipartForm is the parsed multipart form, including file uploads.
func (*Context) PostFormArray ¶
PostFormArray 获取PostForm参数slice
func (*Context) SetCookie ¶
func (c *Context) SetCookie(name, value string, maxAge int, path, domain string, secure, httpOnly bool)
SetCookie adds a Set-Cookie header to the ResponseWriter's headers. The provided cookie must have a valid Name. Invalid cookies may be silently dropped.
func (*Context) SetSameSite ¶
SetSameSite with cookie
func (*Context) ShouldBindJSON ¶ added in v0.1.0
ShouldBindJSON 通过JSON绑定引擎绑定请求体参数
func (*Context) ShouldBindWith ¶ added in v0.1.0
ShouldBindWith 通过绑定引擎绑定请求体参数
func (*Context) WriteHeaderNow ¶
func (c *Context) WriteHeaderNow()
type Engine ¶
type Engine struct { *RouterGroup // 继承了分组的所有属性和方法 // If enabled, the router checks if another method is allowed for the // current route, if the current request can not be routed. // If this is the case, the request is answered with 'Method Not Allowed' // and HTTP status code 405. // If no other Method is allowed, the request is delegated to the NotFound // handler. HandleMethodNotAllowed bool ForwardedByClientIP bool // #726 #755 If enabled, it will thrust some headers starting with // 'X-AppEngine...' for better integration with that PaaS. AppEngine bool // Value of 'maxMemory' param that is given to http.Request's ParseMultipartForm // method call. MaxMultipartMemory int64 // contains filtered or unexported fields }
定义Engine,实现ServeHTPP接口
func (*Engine) AddFuncMap ¶
AddFuncMap
type Error ¶
Error represents a error's specification.
func (*Error) MarshalJSON ¶
MarshalJSON implements the json.Marshaller interface.
type ErrorType ¶
type ErrorType uint64
ErrorType is an unsigned 64-bit error code as defined in the gin spec.
const ( // ErrorTypeBind is used when Context.Bind() fails. ErrorTypeBind ErrorType = 1 << 63 // ErrorTypeRender is used when Context.Render() fails. ErrorTypeRender ErrorType = 1 << 62 // ErrorTypePrivate indicates a private error. ErrorTypePrivate ErrorType = 1 << 0 // ErrorTypePublic indicates a public error. ErrorTypePublic ErrorType = 1 << 1 // ErrorTypeAny indicates any other error. ErrorTypeAny ErrorType = 1<<64 - 1 // ErrorTypeNu indicates any other error. ErrorTypeNu = 2 )
type HandlerFunc ¶
type HandlerFunc func(*Context)
定义HandlerFunc, 提供给框架用户,用来定义路由映射的处理方法
func ErrorLogger ¶
func ErrorLogger() HandlerFunc
ErrorLogger returns a handlerfunc for any error type.
func ErrorLoggerT ¶
func ErrorLoggerT(typ ErrorType) HandlerFunc
ErrorLoggerT returns a handlerfunc for a given error type.
func Logger ¶
func Logger() HandlerFunc
Logger instances a Logger middleware that will write the logs to gin.DefaultWriter. By default gin.DefaultWriter = os.Stdout.
func LoggerWithConfig ¶
func LoggerWithConfig(conf LoggerConfig) HandlerFunc
LoggerWithConfig instance a Logger middleware with config.
func LoggerWithFormatter ¶
func LoggerWithFormatter(f LogFormatter) HandlerFunc
LoggerWithFormatter instance a Logger middleware with the specified log format function.
func LoggerWithWriter ¶
func LoggerWithWriter(out io.Writer, notlogged ...string) HandlerFunc
LoggerWithWriter instance a Logger middleware with the specified writer buffer. Example: os.Stdout, a file opened in write mode, a socket...
func Recovery ¶
func Recovery() HandlerFunc
Recovery returns a middleware that recovers from any panics and writes a 500 if there was one.
type LogFormatter ¶
type LogFormatter func(params LogFormatterParams) string
LogFormatter gives the signature of the formatter function passed to LoggerWithFormatter
type LogFormatterParams ¶
type LogFormatterParams struct { Request *http.Request // TimeStamp shows the time after the server returns a response. TimeStamp time.Time // StatusCode is HTTP response code. StatusCode int // Latency is how much time the server cost to process a certain request. Latency time.Duration // ClientIP equals Context's ClientIP method. ClientIP string // Method is the HTTP method given to the request. Method string // Path is a path the client requests. Path string // ErrorMessage is set if error has occurred in processing the request. ErrorMessage string // BodySize is the size of the Response Body BodySize int // Keys are the keys set on the request's context. Keys map[string]interface{} // contains filtered or unexported fields }
LogFormatterParams is the structure any formatter will be handed when time to log comes
func (*LogFormatterParams) IsOutputColor ¶
func (p *LogFormatterParams) IsOutputColor() bool
IsOutputColor indicates whether can colors be outputted to the log.
func (*LogFormatterParams) MethodColor ¶
func (p *LogFormatterParams) MethodColor() string
MethodColor is the ANSI color for appropriately logging http method to a terminal.
func (*LogFormatterParams) ResetColor ¶
func (p *LogFormatterParams) ResetColor() string
ResetColor resets all escape attributes.
func (*LogFormatterParams) StatusCodeColor ¶
func (p *LogFormatterParams) StatusCodeColor() string
StatusCodeColor is the ANSI color for appropriately logging http status code to a terminal.
type LoggerConfig ¶
type LoggerConfig struct { // Optional. Default value is gin.defaultLogFormatter Formatter LogFormatter // Output is a writer where logs are written. // Optional. Default value is gin.DefaultWriter. Output io.Writer // SkipPaths is a url path array which logs are not written. // Optional. SkipPaths []string }
LoggerConfig defines the config for Logger middleware.
type RouterGroup ¶
type RouterGroup struct {
// contains filtered or unexported fields
}
定义路由分组
func (*RouterGroup) DELETE ¶
func (group *RouterGroup) DELETE(pattern string, handler HandlerFunc)
DELETE路由
func (*RouterGroup) HEAD ¶
func (group *RouterGroup) HEAD(pattern string, handler HandlerFunc)
HEAD路由
func (*RouterGroup) Handle ¶ added in v0.0.7
func (group *RouterGroup) Handle(httpMethod, relativePath string, handler HandlerFunc)
Handle For GET, POST, PUT, PATCH and DELETE requests the respective shortcut functions can be used.
func (*RouterGroup) OPTIONS ¶
func (group *RouterGroup) OPTIONS(pattern string, handler HandlerFunc)
OPTIONS路由
func (*RouterGroup) PATCH ¶
func (group *RouterGroup) PATCH(pattern string, handler HandlerFunc)
PATCH路由
func (*RouterGroup) POST ¶
func (group *RouterGroup) POST(pattern string, handler HandlerFunc)
POST路由
func (*RouterGroup) Static ¶
func (group *RouterGroup) Static(relativePath, root string)
静态文件 use :
router.Static("/static", "/var/www")
func (*RouterGroup) StaticFS ¶
func (group *RouterGroup) StaticFS(relativePath string, fs http.FileSystem)