gow

package module
v1.3.7 Latest Latest
Warning

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

Go to latest
Published: Apr 19, 2024 License: MIT Imports: 36 Imported by: 12

README

gow

gow is a golang HTTP web framework

gow logo

借鉴和参考的项目:gin/beego/mux

项目地址

https://github.com/zituocn/gow

特性

  • ginContext 封装、路由分组和 middleware,可快速入门
  • 使用 regexp 实现路由完全匹配,支持大小写忽略
  • 统一的配置入口(ini格式),也可实现自己喜欢的配置方式
  • 支持服务器端渲染HTML页面,可自由扩展HTML模板函数
  • 可以自由选择封装在lib的sdk,如 mysql redis nsq rpc mem-cache oauth pay 等

1. 快速开始

# 创建一个hello的项目
mkdir hello

cd hello

# 使用go mod
go mod init

# 安装gow

go get github.com/zituocn/gow
1.1 创建 main.go
package main

import (
	"github.com/zituocn/gow"
)

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

	r.GET("/", func(c *gow.Context) {
		c.JSON(gow.H{
			"code": 0,
			"msg":  "success",
		})
	})

	//default :8080
	r.Run()
}

也可以写成这样

package main

import (
	"github.com/zituocn/gow"
)

func main() {
	r := gow.Default()
	r.GET("/", IndexHandler)
	//default :8080
	r.Run()
}

// IndexHandler response h
func IndexHandler(c *gow.Context) {
	h := map[string]interface{}{
		"project": "gow",
		"website": "https://github.com/zituocn/gow",
	}
	c.JSON(h)
}

自定义method,使用 r.Handle

package main

import "github.com/zituocn/gow"

func main() {
	r := gow.Default()
	r.Handle("GET,POST", "/", func(c *gow.Context) {
		c.String("index")
	})
}
1.2 运行
go run main.go

运行结果

Listening and serving HTTP on http://127.0.0.1:8080
1.3 访问

curl访问

curl -i http://127.0.0.1:8080

请求结果

HTTP/1.1 200 OK
Content-Type: application/json; charset=utf-8
Date: Tue, 08 Jun 2021 08:51:25 GMT
Content-Length: 67

{
  "project": "gow",
  "website": "https://github.com/zituocn/gow"
}

浏览器访问

在浏览器访问:http://127.0.0.1:8080

一些演示代码

可直接运行


2. 更多文档

3. 感谢

  • beego -> 参考了1.x中的HTML模板设计
  • gin -> 参考了 engineContext 设计
  • mux -> 参考了 路由设计
  • gorm -> 推荐使用 gorm
  • gini -> 用来操作 ini 格式的配置文件

4. License

MIT License. See the LICENSE file for details.

Documentation

Index

Constants

View Source
const (
	ContentJSON       = "application/json; charset=utf-8"
	ContentAsciiJSON  = "application/json"
	ContentHTML       = "text/html; charset=utf-8"
	ContentJavaScript = "application/javascript; charset=utf-8"
	ContentXML        = "application/xml; charset=utf-8"
	ContentPlain      = "text/plain; charset=utf-8"
	ContentYAML       = "application/x-yaml; charset=utf-8"
	ContentDownload   = "application/octet-stream; charset=utf-8"
)
View Source
const (
	DevMode  = "dev"
	ProdMode = "prod"
)
View Source
const (
	BestCompression    = gzip.BestCompression
	BestSpeed          = gzip.BestSpeed
	DefaultCompression = gzip.DefaultCompression
	NoCompression      = gzip.NoCompression
)

Variables

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

Functions

func BytesToString added in v1.0.3

func BytesToString(b []byte) string

BytesToString converts byte slice to string without a memory allocation.

func DefaultDecompressHandle

func DefaultDecompressHandle(c *Context)

DefaultDecompressHandle default handle

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 InitSession

func InitSession()

InitSession init gow session

before using session,please call this function first

func IsDebugging

func IsDebugging() bool

func StringToBytes added in v1.0.3

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

StringToBytes converts string to byte slice without a memory allocation.

Types

type AppConfig

