gwf

package module
v0.0.0-...-4e8bdb6 Latest Latest
Warning

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

Go to latest
Published: Jan 13, 2020 License: MIT Imports: 32 Imported by: 0

README

gwf

golang web framework

Documentation

Overview

gwf 是一个精简的mvc框架 1、支持静态路由和动态路由,其中动态路由包含反射自某一controller中的所有action 2、支持pulic目录下静态文件路由 3、支持middleware 4、支持context 5、支持平滑重启 6、支持template快速开发 7、集成健康探针与pprof监控

Index

Constants

View Source
const (
	// NoWritten 默认未写入响应时的size初始值
	NoWritten = -1
	// DefaultStatus 默认响应状态码200
	DefaultStatus = http.StatusOK
)
View Source
const AppDefaultRouterGroupName = "app"
View Source
const (
	// 平滑重启时的环境变量
	GRACE_ENV = "GWF_GRACE=true"
)
View Source
const INIT_METHOD_NAME = "Init"

Variables

This section is empty.

Functions

func EnableDebug

func EnableDebug()

EnableDebug开启debug模式,debug模式下,可以随便修改layout/tmpl文件定义。 生产环境下,为了性能,请一定不要调用此函数

func LoadMenuList

func LoadMenuList(layoutName string, jsonData []byte) menu.MenuList

LoadMenuList为名称为layoutName的layout加载目录,第二个参数传入nil,将找layout文件同名的.menu文件加载 .menu文件格式为json格式

func LoadTemplate

func LoadTemplate()

func NewResponseWriter

func NewResponseWriter(w http.ResponseWriter, respStatusHandler ResponseStatusHandler, respHeaderHandler ResponseHeaderHandler,
	respBodyHandler ResponseBodyHandler) *responseWriter

NewResponseWriter 初始化

func ReloadTemplate

func ReloadTemplate()

ReloadTemplate用来重新加载模板,重新加载后,缓存的模板会失效

func Render

func Render(w http.ResponseWriter, code int, layoutName, tmplName string, data map[string]interface{})

func RenderDebug

func RenderDebug(w http.ResponseWriter, code int, layoutName, tmplName string, data map[string]interface{})

func RunGrace

func RunGrace(srv *http.Server, timeout time.Duration) error

RunGrace方法平滑的运行某个http.Server,平滑重启时,需要停止的进程在timeout后退出

func SaveUploadedFile

func SaveUploadedFile(file *multipart.FileHeader, dst string) error

SaveUploadedFile用于存储上传文件到文件路径dst

func SetDelimiters

func SetDelimiters(left, right string)

SetDelimiters用来自定义定界符, 默认定界符是SetDelimiters("{{", "}}")

func SetFuncMap

func SetFuncMap(funcMap map[string]interface{})

SetFuncMap设定模板中的自定义函数,此方法要在LoadAdminTemplate之前调用才有效 比如自定义一个时间格式化函数:

 func formatAsDate(t time.Time) string {
		year, month, day := t.Date()
		return fmt.Sprintf("%d%02d/%02d", year, month, day)
	}

可以使用如下代码设定一个可以在模板文件中调用的formatAsDate函数:

 template.SetFuncMap(map[string]interface{}{
		"formatAsDate": formatAsDate,
	})

在模板中可以使用自定义函数:

Date: {{.now | formatAsDate}}

func Stack

func Stack(skip int) []byte

Stack返回格式化的调用栈,skip参数用来设置忽略调用栈中的栈帧数量

func StackNoNewLine

func StackNoNewLine(skip int) string

StackNoNewLine返回当前调用栈的信息,不含有换行符。 日志中输出调用栈信息可以用此方法,用于某些日志采集程序不支持多行的情况

Types

type AdminController

type AdminController struct {
	*log.Logger
	// contains filtered or unexported fields
}

AdminController 后台专用controller

func (*AdminController) GetApplication

func (c *AdminController) GetApplication() *Application

GetApplication 获取app数据

