package module
v0.6.8 Latest Latest

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

Go to latest
Published: Aug 17, 2021 License: MIT Imports: 36 Imported by: 8



gow 是基于gin的HTTP框架,在gin的基础上,做了更好的html模板封装和数据输出。可用于开发Web API和Web网站项目。



1. 快速开始
mkdir hello
cd hello
go mod init
go get github.com/gkzy/gow
1.1 创建 main.go
package main

import (

func main() {
    r := gow.Default()

    r.GET("/", func(c *gow.Context) {
            "code": 0,
            "msg":  "success",
    //default :8080
1.2 运行
go run main.go

go build && ./hello
2. 做一个HTML网站



3. 使用手册

请查阅 使用手册:





View Source
const (
	ContentJSON              = "application/json; charset=utf-8"
	ContentHTML              = "text/html; charset=utf-8"
	ContentJavaScript        = "application/javascript; charset=utf-8"
	ContentXML               = "application/xml; charset=utf-8"
	ContentXML2              = "text/xml; charset=utf-8"
	ContentPlain             = "text/plain; charset=utf-8"
	ContentPOSTForm          = "application/x-www-form-urlencoded"
	ContentMultipartPOSTForm = "multipart/form-data"
	ContentPROTOBUF          = "application/x-protobuf"
	ContentMSGPACK           = "application/x-msgpack"
	ContentMSGPACK2          = "application/msgpack"
	ContentYAML              = "application/x-yaml; charset=utf-8"
	ContentDownload          = "application/octet-stream; charset=utf-8"
View Source
const (
	DevMode  = "dev"
	TestMode = "test"
	ProdMode = "prod"
View Source
const (
	BestCompression    = gzip.BestCompression
	BestSpeed          = gzip.BestSpeed
	DefaultCompression = gzip.DefaultCompression
	NoCompression      = gzip.NoCompression


View Source
var (
	DefaultExcludedExtentions = NewExcludedExtensions([]string{
		".png", ".gif", ".jpeg", ".jpg",
	DefaultOptions = &Options{
		ExcludedExtensions: DefaultExcludedExtentions,
View Source
var (
	// DefaultWriter default io writer
	DefaultWriter io.Writer = os.Stdout

	// DefaultErrorWriter default error writer
	DefaultErrorWriter io.Writer = os.Stderr
View Source
var DebugPrintRouteFunc func(httpMethod, absolutePath, handlerName string, nuHandlers int)

DebugPrintRouteFunc indicates debug logy output format.


func BytesToString

func BytesToString(b []byte) string

BytesToString converts byte slice to string without a memory allocation.

func DefaultDecompressHandle added in v0.5.2

func DefaultDecompressHandle(c *Context)


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 internally 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 DisableConsoleColor added in v0.1.0

func DisableConsoleColor()

DisableConsoleColor disables color output in the console.

func ForceConsoleColor added in v0.1.0

func ForceConsoleColor()

ForceConsoleColor force color output in the console.

func InitSession added in v0.0.2

func InitSession()

InitSession init gow session

before using session,please call this function first

func IsDebugging added in v0.1.0

func IsDebugging() bool

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

func StringToBytes

func StringToBytes(s string) (b []byte)

StringToBytes converts string to byte slice without a memory allocation.


type AppConfig

type AppConfig struct {
	AppName       string //应用名称
	RunMode       string //运行模板
	HTTPAddr      string //监听端口
	AutoRender    bool   //是否自动渲染html模板
	Views         string //html模板目录
	TemplateLeft  string //模板符号
	TemplateRight string //模板符号
	SessionOn     bool   //是否打开session
	GzipOn        bool   // 是否打开gzip

AppConfig gow app 统一配置入口


func GetAppConfig

func GetAppConfig() *AppConfig

GetAppConfig 获取配置文件中的信息

 当环境变量 APP_RUN_MODE ="dev"时,使用 conf/dev.app.conf
 当环境变量 APP_RUN_MODE = "test"时,使用 conf/test.conf
 当环境变量 APP_RUN_MODE ="prod"时,使用 conf/prod.app.conf

type Body added in v0.1.0

type Body struct {
	Pager *Pager      `json:"pager"`
	Data  interface{} `json:"data"`

Body response body

type Context

type Context struct {
	Request *http.Request
	Writer  ResponseWriter

	Params Params

	// Keys is a key/value pair exclusively for the context of each request.
	Keys map[string]interface{}

	Data map[interface{}]interface{}

	// Errors is a list of errors attached to all the handlers/middlewares who used this context.
	Errors errorMsgs

	// Accepted defines a list of manually accepted formats for content negotiation.
	Accepted []string

	Pager *Pager
	// contains filtered or unexported fields

Context gow context

func (*Context) Abort

func (c *Context) Abort()

Abort abort handler

func (*Context) AbortWithError added in v0.2.2

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

AbortWithError `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 added in v0.1.0

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) Body added in v0.1.0

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

Body request body

func (*Context) ClientIP added in v0.1.0

func (c *Context) ClientIP() (ip string)

ClientIP get client ip address

func (*Context) DataJSON added in v0.1.0

func (c *Context) DataJSON(args ...interface{})

DataJSON DataJSON json data

response format json
c.DataJSON(1,"lost param")

func (*Context) DecodeJSONBody

func (c *Context) DecodeJSONBody(v interface{}) error

DecodeJSONBody request body to struct or map

func (*Context) DeleteSession added in v0.0.2

func (c *Context) DeleteSession(key string)

DeleteSession delete session key

func (*Context) Download

func (c *Context) Download(data []byte)

Download download data

func (*Context) Error added in v0.1.0

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

Error set error to c.Errors

func (*Context) File

func (c *Context) File(filepath string)

File writes the specified file into the body stream in a efficient way.

func (*Context) FileAttachment added in v0.1.0

func (c *Context) FileAttachment(filepath, filename string)

FileAttachment writes the specified file into the body stream in an efficient way On the client side, the file will typically be downloaded with the given filename

func (*Context) FileFromFS added in v0.1.0

func (c *Context) FileFromFS(filepath string, fs http.FileSystem)

FileFromFS writes the specified file from http.FileSytem into the body stream in an efficient way.

func (*Context) Form

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

Form return request.FormValue key

func (*Context) FullPath added in v0.1.0

func (c *Context) FullPath() string

FullPath returns a matched route full path. For not found routes returns an empty string.

router.GET("/user/{id}", func(c *gin.Context) {
    c.FullPath() == "/user/:id" // true

func (*Context) GetBool

func (c *Context) GetBool(key string, def ...bool) (bool, error)

GetBool GetBool

func (*Context) GetCookie

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

GetCookie 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) GetFile

func (c *Context) GetFile(key string) (multipart.File, *multipart.FileHeader, error)

GetFile get single file from request

func (*Context) GetFiles

func (c *Context) GetFiles(key string) ([]*multipart.FileHeader, error)

GetFiles get files from request

func (*Context) GetFloat64

func (c *Context) GetFloat64(key string, def ...float64) (float64, error)

GetFloat64 GetFloat64

func (*Context) GetHeader

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

GetHeader returns value from request headers.

func (*Context) GetIP

func (c *Context) GetIP() (ip string)

GetIP return k8s Cluster ip

if ip=="" return ""

func (*Context) GetInt

func (c *Context) GetInt(key string, def ...int) (int, error)

GetInt return int

func (*Context) GetInt16

func (c *Context) GetInt16(key string, def ...int16) (int16, error)

GetInt16 GetInt16


func (*Context) GetInt32

func (c *Context) GetInt32(key string, def ...int32) (int32, error)

GetInt32 GetInt32


func (*Context) GetInt64

func (c *Context) GetInt64(key string, def ...int64) (int64, error)

GetInt64 GetInt64


func (*Context) GetInt8

func (c *Context) GetInt8(key string, def ...int8) (int8, error)

GetInt8 GetInt8


func (*Context) GetKey

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

GetKey returns the value for the given key, ie: (value, true). If the value does not exists it returns (nil, false)

func (*Context) GetRunMode added in v0.1.0

func (c *Context) GetRunMode() string

GetRunMode return app run mode string

return dev or prod

func (*Context) GetSession added in v0.0.2

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

GetSession return interface

func (*Context) GetString

func (c *Context) GetString(key string, def ...string) string

GetString 按key返回字串值,可以设置default值

func (*Context) GetStrings

func (c *Context) GetStrings(key string, def ...[]string) []string

GetStrings GetStrings

func (*Context) GetUint16

func (c *Context) GetUint16(key string, def ...uint16) (uint16, error)

GetUint16 GetUint16


func (*Context) GetUint32

func (c *Context) GetUint32(key string, def ...uint32) (uint32, error)

GetUint32 GetUint32


func (*Context) GetUint64

func (c *Context) GetUint64(key string, def ...uint64) (uint64, error)

GetUint64 GetUint64


func (*Context) GetUint8

func (c *Context) GetUint8(key string, def ...uint8) (uint8, error)

GetUint8 GetUint8


func (*Context) HTML

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

HTML render html page

When inputting data, use the value of data, otherwise use c.Data

func (*Context) Handler added in v0.1.0

func (c *Context) Handler() HandlerFunc

Handler returns the main handler.

func (*Context) HandlerName

func (c *Context) HandlerName() string

HandlerName last handler name

func (*Context) Header added in v0.1.0

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

Header Header

func (*Context) Host added in v0.1.0

func (c *Context) Host() string

Host return request host string

func (*Context) IsAborted added in v0.1.0

func (c *Context) IsAborted() bool

IsAborted returns true if the current context was aborted.

func (*Context) IsAjax

func (c *Context) IsAjax() bool

IsAjax return is ajax request

func (*Context) IsProd added in v0.1.0

func (c *Context) IsProd() bool

IsProd return bool


func (*Context) IsWeChat added in v0.1.0

func (c *Context) IsWeChat() bool

IsWeChat return is WeChat user-agent

func (*Context) IsWebsocket added in v0.0.2

func (c *Context) IsWebsocket() bool

IsWebsocket return is websocket request

func (*Context) JSON

func (c *Context) JSON(data interface{})

JSON serializes the given struct as JSON into the response body

func (*Context) JSONP added in v0.1.9

func (c *Context) JSONP(callback string, data interface{})

JSONP write date by jsonp format

func (*Context) KeyBool added in v0.1.0

func (c *Context) KeyBool(key string) (b bool)

KeyBool returns the value associated with the key as a boolean.

func (*Context) KeyDuration added in v0.1.0

func (c *Context) KeyDuration(key string) (d time.Duration)

KeyDuration returns the value associated with the key as a duration.

func (*Context) KeyFloat64 added in v0.1.0

func (c *Context) KeyFloat64(key string) (f64 float64)

KeyFloat64 returns the value associated with the key as a float64.

func (*Context) KeyInt added in v0.1.0

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

KeyInt returns the value associated with the key as an integer.

func (*Context) KeyInt64 added in v0.1.0

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

KeyInt64 returns the value associated with the key as an integer.

func (*Context) KeyString added in v0.1.0

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

KeyString returns the value associated with the key as a string.

func (*Context) KeyStringMap added in v0.1.0

func (c *Context) KeyStringMap(key string) (sm map[string]interface{})

KeyStringMap returns the value associated with the key as a map of interfaces.

func (*Context) KeyStringMapString added in v0.1.0

func (c *Context) KeyStringMapString(key string) (sms map[string]string)

KeyStringMapString returns the value associated with the key as a map of strings.

func (*Context) KeyStringMapStringSlice added in v0.1.0

func (c *Context) KeyStringMapStringSlice(key string) (smss map[string][]string)

KeyStringMapStringSlice returns the value associated with the key as a map to a slice of strings.

func (*Context) KeyStringSlice added in v0.1.0

func (c *Context) KeyStringSlice(key string) (ss []string)

KeyStringSlice returns the value associated with the key as a slice of strings.

func (*Context) KeyTime added in v0.1.0

func (c *Context) KeyTime(key string) (t time.Time)

KeyTime returns the value associated with the key as time.

func (*Context) KeyUint added in v0.1.0

func (c *Context) KeyUint(key string) (ui uint)

KeyUint returns the value associated with the key as an unsigned integer.

func (*Context) KeyUint64 added in v0.1.0

func (c *Context) KeyUint64(key string) (ui64 uint64)

KeyUint64 returns the value associated with the key as an unsigned integer.

func (*Context) MustGet added in v0.1.0

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 should be used only inside middleware. It executes the pending handlers in the chain inside the calling handler. See example in GitHub.

func (*Context) Param

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

Param returns the value of the URL param. It is a shortcut for c.Params.ByName(key)

router.GET("/user/{id}, func(c *gin.Context) {
    // a GET request to /user/john
    id := c.Param("id") // id == "john"

func (*Context) ParamInt added in v0.1.9

func (c *Context) ParamInt(key string) (int, error)

ParamInt return the value of the URL param

func (*Context) ParamInt64 added in v0.1.9

func (c *Context) ParamInt64(key string) (int64, error)

ParamInt64 return the value of the URL param

func (*Context) Query

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

Query return query string

func (*Context) Redirect

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

Redirect http redirect like : 301 302 ...

func (*Context) Referer

func (c *Context) Referer() string

Referer return request referer

func (*Context) Render added in v0.1.0

func (c *Context) Render(statusCode int, name string, data interface{})

Render render html

func (*Context) SaveToFile

func (c *Context) SaveToFile(fromFile, toFile string) error

SaveToFile saves uploaded file to new path.

upload the file and save it on the server

func (*Context) ServerDataJSON added in v0.3.1

func (c *Context) ServerDataJSON(statusCode int, args ...interface{})

ServerDataJSON json format response


func (*Context) ServerHTML

func (c *Context) ServerHTML(statusCode int, name string, data ...interface{})

ServerHTML render html page

func (*Context) ServerHTMLString added in v0.4.0

func (c *Context) ServerHTMLString(code int, msg string)

ServerHTMLString write html string into response body

func (*Context) ServerJSON

func (c *Context) ServerJSON(code int, data interface{})

ServerJSON serializes the given struct as JSON into the response body.

func (*Context) ServerJSONP added in v0.1.9

func (c *Context) ServerJSONP(code int, callback string, data interface{})

ServerJSONP write data by jsonp format

func (*Context) ServerString

func (c *Context) ServerString(code int, msg string)

ServerString write string into the response body

func (*Context) ServerXML

func (c *Context) ServerXML(code int, data interface{})

ServerXML write data by xml format

func (*Context) ServerYAML added in v0.1.0

func (c *Context) ServerYAML(code int, data interface{})

ServerYAML serializes the given struct as YAML into the response body.

func (*Context) SessionBool added in v0.1.0

func (c *Context) SessionBool(key string) bool

SessionBool return bool

default false

func (*Context) SessionInt added in v0.1.0

func (c *Context) SessionInt(key string) int

SessionInt return int

default 0

func (*Context) SessionInt64 added in v0.1.0

func (c *Context) SessionInt64(key string) int64

SessionInt64 return int64

default 0

func (*Context) SessionString added in v0.1.0

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

SessionString return string

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

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

SetKey is used to store a new key/value pair exclusively for this context. It also lazy initializes c.Keys if it was not used previously.

func (*Context) SetSameSite added in v0.1.0

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

SetSameSite with cookie

func (*Context) SetSession added in v0.0.2

func (c *Context) SetSession(key string, v interface{})

SetSession set session

func (*Context) Status

func (c *Context) Status(code int)

Status sets the HTTP response code.

func (*Context) StopRun added in v0.0.2

func (c *Context) StopRun()

StopRun stop run

func (*Context) String

func (c *Context) String(msg string)

String write string into the response

func (*Context) UserAgent

func (c *Context) UserAgent() string

UserAgent get useragent

func (*Context) XML

func (c *Context) XML(data interface{})

XML response xml doc

func (*Context) YAML added in v0.1.0

func (c *Context) YAML(data interface{})

YAML serializes the given struct as YAML into the response body

type DataResponse added in v0.1.0

type DataResponse struct {
	Code int    `json:"code"`
	Msg  string `json:"msg"`
	Time int    `json:"time"`
	Body *Body  `json:"body"`

DataResponse data json response struct

type Engine

type Engine struct {
	AppName string
	RunMode string

	//views and static
	AutoRender bool
	HTMLRender render.HTMLRender

	FuncMap template.FuncMap
	Render  render.Render

	RedirectTrailingSlash  bool
	RedirectFixedPath      bool
	HandleMethodNotAllowed bool
	ForwardedByClientIP    bool
	AppEngine              bool
	UseRawPath             bool
	UnescapePathValues     bool
	MaxMultipartMemory     int64
	RemoveExtraSlash       bool
	// contains filtered or unexported fields

Engine is the framework's instance, it contains the muxer, middleware and configuration settings. Create an instance of Engine, by using New() or Default()

func Default

func Default() *Engine

Default returns an Engine instance with the Logger and Recovery middleware already attached.

func New

func New() *Engine

New returns a new blank Engine instance without any middleware attached. By default the configuration is: - RedirectTrailingSlash: true - RedirectFixedPath: false - HandleMethodNotAllowed: false - ForwardedByClientIP: true - UseRawPath: false - UnescapePathValues: true

func (*Engine) AddFuncMap

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

AddFuncMap add fn func to template func map

func (*Engine) HandleContext added in v0.1.0

func (engine *Engine) HandleContext(c *Context)

HandleContext re-enter a context that has been rewritten. This can be done by setting c.Request.URL.Path to your new target. Disclaimer: You can loop yourself to death with this, use wisely.

func (*Engine) NoMethod

func (engine *Engine) NoMethod(handlers ...HandlerFunc)

NoMethod sets the handlers called when... TODO.

func (*Engine) NoRoute

func (engine *Engine) NoRoute(handlers ...HandlerFunc)

NoRoute adds handlers for NoRoute. It return a 404 code by default.

func (*Engine) RouterMap

func (engine *Engine) RouterMap() (routes RoutesInfo)

RoutesMap get all router map

func (*Engine) Routes added in v0.1.0

func (engine *Engine) Routes() (routes RoutesInfo)

Routes returns a slice of registered routes, including some useful information, such as: the http method, path and the handler name.

func (*Engine) Run

func (engine *Engine) Run(args ...interface{}) (err error)

Run attaches the router to a http.Server and starts listening and serving HTTP requests. It is a shortcut for http.ListenAndServe(addr, router) Note: this method will block the calling goroutine indefinitely unless an error happens.

func (*Engine) RunFd added in v0.1.0

func (engine *Engine) RunFd(fd int) (err error)

RunFd attaches the router to a http.Server and starts listening and serving HTTP requests through the specified file descriptor. Note: this method will block the calling goroutine indefinitely unless an error happens.

func (*Engine) RunListener added in v0.1.0

func (engine *Engine) RunListener(listener net.Listener) (err error)

RunListener attaches the router to a http.Server and starts listening and serving HTTP requests through the specified net.Listener

func (*Engine) RunTLS

func (engine *Engine) RunTLS(certFile, keyFile string, args ...interface{}) (err error)

RunTLS attaches the router to a http.Server and starts listening and serving HTTPS (secure) requests. It is a shortcut for http.ListenAndServeTLS(addr, certFile, keyFile, router) Note: this method will block the calling goroutine indefinitely unless an error happens.

func (*Engine) RunUnix added in v0.1.0

func (engine *Engine) RunUnix(file string) (err error)

RunUnix attaches the router 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 (*Engine) SecureJsonPrefix added in v0.1.0

func (engine *Engine) SecureJsonPrefix(prefix string) *Engine

SecureJsonPrefix sets the secureJSONPrefix used in Context.SecureJSON.

func (*Engine) ServeHTTP

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

ServeHTTP conforms to the http.Handler interface.

func (*Engine) SetAppConfig

func (engine *Engine) SetAppConfig(app *AppConfig)

SetAppConfig 统一的配置入口


func (*Engine) SetDelims added in v0.1.0

func (engine *Engine) SetDelims(left, right string) *Engine

SetDelims sets template left and right delims and returns a Engine instance.

func (*Engine) SetFuncMap added in v0.1.0

func (engine *Engine) SetFuncMap(funcMap template.FuncMap)

SetFuncMap sets the FuncMap used for template.FuncMap.

func (*Engine) SetSessionOn added in v0.0.2

func (engine *Engine) SetSessionOn(on bool)

SetSessionOn SetSessionOn

func (*Engine) SetView

func (engine *Engine) SetView(path ...string)

SetView set views path 模板目录为 views 时,可不用设置此值

func (*Engine) Use added in v0.0.3

func (engine *Engine) Use(middleware ...HandlerFunc) IRoutes

Use attaches a global middleware to the router. ie. the middleware attached though 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 Error added in v0.1.0

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

Error represents a error's specification.

func (Error) Error added in v0.1.0

func (msg Error) Error() string

Error implements the error interface.

func (*Error) IsType added in v0.1.0

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

IsType judges one error.

func (*Error) JSON added in v0.1.0

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

JSON creates a properly formatted JSON

func (*Error) MarshalJSON added in v0.1.0

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

MarshalJSON implements the json.Marshaller interface.

func (*Error) SetMeta added in v0.1.0

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

SetMeta sets the error's meta data.

func (*Error) SetType added in v0.1.0

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

SetType sets the error's type.

type ErrorType added in v0.1.0

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 ExcludedExtensions added in v0.5.2

type ExcludedExtensions map[string]bool

Using map for better lookup performance

func NewExcludedExtensions added in v0.5.2

func NewExcludedExtensions(extensions []string) ExcludedExtensions

func (ExcludedExtensions) Contains added in v0.5.2

func (e ExcludedExtensions) Contains(target string) bool

type ExcludedPathesRegexs added in v0.5.2

type ExcludedPathesRegexs []*regexp.Regexp

func NewExcludedPathesRegexs added in v0.5.2

func NewExcludedPathesRegexs(regexs []string) ExcludedPathesRegexs

func (ExcludedPathesRegexs) Contains added in v0.5.2

func (e ExcludedPathesRegexs) Contains(requestURI string) bool

type ExcludedPaths added in v0.5.2

type ExcludedPaths []string

func NewExcludedPaths added in v0.5.2

func NewExcludedPaths(paths []string) ExcludedPaths

func (ExcludedPaths) Contains added in v0.5.2

func (e ExcludedPaths) Contains(requestURI string) bool

type H

type H map[string]interface{}

H map[string]interface{}

func (H) MarshalXML added in v0.1.0

func (h H) MarshalXML(e *xml.Encoder, start xml.StartElement) error

MarshalXML allows type H to be used with xml.Marshal.

type HandlerFunc

type HandlerFunc func(*Context)

HandlerFunc defines the handler used by gin middleware as return value.

func CustomRecovery added in v0.1.0

func CustomRecovery(handle RecoveryFunc) HandlerFunc

CustomRecovery returns a middleware that recovers from any panics and calls the provided handle func to handle it.

func CustomRecoveryWithWriter added in v0.1.0

func CustomRecoveryWithWriter(out io.Writer, handle RecoveryFunc) HandlerFunc

CustomRecoveryWithWriter returns a middleware for a given writer that recovers from any panics and calls the provided handle func to handle it.

func DataPager added in v0.1.0

func DataPager() HandlerFunc

DataPager middleware


func ErrorLogger added in v0.1.0

func ErrorLogger() HandlerFunc

ErrorLogger returns a handlerfunc for any error type.

func ErrorLoggerT added in v0.1.0

func ErrorLoggerT(typ ErrorType) HandlerFunc

ErrorLoggerT returns a handlerfunc for a given error type.

func Gzip added in v0.5.2

func Gzip(level int, options ...Option) HandlerFunc

Gzip middleware

1~9 Compress level

func Logger

func Logger() HandlerFunc

Logger 使用

func LoggerWithConfig added in v0.1.0

func LoggerWithConfig(conf LoggerConfig) HandlerFunc

LoggerWithConfig instance a Logger middleware with config.

func LoggerWithFormatter added in v0.1.0

func LoggerWithFormatter(f LogFormatter) HandlerFunc

LoggerWithFormatter instance a Logger middleware with the specified logy format function.

func LoggerWithWriter added in v0.1.0

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 added in v0.1.0

func RecoveryWithWriter(out io.Writer, recovery ...RecoveryFunc) HandlerFunc

RecoveryWithWriter returns a middleware for a given writer that recovers from any panics and writes a 500 if there was one.

func Session added in v0.0.2

func Session() HandlerFunc

Session session middleware

r := gow.Default()

func WrapF added in v0.1.0

func WrapF(f http.HandlerFunc) HandlerFunc

WrapF is a helper function for wrapping http.HandlerFunc and returns a Gin middleware.

func WrapH added in v0.1.0

func WrapH(h http.Handler) HandlerFunc

WrapH is a helper function for wrapping http.Handler and returns a Gin middleware.

type HandlersChain

type HandlersChain []HandlerFunc

HandlersChain defines a HandlerFunc array.

func (HandlersChain) Last

func (c HandlersChain) Last() HandlerFunc

Last returns the last handler in the chain. ie. the last handler is the main one.

type IRouter added in v0.1.0

type IRouter interface {
	Group(string, ...HandlerFunc) *RouterGroup

IRouter defines all router handle interface includes single and group router.

type IRoutes added in v0.1.0

type IRoutes interface {
	Use(...HandlerFunc) IRoutes

	Handle(string, string, ...HandlerFunc) IRoutes
	Any(string, ...HandlerFunc) IRoutes
	GET(string, ...HandlerFunc) IRoutes
	POST(string, ...HandlerFunc) IRoutes
	DELETE(string, ...HandlerFunc) IRoutes
	PATCH(string, ...HandlerFunc) IRoutes
	PUT(string, ...HandlerFunc) IRoutes
	OPTIONS(string, ...HandlerFunc) IRoutes
	HEAD(string, ...HandlerFunc) IRoutes

	StaticFile(string, string) IRoutes
	Static(string, string) IRoutes
	StaticFS(string, http.FileSystem) IRoutes

IRoutes defines all router handle interface.

type LogFormatter added in v0.1.0

type LogFormatter func(params LogFormatterParams) string

LogFormatter gives the signature of the formatter function passed to LoggerWithFormatter

type LogFormatterParams added in v0.1.0

type LogFormatterParams struct {
	Request *http.Request

	AppName string

	// 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 logy comes

func (*LogFormatterParams) IsOutputColor added in v0.1.0

func (p *LogFormatterParams) IsOutputColor() bool

IsOutputColor indicates whether can colors be outputted to the logy.

func (*LogFormatterParams) MethodColor added in v0.1.0

func (p *LogFormatterParams) MethodColor() string

MethodColor is the ANSI color for appropriately logging http method to a terminal.

func (*LogFormatterParams) ResetColor added in v0.1.0

func (p *LogFormatterParams) ResetColor() string

ResetColor resets all escape attributes.

func (*LogFormatterParams) StatusCodeColor added in v0.1.0

func (p *LogFormatterParams) StatusCodeColor() string

StatusCodeColor is the ANSI color for appropriately logging http status code to a terminal.

type LoggerConfig added in v0.1.0

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 Option added in v0.5.2

type Option func(*Options)

func WithDecompressFn added in v0.5.2

func WithDecompressFn(decompressFn func(c *Context)) Option

func WithExcludedExtensions added in v0.5.2

func WithExcludedExtensions(args []string) Option

func WithExcludedPaths added in v0.5.2

func WithExcludedPaths(args []string) Option

func WithExcludedPathsRegexs added in v0.5.2

func WithExcludedPathsRegexs(args []string) Option

type Options added in v0.5.2

type Options struct {
	ExcludedExtensions   ExcludedExtensions
	ExcludedPaths        ExcludedPaths
	ExcludedPathesRegexs ExcludedPathesRegexs
	DecompressFn         func(c *Context)

type Pager added in v0.1.0

type Pager struct {
	Page      int64 `json:"page"`
	Limit     int64 `json:"-"`
	Offset    int64 `json:"-"`
	Count     int64 `json:"count"`
	PageCount int64 `json:"page_count"`

Pager pager struct

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

func (ps Params) ByName(name string) (va string)

ByName returns the value of the first Param which key matches the given name. If no matching Param is found, an empty string is returned.

func (Params) Get

func (ps Params) Get(name string) (string, bool)

Get returns the value of the first Param which key matches the given name. If no matching Param is found, an empty string is returned.

type RecoveryFunc added in v0.1.0

type RecoveryFunc func(c *Context, err interface{})

RecoveryFunc defines the function passable to CustomRecovery.

type ResponseWriter

type ResponseWriter interface {

	// Status Returns the HTTP response status code of the current request.
	Status() int

	// Size Returns the number of bytes already written into the response http body.
	//  See Written()
	Size() int

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

	// Written Returns true if the response body was already written.
	Written() bool

	// WriteHeaderNow Forces to write the http header (status code + headers).

	// Pusher get the http.Pusher for server push
	Pusher() http.Pusher

ResponseWriter interface

type RouteInfo

type RouteInfo struct {
	Method      string
	Path        string
	Handler     string
	HandlerFunc HandlerFunc

RouteInfo represents a request route's specification which contains method and path and its handler.

type RouterGroup

type RouterGroup struct {
	Handlers HandlersChain
	// contains filtered or unexported fields

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

func (*RouterGroup) Any

func (group *RouterGroup) Any(relativePath string, handlers ...HandlerFunc) IRoutes

Any registers a route that matches all the HTTP methods. GET, POST, PUT, PATCH, HEAD, OPTIONS, DELETE, CONNECT, TRACE.

func (*RouterGroup) BasePath added in v0.1.0

func (group *RouterGroup) BasePath() string

BasePath returns the base path of router group. For example, if v := router.Group("/rest/n/v1/api"), v.BasePath() is "/rest/n/v1/api".

func (*RouterGroup) DELETE

func (group *RouterGroup) DELETE(relativePath string, handlers ...HandlerFunc) IRoutes

DELETE is a shortcut for router.Handle("DELETE", path, handle).

func (*RouterGroup) GET

func (group *RouterGroup) GET(relativePath string, handlers ...HandlerFunc) IRoutes

GET is a shortcut for router.Handle("GET", path, handle).

func (*RouterGroup) Group

func (group *RouterGroup) Group(relativePath string, handlers ...HandlerFunc) *RouterGroup

Group creates a new router group. You should add all the routes that have common middlewares or the same path prefix. For example, all the routes that use a common middleware for authorization could be grouped.

func (*RouterGroup) HEAD

func (group *RouterGroup) HEAD(relativePath string, handlers ...HandlerFunc) IRoutes

HEAD is a shortcut for router.Handle("HEAD", path, handle).

func (*RouterGroup) Handle

func (group *RouterGroup) Handle(httpMethod, relativePath string, handlers ...HandlerFunc) IRoutes

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. See the example code in GitHub.

For GET, POST, PUT, PATCH and DELETE requests the respective shortcut functions can be used.

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 (*RouterGroup) OPTIONS added in v0.1.0

func (group *RouterGroup) OPTIONS(relativePath string, handlers ...HandlerFunc) IRoutes

OPTIONS is a shortcut for router.Handle("OPTIONS", path, handle).

func (*RouterGroup) PATCH

func (group *RouterGroup) PATCH(relativePath string, handlers ...HandlerFunc) IRoutes

PATCH is a shortcut for router.Handle("PATCH", path, handle).

func (*RouterGroup) POST

func (group *RouterGroup) POST(relativePath string, handlers ...HandlerFunc) IRoutes

POST is a shortcut for router.Handle("POST", path, handle).

func (*RouterGroup) PUT

func (group *RouterGroup) PUT(relativePath string, handlers ...HandlerFunc) IRoutes

PUT is a shortcut for router.Handle("PUT", path, handle).

func (*RouterGroup) Static

func (group *RouterGroup) Static(relativePath, root string) IRoutes

Static serves files from the given file system root. Internally a http.FileServer is used, therefore http.NotFound is used instead of the Router's NotFound handler. To use the operating system's file system implementation, use :

router.Static("/static", "/var/www")

func (*RouterGroup) StaticFS

func (group *RouterGroup) StaticFS(relativePath string, fs http.FileSystem) IRoutes

StaticFS works just like `Static()` but a custom `http.FileSystem` can be used instead. Gin by default user: gin.Dir()

func (*RouterGroup) StaticFile

func (group *RouterGroup) StaticFile(relativePath, filepath string) IRoutes

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

func (*RouterGroup) Use

func (group *RouterGroup) Use(middleware ...HandlerFunc) IRoutes

Use adds middleware to the group, see example code in GitHub.

type RouterPath added in v0.1.3

type RouterPath []routerPathInfo

RouterPath defines a routerPathInfo array.

type RoutesInfo

type RoutesInfo []RouteInfo

RoutesInfo defines a RouteInfo array.


Path Synopsis
color 实现 sam 2020-09-29 logy 写日志文件的实现 sam 2020-10-09 logy logger 实现 report log to nsq server sam 2020-12-21 logy std 标准输出实现 sam 2020-09-29
color 实现 sam 2020-09-29 logy 写日志文件的实现 sam 2020-10-09 logy logger 实现 report log to nsq server sam 2020-12-21 logy std 标准输出实现 sam 2020-09-29
//init pu,err:=NewProducer("",4150) if err!=nil{ //error } b,_:=json.Marshal(obj) //发送 err = pu.Publish("topic",b) if err!=nil{ //error }
//init pu,err:=NewProducer("",4150) if err!=nil{ //error } b,_:=json.Marshal(obj) //发送 err = pu.Publish("topic",b) if err!=nil{ //error }
基础通讯业务实现 sam
基础通讯业务实现 sam
AES CBC PKCS5Padding加/解密 使用 hex.Encode 查看测试文件: aes_cbc_test.go
AES CBC PKCS5Padding加/解密 使用 hex.Encode 查看测试文件: aes_cbc_test.go

Jump to

Keyboard shortcuts

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