gig

package module
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Oct 4, 2022 License: MIT Imports: 29 Imported by: 0

README

gig

gig 是一个简单的Go MVC 框架,仅供自己学习Gin框架时练习使用。

Documentation

Index

Constants

View Source
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"
)
View Source
const (
	DevMode  = "dev"
	TestMode = "test"
	ProdMode = "prod"
)
View Source
const EnvGigMode = "GIG_MODE"
View Source
const VERSION = "0.0.1"

VERSION represent beego web framework version.

Variables

View Source
var DefaultErrorWriter io.Writer = os.Stderr

DefaultErrorWriter is the default io.Writer used by Gin to debug errors

View Source
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()
View Source
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

func AddFuncMap(key string, fn interface{}) error

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

func ExecuteTemplate(wr io.Writer, name string, data interface{}) error

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

func HasTemplateExt(paths string) bool

HasTemplateExt return this path contains supported template extension of gig or not.

func IsDebugging

func IsDebugging() bool

是否调试模式

func LoadTemplates

func LoadTemplates(dir string) error

BuildTemplate will build all template files in a directory. it makes gig can render any template file in view directory.

func Mode

func Mode() string

Mode returns currently gin mode.

func SetMode

func SetMode(value string)

设置运行模式

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

func (c *Context) AbortWithStatus(code int)

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

func (c *Context) ClientIP() string

ClientIP 获取客户端IP

func (*Context) Cookie

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

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

func (c *Context) Data(code int, data []byte)

Data 响应数据

func (*Context) DefaultPostForm

func (c *Context) DefaultPostForm(key, defaultValue string) string

DefaultPostForm 解析Post方式提交的Form表单参数, 失败时返回默认值

func (*Context) DefaultQuery

func (c *Context) DefaultQuery(key, defaultValue string) string

DefaultQuery 获取Query参数,如果获取失败,返回默认值

func (*Context) Fail

func (c *Context) Fail(code int, err string)

Fail 响应失败

func (*Context) FormFile

func (c *Context) FormFile(name string) (*multipart.FileHeader, error)

FormFile 获取上传的第一个文件

func (*Context) Get added in v0.0.7

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

Get 获取元数据

func (*Context) GetInt added in v0.0.7

func (c *Context) GetInt(key string) (i int)

GetInt 获取Int元数据

func (*Context) GetInt64 added in v0.0.7

func (c *Context) GetInt64(key string) (i64 int64)

GetInt64 获取Int64元数据

func (*Context) GetPostForm

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

GetPostForm 获取PostForm参数

func (*Context) GetPostFormArray

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

GetPostFormArray 获取PostForm参数slice

func (*Context) GetQuery

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

GetQuery 获取单个Query参数,获取不到会返回false

func (*Context) GetQueryArray

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

GetQueryArray 获取参数key对应的参数Slice

func (*Context) GetString added in v0.0.7

func (c *Context) GetString(key string) (s string)

GetString 获取String元数据

func (*Context) HTML

func (c *Context) HTML(code int, name string, data interface{})

HTML 响应HTML格式数据 类似Beego使用的方法

func (*Context) Header

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

Header 设置HTTP响应头信息 如果 value == "" 则会删除当前header

func (*Context) IsAborted

func (c *Context) IsAborted() bool

IsAborted returns true if the current context was aborted.

func (*Context) IsAjax

func (c *Context) IsAjax() bool

IsAjax 判断是否Ajax请求

func (*Context) IsUpload

func (c *Context) IsUpload() bool

IsUpload 判断是否上传文件

func (*Context) JSON

func (c *Context) JSON(code int, obj interface{})

JSON 响应JSON格式数据

func (*Context) MultipartForm

func (c *Context) MultipartForm() (*multipart.Form, error)

MultipartForm is the parsed multipart form, including file uploads.

func (*Context) Next

func (c *Context) Next()

Next 执行中间件HandleFunc和匹配到的路由HandleFunc

func (*Context) Param

func (c *Context) Param(key string) string

Param 获取路由参数 比如: /a/:name Param("name")

func (*Context) PostForm

func (c *Context) PostForm(key string) string

PostForm 解析Post方式提交的Form表单参数

func (*Context) PostFormArray

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

PostFormArray 获取PostForm参数slice

func (*Context) Query

func (c *Context) Query(key string) string

Query 获取单个Query参数

func (*Context) QueryArray

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

QueryArray 获取参数切片

func (*Context) Redirect

func (c *Context) Redirect(status int, localurl string)

Redirect 跳转

func (*Context) RequestBody

func (c *Context) RequestBody() []byte

RequestBody 获取RequestBody

func (*Context) Set added in v0.0.7

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

Set 设置元数据

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

func (c *Context) SetSameSite(samesite http.SameSite)

SetSameSite with cookie

func (*Context) ShouldBindJSON added in v0.1.0

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

ShouldBindJSON 通过JSON绑定引擎绑定请求体参数

func (*Context) ShouldBindWith added in v0.1.0

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

ShouldBindWith 通过绑定引擎绑定请求体参数

func (*Context) Status

func (c *Context) Status(code int)

Status 设置HTTP响应状态码

func (*Context) String

func (c *Context) String(code int, format string, values ...interface{})

String 响应String格式数据

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 Default

func Default() *Engine

默认引擎,使用了日志和错误恢复中间件

func New

func New() *Engine

创建一个新的引擎

func (*Engine) AddFuncMap

func (engine *Engine) AddFuncMap(key string, fn interface{}) error

AddFuncMap

func (*Engine) Run

func (engine *Engine) Run(addr string) (err error)

运行http server

func (*Engine) ServeHTTP

func (engine *Engine) ServeHTTP(w http.ResponseWriter, req *http.Request)

实现ServeHTTP

func (*Engine) Templates

func (engine *Engine) Templates(viewPath string)

加载全部模板文件

type Error

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

Error represents a error's specification.

func (Error) Error

func (msg Error) Error() string

Error implements the error interface.

func (*Error) IsType

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

IsType judges one error.

func (*Error) JSON

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

JSON creates a properly formatted JSON

func (*Error) MarshalJSON

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

MarshalJSON implements the json.Marshaller interface.

func (*Error) SetMeta

func (msg *Error) SetMeta(data interface{}) *Error

SetMeta sets the error's meta data.

func (*Error) SetType

func (msg *Error) SetType(flags ErrorType) *Error

SetType sets the error's type.

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 H

type H map[string]interface{}

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.

func RecoveryWithWriter

func RecoveryWithWriter(out io.Writer) HandlerFunc

错误恢复中间件

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

func (group *RouterGroup) ANY(pattern string, handler HandlerFunc)

ANY路由

func (*RouterGroup) DELETE

func (group *RouterGroup) DELETE(pattern string, handler HandlerFunc)

DELETE路由

func (*RouterGroup) GET

func (group *RouterGroup) GET(pattern string, handler HandlerFunc)

GET路由

func (*RouterGroup) Group

func (group *RouterGroup) Group(prefix string) *RouterGroup

创建一个新的Group

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

func (group *RouterGroup) PUT(pattern string, handler HandlerFunc)

PUT路由

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)

func (*RouterGroup) Use

func (group *RouterGroup) Use(middlewares ...HandlerFunc)

添加中间件到group

Directories

Path Synopsis
internal

Jump to

Keyboard shortcuts

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