func (*AdminController) Init

func (c *AdminController) Init()

Init AdminController 初始化

type Application

type Application struct {

	// Logger 日志
	Logger *log.Logger

	// RouterGroup app级别的RouterGroup
	*RouterGroup
	// contains filtered or unexported fields
}

Application 是应用的抽象

func New

func New() *Application

初始化

func (*Application) AddRouterGroup

func (app *Application) AddRouterGroup(rg *RouterGroup)

AddRouterGroup 添加额外的路由组,app初始化时会默认添加app级别路由组

func (*Application) EnableStaticFileServer

func (app *Application) EnableStaticFileServer()

EnableStaticFileServer 开启静态文件服务器,可以基于public目录提供静态文件服务

func (*Application) ServeHTTP

func (app *Application) ServeHTTP(w http.ResponseWriter, r *http.Request)

ServeHttp实现了http.Handler接口

func (*Application) SetMaxMultipartMemory

func (app *Application) SetMaxMultipartMemory(n int64)

SetMaxMultipartMemory 设置客户端上传数据的最大内存占用量

func (*Application) SetNotFound

func (app *Application) SetNotFound(handler HandlerFunc)

SetNotFound 设置404的处理器

func (*Application) SetRestartTimeout

func (app *Application) SetRestartTimeout(timeout time.Duration)

SetRestartTimeout 设置平滑重启超时时间

func (*Application) Start

func (app *Application) Start()

Start启动App, 此方法会监听配置的端口,提供服务 此方法会阻塞主协程 路由设置一定要在此方法之前设定,否则不生效

type Config

type Config struct {
	// app名称
	AppName string `yaml:"appName"`
	// listen addr
	Listen string `yaml:"listen"`
	// app 版本
	AppVersion string `yaml:"appVersion"`
}

type Context

type Context struct {
	Request *http.Request
	Writer  *responseWriter

	//url参数列表
	URLParameters url.Values

	//url和POST/PUT/PATCH参数列表,url参数会被POST/PUT/PATCH的同名参数覆盖
	URLFormParameters url.Values

	//POST/PUT/PATCH参数列表
	FormParameters url.Values

	// Keys key/value对,请求唯一,可以将参数贯串整个请求上下文
	Keys map[string]interface{}
	// contains filtered or unexported fields
}

Context 是对某次请求上下文的抽象

func (*Context) Abort

func (c *Context) Abort()

Abort 终止待执行的hanlers,不会终止正在执行中的handler 比如认证middleware执行失败时,不需要再执行之后的handlers 调用Abort来终止剩下的handlers的调用

func (*Context) AbortWithStatus

func (c *Context) AbortWithStatus(code int)

AbortWithStatus 写入status code并终止后续的handlers调用

func (*Context) AbortWithStatusJson

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

AbortWithStatusJson 响应为json格式,并终止后续的handlers调用

func (*Context) AbortWithStatusString

func (c *Context) AbortWithStatusString(code int, data string)

AbortWithStatusString 响应为string格式,并终止后续的handlers调用

func (*Context) Bind

func (c *Context) Bind(dst interface{}, src url.Values) error

*********参数绑定到struct相关函数 begin********* Bind 用于参数绑定,dst必须是struct的指针类型

func (*Context) BindForm

func (c *Context) BindForm(dst interface{}) error

BindForm 将POST/PUT/PATCH参数绑定到dst

func (*Context) BindMultipartForm

func (c *Context) BindMultipartForm(dst interface{}) error

BindMultipartForm将POST/PUT/PATCH参数绑定到dst 与BindForm的区别是,此方法将绑定form的enctype="multipart/form-data"的参数 如果要获得上传的文件,请使用FormFile方法

func (*Context) BindParam

func (c *Context) BindParam(dst interface{}) error

BindParam 将url参数和POST/PUT/PATCH参数绑定到dst

func (*Context) BindQuery

func (c *Context) BindQuery(dst interface{}) error