type AppConfig struct {
	AppName       string `json:"app_name,omitempty" yaml:"app_name"`             // app name
	RunMode       string `json:"run_mode,omitempty" yaml:"run_mode"`             // app run mode
	HTTPAddr      string `json:"http_addr,omitempty" yaml:"http_addr"`           // http address
	AutoRender    bool   `json:"auto_render,omitempty" yaml:"auto_render"`       // if true load html template
	Views         string `json:"views,omitempty" yaml:"views"`                   // html template dir
	TemplateLeft  string `json:"template_left,omitempty" yaml:"template_left"`   // html template tag symbol
	TemplateRight string `json:"template_right,omitempty" yaml:"template_right"` // html template tag symbol
	SessionOn     bool   `json:"session_on,omitempty" yaml:"session_on"`         // if true open session
	GzipOn        bool   `json:"gzip_on,omitempty" yaml:"gzip_on"`               // if true:load gzip middleware
	IgnoreCase    bool   `json:"ignore_case" yaml:"ignore_case"`                 // if true ignore case on route
}

AppConfig unified configuration entry

func GetAppConfig

func GetAppConfig() *AppConfig

GetAppConfig return engine config

type Body

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

Body struct

type Context

type Context struct {
	Request *http.Request
	Writer  ResponseWriter

	Params Params

	Keys map[string]interface{}

	// Data html template render Data
	Data map[interface{}]interface{}

	Pager *Pager

	Errors errorMsgs
	// contains filtered or unexported fields
}

Context gow context

func (*Context) Abort

func (c *Context) Abort()

Abort abort handler

func (*Context) AbortWithError

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

AbortWithError abort and error

func (*Context) AbortWithStatus

func (c *Context) AbortWithStatus(code int)

AbortWithStatus abort and write status code

func (*Context) AsciiJSON added in v1.0.3

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

AsciiJSON response ascii JSON

func (*Context) Body

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

Body return request body -> []byte

func (*Context) ClientIP

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

ClientIP return client ip

return c.Request.RemoteAddr[0]

func (*Context) DataJSON

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

DataJSON response JSON format

c.DataJSON(1,"lost param")
c.DataJSON()

func (*Context) DecodeJSONBody

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

DecodeJSONBody Unmarshal request body to v

user:=&User{}
err:=c.DecodeJSONBody(&user)

func (*Context) DeleteSession

func (c *Context) DeleteSession(key string)

DeleteSession delete session key

func (*Context) DownLoadFile

func (c *Context) DownLoadFile(data []byte, filename string)

DownLoadFile download data to filename

c.DownLoadFile(data,"table.xlsx")

func (*Context) Download

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

Download download data

func (*Context) Error

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

Error set error to c.Errors

func (*Context) File

func (c *Context) File(filepath string)

File response file

support: text image bin ..

func (*Context) FileAttachment

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

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

Form return request.FormValue key

func (*Context) FullPath added in v1.0.3

func (c *Context) FullPath() string

FullPath return full path

func (*Context) GetBool

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

GetBool return bool and error

func (*Context) GetCookie

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

GetCookie get cookie

func (*Context) GetEngine added in v1.2.5

func (c *Context) GetEngine() *Engine

GetEngine returns *engine

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 return float64 and error

func (*Context) GetHeader

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

GetHeader returns value from request headers.