BindQuery 将url参数绑定到dst

func (*Context) Bytes

func (c *Context) Bytes(statusCode int, bytes []byte)

Bytes 用于输出[]byte类型数据,并设置HTTP状态码为statusCode 调用方需要自己使用return控制程序流程

func (*Context) FormBool

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

func (*Context) FormBoolDefault

func (c *Context) FormBoolDefault(key string, defaultV bool) bool

func (*Context) FormFile

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

func (*Context) FormFloa32Default

func (c *Context) FormFloa32Default(key string, defaultV float32) float32

func (*Context) FormFloa64Default

func (c *Context) FormFloa64Default(key string, defaultV float64) float64

func (*Context) FormFloat32

func (c *Context) FormFloat32(key string) float32

func (*Context) FormFloat64

func (c *Context) FormFloat64(key string) float64

func (*Context) FormInt

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

func (*Context) FormInt16

func (c *Context) FormInt16(key string) int16

func (*Context) FormInt16Default

func (c *Context) FormInt16Default(key string, defaultV int16) int16

func (*Context) FormInt32

func (c *Context) FormInt32(key string) int32

func (*Context) FormInt32Default

func (c *Context) FormInt32Default(key string, defaultV int32) int32

func (*Context) FormInt64

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

func (*Context) FormInt64Default

func (c *Context) FormInt64Default(key string, defaultV int64) int64

func (*Context) FormInt8

func (c *Context) FormInt8(key string) int8

func (*Context) FormInt8Default

func (c *Context) FormInt8Default(key string, defaultV int8) int8

func (*Context) FormIntDefault

func (c *Context) FormIntDefault(key string, defaultV int) int

func (*Context) FormString

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

func (*Context) FormStringDefault

func (c *Context) FormStringDefault(key string, defaultV string) string

func (*Context) FormStringSlice

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

func (*Context) FormUint

func (c *Context) FormUint(key string) uint

func (*Context) FormUint16

func (c *Context) FormUint16(key string) uint16

func (*Context) FormUint16Default

func (c *Context) FormUint16Default(key string, defaultV uint16) uint16

func (*Context) FormUint32

func (c *Context) FormUint32(key string) uint32

func (*Context) FormUint32Default

func (c *Context) FormUint32Default(key string, defaultV uint32) uint32

func (*Context) FormUint64

func (c *Context) FormUint64(key string) uint64

func (*Context) FormUint64Default

func (c *Context) FormUint64Default(key string, defaultV uint64) uint64

func (*Context) FormUint8

func (c *Context) FormUint8(key string) uint8

func (*Context) FormUint8Default

func (c *Context) FormUint8Default(key string, defaultV uint8) uint8

func (*Context) FormUintDefault

func (c *Context) FormUintDefault(key string, defaultV uint) uint

func (*Context) Get

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

Get 取出当前Context中自定义key的value,存在时exists为true

func (*Context) GetReqeustBody

func (c *Context) GetReqeustBody() ([]byte, error)

func (*Context) Header

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

*********输出相关函数 begin********* Header 用于输出http协议header

func (*Context) IsAborted

func (c *Context) IsAborted() bool

IsAborted 当前Context终止返回true

func (*Context) Json

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

Json 将data输出,data一般是一个struct 调用方需要自己使用return控制程序流程

func (*Context) MultipartFormParameters

func (c *Context) MultipartFormParameters() (url.Values, error)

MultipartFormParameters返回form的enctype="multipart/form-data"的POST/PUT/PATCH参数

func (*Context) Next

func (c *Context) Next()

Next 循环执行hanlers链中的handler

func (*Context) ParamBool

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

func (*Context) ParamBoolDefault

func (c *Context) ParamBoolDefault(key string, defaultV bool) bool

func (*Context) ParamFloat32

func (c *Context) ParamFloat32(key string) float32

func (*Context) ParamFloat32Default

func (c *Context) ParamFloat32Default(key string, defaultV float32) float32

func (*Context) ParamFloat64