userAgent:=c.GetHeader("user-agent)

func (*Context) GetIP

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

GetIP return k8s Cluster ip

ip:=c.GetIP()

default 10.10.10.2

func (*Context) GetInt

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

GetInt return int and error

def default value

func (*Context) GetInt16

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

GetInt16 return int16 and error

-32768~32767

func (*Context) GetInt32

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

GetInt32 return int32 and error

-2147483648~2147483647

func (*Context) GetInt64

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

GetInt64 return int64 and error

-9223372036854775808~9223372036854775807

func (*Context) GetInt8

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

GetInt8 return int8 and error

-128~127

func (*Context) GetKey added in v1.0.6

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

GetKey return value from c.Keys

func (*Context) GetSession

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

GetSession return interface

func (*Context) GetString

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

GetString return string

def: default value

request url: /article?id=111 id:=c.GetString("id")

func (*Context) GetStrings

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

GetStrings return []string request url: /article?id=111&id=456 ids:=c.GetStrings("id")

func (*Context) GetUint16

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

GetUint16 return uint16 and error

0~65535

func (*Context) GetUint32

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

GetUint32 return uint32 and error

0~4294967295

func (*Context) GetUint64

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

GetUint64 return uint64 and error

0~18446744073709551615

func (*Context) GetUint8

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

GetUint8 return uint8 and error

0~255

func (*Context) HTML

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

HTML page render

c.HTML("index.html")
c.HTML("login.html",data)

func (*Context) Handler

func (c *Context) Handler() HandlerFunc

Handler returns the main handler.

func (*Context) HandlerName

func (c *Context) HandlerName() string

HandlerName last handler name

func (*Context) HandlerNames

func (c *Context) HandlerNames() []string

HandlerNames return []string

func (*Context) Header

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

Header set response header

c.Header("Server","gow")

func (*Context) Host

func (c *Context) Host() string

Host return request host

func (*Context) IsAborted

func (c *Context) IsAborted() bool

IsAborted return is abort

func (*Context) IsAjax

func (c *Context) IsAjax() bool

IsAjax return is ajax request

return X-Requested-With==XMLHttpRequest

func (*Context) IsProd

func (c *Context) IsProd() bool

IsProd return running in production mode

func (*Context) IsWeChat

func (c *Context) IsWeChat() bool

IsWeChat return is WeChat request

func (*Context) IsWebsocket

func (c *Context) IsWebsocket() bool

IsWebsocket return is websocket request

func (*Context) JSON

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

JSON response JSON data

user:=&User{}
c.JSON(user)

func (*Context) JSONP added in v0.1.2

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

JSONP write date by jsonp format

func (*Context) KeyBool added in v1.0.6

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

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

func (*Context) KeyDuration added in v1.0.6

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 v1.0.6

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

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

func (*Context) KeyInt added in v1.0.6

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

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

func (*Context) KeyInt64 added in v1.0.6

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

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

func (*Context) KeyString added in v1.0.6

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

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

func (*Context) KeyStringMap added in v1.0.6

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 v1.0.6

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 v1.0.6

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 v1.0.6

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 v1.0.6

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

KeyTime returns the value associated with the key as time.

func (*Context) KeyUint added in v1.0.6

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 v1.0.6

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 v1.0.6

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

MustGet return interface{}

func (*Context) Next

func (c *Context) Next()

Next c.Next method

call func: c.handler[i](c)

func (*Context) Param

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

Param return the value of the URL param.

request path: /article/{id}
c.Param(id)

func (*Context) ParamInt

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

ParamInt return the value of the URL param

request path: /article/{id}
c.ParamInt(id)

func (*Context) ParamInt64

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

ParamInt64 return the value of the URL param

request path: /article/{id}
c.ParamInt64(id)

func (*Context) PureJSON added in v1.0.3

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

PureJSON response pure JSON

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

c.Redirect(301,url)
c.Redirect(302,url)

func (*Context) Referer

func (c *Context) Referer() string

Referer return request referer

func (*Context) Render

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

Render html render

func (*Context) SaveToFile

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

SaveToFile upload the file and save it on the server.

c.SaveToFile("file","./upload/1.jpg")

func (*Context) SecureJSON added in v1.0.3

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

SecureJSON response secure JSON

func (*Context) ServerAsciiJSON added in v1.0.3

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

ServerAsciiJSON response ascii JSON

func (*Context) ServerDataJSON

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

ServerDataJSON response JSON format

statusCode httpStatusCode
like:  c.ServerDataJSON(401,1,"UnAuthorized")

func (*Context) ServerHTML

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

ServerHTML html page render

c.ServerHTML(200,"index.html")
c.ServerHTML(200,"admin/login.html")
c.ServerHTML(404,"error.html")

func (*Context) ServerJSON

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

ServerJSON response JSON data

c.ServerJSON(200,"success")
c.ServerJSON(404,structData)
c.ServerJSON(404,mapData)

func (*Context) ServerJSONP added in v0.1.2

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

ServerJSONP write data by jsonp format

user:=&User{}
c.ServerJSONP(200,"callback",user)

func (*Context) ServerPureJSON added in v1.0.3

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

ServerPureJSON response pure JSON

func (*Context) ServerSecureJSON added in v1.0.3

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

ServerSecureJSON response secure JSON

func (*Context) ServerString

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

ServerString response text message

c.ServerString(200,"success")
c.ServerString(404,"page not found")

func (*Context) ServerXML

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

ServerXML response xml data

func (*Context) ServerYAML

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

ServerYAML response yaml data

c.ServerYAML(200,yamlData)

func (*Context) SessionBool

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

SessionBool return bool

default false

func (*Context) SessionInt

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

SessionInt return int

default 0

func (*Context) SessionInt64

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

SessionInt64 return int64

default 0

func (*Context) SessionString

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 set cookie

c.SetCookie("name","zituocn",360,"/","",false,true)

func (*Context) SetKey added in v1.0.6

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

SetKey set k-v to c.Keys

func (*Context) SetSameSite added in v1.0.3

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

SetSameSite set http.SamSite

func (*Context) SetSession

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

SetSession set session

func (*Context) Status

func (c *Context) Status(code int)

Status write header statusCode

func (*Context) StopRun

func (c *Context) StopRun()

StopRun stop run handler

c.StopRun()

func (*Context) String

func (c *Context) String(msg string)

String response text message

func (*Context) UserAgent

func (c *Context) UserAgent() string

UserAgent return request user agent

func (*Context) XML

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

XML response xml data

user:=&User{}
c.XML(user)

func (*Context) YAML

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

YAML response yaml data

type DataResponse

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

DataResponse data struct

type Engine

type Engine struct {
	AppName string
	RunMode string

	AutoRender bool

	FuncMap template.FuncMap
	Render  render.Render

	RouterGroup
	HandleMethodNotAllowed bool
	MaxMultipartMemory     int64
	// contains filtered or unexported fields
}

Engine gow Engine

func Default

func Default() *Engine

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

r:=gow.Default()
r.Run()

func New

func New() *Engine

New returns a new blank Engine instance without any middleware attached.

gzipOn false
sessionOn false
ignoreCase true
ignoreTrailingSlash true
AutoRender false
RunMode = "dev"

func (*Engine) AddFuncMap added in v0.1.1

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

AddFuncMap add fn func to template func map

r.AddFuncMap("datetime",fn())

func (*Engine) Match

func (engine *Engine) Match(method, path string, match *matchValue) bool

Match routes from engine.trees

func (*Engine) NoRoute

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

NoRoute set 404 handler

r.NoRoute(error404Handler)

func (*Engine) PrintRouteMap added in v1.0.5

func (engine *Engine) PrintRouteMap()

PrintRouteMap print route map

func (*Engine) ResetRoute added in v1.2.5

func (engine *Engine) ResetRoute()

ResetRoute clear engine's route

func (*Engine) RouteMap added in v1.0.5

func (engine *Engine) RouteMap() []*RouteMapInfo

RouteMap return gow route

func (*Engine) Run

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

Run start http service default 127.0.0.1:8080

r.Run()
r.Run(8080)
r.Run(":8080)
r.Run("127.0.0.1:8080)

func (*Engine) RunFd

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

RunFd start fd service

func (*Engine) RunTLS

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

RunTLS start https service

func (*Engine) RunTLSLoadConfig added in v1.3.6

func (engine *Engine) RunTLSLoadConfig(cfg *tls.Config, args ...interface{}) (err error)

RunTLSLoadConfig use tls.Config{}

func (*Engine) RunUnix

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

RunUnix start unix:/ service

func (*Engine) ServeHTTP

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

ServeHTTP implements the http.Handler interface.

func (*Engine) SetAppConfig

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

SetAppConfig set engine config

gow.SetAppConfig(gow.GetAppConfig())
OR:
gow.SetAppConfig(func())

func (*Engine) SetGzipOn

func (engine *Engine) SetGzipOn(on bool)

SetGzipOn set gzip on

r.SetGzipOn(true)

func (*Engine) SetIgnoreCase

func (engine *Engine) SetIgnoreCase(ignore bool)

SetIgnoreCase set ignore case on the route

r.SetIgnoreCase(true)

func (*Engine) SetIgnoreTrailingSlash added in v1.0.8

func (engine *Engine) SetIgnoreTrailingSlash(ignore bool)

SetIgnoreTrailingSlash set ignore trailing slash one the route

r.SetIgnoreTrailingSlash(true)

func (*Engine) SetViews

func (engine *Engine) SetViews(path string)

SetViews set engine.viewPath = path

r.SetViews("views")

func (*Engine) Use

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

Use middleware

r.Use(Auth())

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(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

func (*Error) SetType

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

SetType set the error's type.

type ErrorType

type ErrorType uint64
const (
	ErrorTypePrivate ErrorType = 1 << 62
	ErrorTypeAny     ErrorType = 1<<64 - 1
)

type ExcludedExtensions

type ExcludedExtensions map[string]bool

ExcludedExtensions Using map for better lookup performance

func NewExcludedExtensions

func NewExcludedExtensions(extensions []string) ExcludedExtensions

func (ExcludedExtensions) Contains

func (e ExcludedExtensions) Contains(target string) bool

type ExcludedPathesRegexs

type ExcludedPathesRegexs []*regexp.Regexp

func NewExcludedPathesRegexs

func NewExcludedPathesRegexs(regexs []string) ExcludedPathesRegexs

func (ExcludedPathesRegexs) Contains

func (e ExcludedPathesRegexs) Contains(requestURI string) bool

type ExcludedPaths

type ExcludedPaths []string

func NewExcludedPaths

func NewExcludedPaths(paths []string) ExcludedPaths

func (ExcludedPaths) Contains

func (e ExcludedPaths) Contains(requestURI string) bool

type H

type H map[string]interface{}

H map[string]interface{}

type HandlerFunc

type HandlerFunc func(ctx *Context)

HandlerFunc gow handler

func(ctx *Context)

func CustomRecovery

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

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

func DataPager() HandlerFunc

DataPager middleware

r.Use(gow.DataPager())
like : /v1/user/page?page=1&limit=20

func Gzip

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

Gzip middleware

1~9 Compress level

func Logger

func Logger() HandlerFunc

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, 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

func Session() HandlerFunc

Session session middleware

r := gow.Default()
r.Use(gow.Session())

type HandlersChain

type HandlersChain []HandlerFunc

HandlersChain []HandlerFunc

func (HandlersChain) Last

func (c HandlersChain) Last() HandlerFunc

Last HandlerFunc

type IRouter

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

type IRoutes

type IRoutes interface {
	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 all router handler interface.

type LogFormatterParams

type LogFormatterParams struct {
	Request *http.Request

	//AppName
	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
}

func (*LogFormatterParams) IsOutputColor

func (p *LogFormatterParams) IsOutputColor() bool

IsOutputColor indicates whether can colors be outputted to the logx.

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 Option

type Option func(*Options)

func WithDecompressFn

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

func WithExcludedExtensions

func WithExcludedExtensions(args []string) Option

func WithExcludedPaths

func WithExcludedPaths(args []string) Option

func WithExcludedPathsRegexs

func WithExcludedPathsRegexs(args []string) Option

type Options

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

type Pager

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 URL parameter store key and 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

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

RecoveryFunc defines the function passable to CustomRecovery.

type ResponseWriter

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

	// 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).
	WriteHeaderNow()

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

ResponseWriter interface

type Route

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

Route store route info

func (*Route) Match

func (r *Route) Match(path string, match *matchValue) bool

Match implements interface

route match
search route path in r.matchers

type RouteMapInfo added in v1.0.5

type RouteMapInfo struct {
	Method   string
	Path     string
	Handler  string
	Handlers HandlersChain
}

RouteMapInfo route map info

type RouterGroup

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

RouterGroup is used internally to configure router.

func (*RouterGroup) Any

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

Any register all HTTP methods.

r.Aay("/",handler)
r.Aay("/article/{id}.html",handler)

func (*RouterGroup) DELETE

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

DELETE register DELETE handler

r.DELETE("/",handler)
r.DELETE("/article/{id}",handler)

func (*RouterGroup) GET

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

GET register GET handler

r.GET("/",handler)
r.GET("/article/{id}.html",handler)

func (*RouterGroup) Group

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

Group create a new route group.

v1:=r.Group("/v1")
THEN:
v1.GET("/user",...)

func (*RouterGroup) HEAD

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

HEAD register HEAD handler

r.HEAD("/",handler)
r.HEAD("/article/{id}",handler)

func (*RouterGroup) Handle

func (group *RouterGroup) Handle(method, path string, handlers ...HandlerFunc) IRoutes

Handle registers a new request handle and middleware with the given path and method

r.Handle("GET","/",handler)
r.Handle("GET,POST","/",handler)
r.Handle("GET,POST,PUT,DELETE","/article/{id}",handler)

func (*RouterGroup) OPTIONS

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

OPTIONS register OPTIONS handler

r.OPTIONS("/",handler)
r.OPTIONS("/article/{id}",handler)

func (*RouterGroup) PATCH

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

PATCH register PATCH handler

func (*RouterGroup) POST

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

POST register POST handler

r.POST("/",handler)
r.POST("/article/{id}.html",handler)

func (*RouterGroup) PUT

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

PUT register PUT handler

func (*RouterGroup) Static

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

Static handler static dir

r.Static("/static","static")

func (*RouterGroup) StaticFS

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

StaticFS r.StaticFS(path,fs)

func (*RouterGroup) StaticFile

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

StaticFile static file

r.StaticFile("/favicon.png","/static/img/favicon.png")

func (*RouterGroup) Use

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

Use add middleware to the group

func Demo() gow.HandlerFunc{
	return func(c *Context) {
		TODO:
		c.Next()
	}
}

r.Use(Demo()) OR: r.Use(Demo(),Demo2())

Jump to

Keyboard shortcuts

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