func (c *Context) ParamFloat64(key string) float64

func (*Context) ParamFloat64Default

func (c *Context) ParamFloat64Default(key string, defaultV float64) float64

func (*Context) ParamInt

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

func (*Context) ParamInt16

func (c *Context) ParamInt16(key string) int16

func (*Context) ParamInt16Default

func (c *Context) ParamInt16Default(key string, defaultV int16) int16

func (*Context) ParamInt32

func (c *Context) ParamInt32(key string) int32

func (*Context) ParamInt32Default

func (c *Context) ParamInt32Default(key string, defaultV int32) int32

func (*Context) ParamInt64

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

func (*Context) ParamInt64Default

func (c *Context) ParamInt64Default(key string, defaultV int64) int64

func (*Context) ParamInt8

func (c *Context) ParamInt8(key string) int8

func (*Context) ParamInt8Default

func (c *Context) ParamInt8Default(key string, defaultV int8) int8

func (*Context) ParamIntDefault

func (c *Context) ParamIntDefault(key string, defaultV int) int

func (*Context) ParamString

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

ParamXXX和ParamXXXDefault函数可以取得url参数和POST、PUT、PATCH上传的参数 如果某个参数在url参数和POST、PUT、PATCH上传参数中都有,将取得POST、PUT、PATCH参数 如果一定要取得url参数,请使用QueryXXX和QueryXXXDefault方法 如果没有为key的参数名,或者值为空字符串,ParamXXX返回XXX类型的默认零值 ParamXXXDefault返回传入的defaultV

func (*Context) ParamStringDefault

func (c *Context) ParamStringDefault(key string, defaultV string) string

func (*Context) ParamStringSlice

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

func (*Context) ParamUint

func (c *Context) ParamUint(key string) uint

func (*Context) ParamUint16

func (c *Context) ParamUint16(key string) uint16

func (*Context) ParamUint16Default

func (c *Context) ParamUint16Default(key string, defaultV uint16) uint16

func (*Context) ParamUint32

func (c *Context) ParamUint32(key string) uint32

func (*Context) ParamUint32Default

func (c *Context) ParamUint32Default(key string, defaultV uint32) uint32

func (*Context) ParamUint64

func (c *Context) ParamUint64(key string) uint64

func (*Context) ParamUint64Default

func (c *Context) ParamUint64Default(key string, defaultV uint64) uint64

func (*Context) ParamUint8

func (c *Context) ParamUint8(key string) uint8

func (*Context) ParamUint8Default

func (c *Context) ParamUint8Default(key string, defaultV uint8) uint8

func (*Context) ParamUintDefault

func (c *Context) ParamUintDefault(key string, defaultV uint) uint

func (*Context) QueryBool

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

func (*Context) QueryBoolDefault

func (c *Context) QueryBoolDefault(key string, defaultV bool) bool

func (*Context) QueryFloa32Default

func (c *Context) QueryFloa32Default(key string, defaultV float32) float32

func (*Context) QueryFloa64Default

func (c *Context) QueryFloa64Default(key string, defaultV float64) float64

func (*Context) QueryFloat32

func (c *Context) QueryFloat32(key string) float32

func (*Context) QueryFloat64

func (c *Context) QueryFloat64(key string) float64

func (*Context) QueryInt

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

func (*Context) QueryInt16

func (c *Context) QueryInt16(key string) int16

func (*Context) QueryInt16Default

func (c *Context) QueryInt16Default(key string, defaultV int16) int16

func (*Context) QueryInt32

func (c *Context) QueryInt32(key string) int32

func (*Context) QueryInt32Default

func (c *Context) QueryInt32Default(key string, defaultV int32) int32

func (*Context) QueryInt64

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

func (*Context) QueryInt64Default

func (c *Context) QueryInt64Default(key string, defaultV int64) int64

func (*Context) QueryInt8

func (c *Context) QueryInt8(key string) int8

func (*Context) QueryInt8Default

func (c *Context) QueryInt8Default(key string, defaultV int8) int8

func (*Context) QueryIntDefault

func (c *Context) QueryIntDefault(key string, defaultV int) int

func (*Context) QueryString

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

func (*Context) QueryStringDefault

func (c *Context) QueryStringDefault(key string, defaultV string) string

func (*Context) QueryStringSlice

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

func (*Context) QueryUint

func (c *Context) QueryUint(key string) uint

func (*Context) QueryUint16

func (c *Context) QueryUint16(key string) uint16

func (*Context) QueryUint16Default

func (c *Context) QueryUint16Default(key string, defaultV uint16) uint16

func (*Context) QueryUint32

func (c *Context) QueryUint32(key string) uint32

func (*Context) QueryUint32Default

func (c *Context) QueryUint32Default(key string, defaultV uint32) uint32

func (*Context) QueryUint64

func (c *Context) QueryUint64(key string) uint64

func (*Context) QueryUint64Default

func (c *Context) QueryUint64Default(key string, defaultV uint64) uint64

func (*Context) QueryUint8

func (c *Context) QueryUint8(key string) uint8

func (*Context) QueryUint8Default

func (c *Context) QueryUint8Default(key string, defaultV uint8) uint8

func (*Context) QueryUintDefault

func (c *Context) QueryUintDefault(key string, defaultV uint) uint

func (*Context) Redirect301

func (c *Context) Redirect301(location string)

func (*Context) Redirect302

func (c *Context) Redirect302(location string)

func (*Context) Render

func (c *Context) Render(code int, layoutName, tmplName string, data map[string]interface{})

Render 将context数据注入到模板中渲染

func (*Context) RenderAdmin

func (c *Context) RenderAdmin(layoutName, tmplName string, data map[string]interface{})

RenderAdmin 渲染后台模板

func (*Context) RenderAdminDefaultLayout

func (c *Context) RenderAdminDefaultLayout(tmplName string, data map[string]interface{})

RenderAdminDefaultLayout 渲染后台默认模板

func (*Context) Set

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

Set 在当前Context中保存用户自定义key/value

func (*Context) Status

func (c *Context) Status(code int)

Status 写入响应code

func (*Context) String

func (c *Context) String(statusCode int, data string)

String 用于输出string类型数据,并设置HTTP状态码为statusCode 调用方需要自己使用return控制程序流程

type Controller

type Controller struct {
	*log.Logger
	// contains filtered or unexported fields
}

Controller,api的controller使用这个

func (*Controller) GetApplication

func (c *Controller) GetApplication() *Application

GetApplication 获取app数据

func (*Controller) Init

func (c *Controller) Init()

Init Controller 初始化

type Error

type Error struct {
	Err   interface{}
	Type  ErrorType
	Stack string
}

type ErrorType

type ErrorType uint8
const (
	// ErrorTypeInternal 内部错误类型
	ErrorTypeInternal ErrorType = iota
)

type Grace

type Grace interface {
	Run(*http.Server) error
}

Grace接口实现平滑重启

type HandlerFunc

type HandlerFunc func(c *Context)

HandlerFunc 自定义handler类型

var DefaultInternalServerErrorHandler HandlerFunc = func(c *Context) {
	if GetConfig().IsOnlineEnvironment() || GetConfig().IsPreEnvironment() {
		c.Bytes(http.StatusInternalServerError, []byte("服务器内部错误"))
	} else {
		body := fmt.Sprintf("%s \n%s", c.errInternal.Err, c.errInternal.Stack)
		c.String(http.StatusInternalServerError, body)
	}
}

DefaultInternalServerErrorHandler 默认500handler

var DefaultNotFoundHandler HandlerFunc = func(c *Context) {
	c.Bytes(http.StatusNotFound, []byte("资源不存在"))
}

DefaultNotFoundHandler 默认404handler

func Recovery

func Recovery() HandlerFunc

type HandlersChain

type HandlersChain []HandlerFunc

HandlersChain handler链

type IController

type IController interface {
	Init()
	GetApplication() *Application
}

IController Controller 接口

type IRoutes

type IRoutes interface {
	GET(path string, handlers ...HandlerFunc)
	POST(path string, handlers ...HandlerFunc)
	PUT(path string, handlers ...HandlerFunc)
	PATCH(path string, handlers ...HandlerFunc)
	HEAD(path string, handlers ...HandlerFunc)
	DELETE(path string, handlers ...HandlerFunc)
	OPTIONS(path string, handlers ...HandlerFunc)
}

IRoutes Router接口

type Item

type Item struct {
	Name     string `json:"name"`
	Url      string `json:"url"`
	IsActive bool   `json:"is_active"`
}
type Menu struct {
	Name     string  `json:"name"`
	IsActive bool    `json:"is_active"`
	ItemList []*Item `json:"item_list"`
}
type MenuList []*Menu
func (ml MenuList) SetActive(url string)
func (ml MenuList) SetUrlPrefix(prefix string)

type ResponseBodyHandler

type ResponseBodyHandler func([]byte) []byte

ResponseBodyHandler 响应body的装饰器handler

type ResponseHeaderHandler

type ResponseHeaderHandler func(http.Header)

ResponseHeaderHandler 响应头的装饰器handler

type ResponseStatusHandler

type ResponseStatusHandler func(int) int

ResponseStatusHandler 响应状态的装饰器handler

type RouteInfo

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

RouteInfo 路由详细信息 handlers 包含RouterGroup中Handlers和局部middleware(如果有的话)以及主逻辑handler

type RouterGroup

type RouterGroup struct {

	// Handlers 当前路由组下所有路由公共Handlers(middleware)
	Handlers HandlersChain
	// Routes 路由Map
	Routes map[string]map[string]RouteInfo
	// contains filtered or unexported fields
}

RouterGroup 路由组

func NewRouterGroup

func NewRouterGroup(app *Application, name string) *RouterGroup

NewRouterGroup 初始化 默认自动添加Recovery中间件

func (*RouterGroup) AddMiddleware

func (rg *RouterGroup) AddMiddleware(handlers ...HandlerFunc)

AddMiddleware 添加中间件,整个路由组中的路由共享中间件

func (*RouterGroup) DELETE

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

DELETE method delete

func (*RouterGroup) EnableAppNameAsPathPrefix

func (rg *RouterGroup) EnableAppNameAsPathPrefix()

EnableAppNameAsPathPrefix 开启appname作为path前缀

func (*RouterGroup) EnableTemplate

func (rg *RouterGroup) EnableTemplate()

EnableDebugTemplate打开模板功能 在开发环境下是可以调试模板的

func (*RouterGroup) GET

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

GET method get

func (*RouterGroup) HEAD

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

HEAD method head

func (*RouterGroup) OPTIONS

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

OPTIONS method options

func (*RouterGroup) PATCH

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

PATCH method patch

func (*RouterGroup) POST

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

POST method post

func (*RouterGroup) PUT

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

PUT method put

func (*RouterGroup) RegisterDynamicRouter

func (rg *RouterGroup) RegisterDynamicRouter(controller interface{}, options ...interface{})

什么是动态路由?动态路由是不通过Routable中的方法注册的路由 动态路由需要在InitRouter中新增如下代码:

app.RegisterDynamicRouter(&api.MobileAskController{})

也可以注册到其他的RouterGroup中 注意:动态路由会注册GET/POST两种方式的请求 为了更好的满足RESTFUL定义,请使用静态路由,使用IRoutes中的方法注册路由 options参数有以下调用方式:

// 注册到指定的方法中
RegisterDynamicRouter(&api.MobileAskController{}, []string{"get", "post"})
// 只设定path的前缀,前缀必须以/打头
RegisterDynamicRouter(&api.MobileAskController{}, []string{}, "/prefix")

Jump to

Keyboard shortcuts

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