wego

package module
v1.2.2 Latest Latest
Warning

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

Go to latest
Published: Apr 13, 2023 License: Apache-2.0 Imports: 35 Imported by: 0

README

简介

wego是一个Go语言编写的高性能的Web框架,可以用来快速开发RESTful服务以及后端服务等各种应用。 wego框架包括:路由模块、ORM模块、websocket模块、session模块等模块。具体特征如下:

  1. 基于Radix树开发的路由模块,路由查询性能高。
  2. 支持混合路由,固定路由、参数路由、前缀路由可以混合,不冲突。
  3. 支持路由组,可以为不同层次的路由设置过滤器中间件。
  4. 为路由参数、Query参数、Form参数的访问提供率方便易于使用的API,并可以将参数映射到Struct。
  5. 为JSON、XML和HTML渲染提供了易于使用的API。
  6. 支持过滤器中间件,方便您对Web框架进行扩展。
  7. 支持BeforeRoute、BeforeExec、AfterExec拦截器,方便您进行身份验证、日志输出。
  8. 支持Crash处理机制,wego可以recover一个HTTP请求中的panic,这样可确保您的服务器始终可用。
  9. 内置Session模块,您可以选择cookie、redis、memcache、memory缓存引擎存储Session数据。
  10. 内置ORM模块,使用方便,功能强大。
  11. 内置websocket模块,采用更加经济的内存分配机制,使得每台服务器可接入更多的客户端。
  12. 内置配置模块,方便对应用的参数进行管理。
  13. 内置高性能LOG模块,支持日志分级,支持按照天轮换日志文件。
  14. 采用缓存来管理HTML的Template,既方便输出Html页面,又可以使用缓存提升系统性能。

安装

go get github.com/haming123/wego

使用文档

请点击:详细文档

简单http server

创建一个main.go文件,代码如下:

package main
import (
	"github.com/haming123/wego"
	log "github.com/haming123/wego/dlog"
)
func main() {
	web, err := wego.NewWeb()
	if err != nil{
		log.Error(err)
		return
	}

	web.GET("/hello", func(c *wego.WebContext) {
		c.WriteText(200, "world")
	})

	err = web.Run(":8080")
	if err != nil {
		log.Error(err)
	}
}

然后运行它,打开浏览器,输入http://localhost:8080/hello, 就可以看到如下内容:

world

项目结构

wego框没有对项目结构做出限制,这里给出一个MVC框架项目的建议结构:

demo
├── app             
│   └── router.go       - 路由配置文件
│   └── templfun.go     - 模板函数文件
├── controllers         - 控制器目录,必要的时候可以继续划分子目录
│   └── controller_xxx.go
├── models              - 模型目录
│   └── model_xxx.go
├── logs                - 日志文件目录,主要保存项目运行过程中产生的日志
│   └── applog_20211203.log
├── static              - 静态资源目录
│   ├── css
│   ├── img
│   └── js
├── utils               - 公共代码目录
│   └── util_xxx.go
├── views               - 视图模板目录
│   └── html_xxx.html
├── app.conf            - 应用配置文件
└── main.go             - 入口文件

注册参数路由

func main() {
	web, err := wego.NewWeb()
	if err != nil{
		log.Error(err)
		return
	}

	web.PATH("/user/:id", func(c *wego.WebContext) {
		c.WriteTextF(200, "param id=%s", c.RouteParam.GetString("id").Value)
	})

	err = web.Run(":8080")
	if err != nil {
		log.Error(err)
	}
}

注册模糊匹配路由

func main() {
	web, err := wego.NewWeb()
	if err != nil{
		log.Error(err)
		return
	}

	web.PATH("/files/*name", func(c *wego.WebContext) {
		c.WriteTextF(200, "param name=%s", c.RouteParam.GetString("name").Value)
	})

	err = web.Run(":8080")
	if err != nil {
		log.Error(err)
	}
}

注册RESTful路由

func main() {
	web, err := wego.NewWeb()
	if err != nil{
		log.Error(err)
		return
	}

	web.GET("/users/:id", func(c *wego.WebContext) {
		//查询一个用户
	})
	web.POST("/users/:id", func(c *wego.WebContext) {
		//创建一个用户
	})
	web.PUT("/users/:id", func(c *wego.WebContext) {
		//更新用户信息
	})
	web.PATCH("/users/:id", func(c *wego.WebContext) {
		//更新用户的部分信息
	})
	web.DELETE("/users/:id", func(c *wego.WebContext) {
		//删除用户
	})

	err = web.Run(":8080")
	if err != nil {
		log.Error(err)
	}
}

获取参数

在wego中通过c.Param.GetXXX函数来获取请求参数:

func main() {
	web, err := wego.NewWeb()
	if err != nil{
		log.Error(err)
		return
	}

	web.GET("/user", func(c *WebContext) {
		name := c.Param.GetString("name")
		if name.Error != nil {
			t.Error(name.Error)
		}
		age := c.Param.GetInt("age")
		if age.Error != nil {
			t.Error(age.Error)
		}
        c.WriteText(200, name.Value)
	})

	err = web.Run(":8080")
	if err != nil {
		log.Error(err)
	}
}

使用MustXXX便捷函数获取参数

func main() {
	web, err := wego.NewWeb()
	if err != nil{
		log.Error(err)
		return
	}

	web.GET("/user", func(c *WebContext) {
		name := c.Param.MustString("name")
		t.Log(name)
		age := c.Param.MustInt("age")
		t.Log(age)
	})

	err = web.Run(":8080")
	if err != nil {
		log.Error(err)
	}
}

使用ReadJSON获取参数

若POST请求中Body的数据的格式为JSON格式,可以直接使用WebContext的ReadJSON函数来读取:

func main() {
   web, err := wego.NewWeb()
   if err != nil{
   	log.Error(err)
   	return
   }

   web.POST("/user", func(c *WebContext) {
   	var user2 User
   	err := c.ReadJSON(&user2)
   	if err != nil {
   		t.Log(err)
   	}
   	t.Log(user2)
   })

   err = web.Run(":8080")
   if err != nil {
   	log.Error(err)
   }
}

输出JSON数据

wego对于JSON的支持非常好,可以让我们非常方便的开发一个基于JSON的API。若要返回JSON请求结果,您可以使用WriteJSON函数:

func writeJson(c *wego.WebContext) {
	var user User
	user.ID = 1
	user.Name = "demo"
	user.Age = 12
	c.WriteJSON(200, user)
}

输出HTML数据

wego框架的html结果的输出是基于html/template实现的。以下是一个输出html页面的例子:

func writeHtml(c *wego.WebContext) {
	var user User
	user.ID = 1
	user.Name = "demo"
	user.Age = 12
	c.WriteHTML(200, "./views/index.html", user)
}

使用模板函数

如果您的模板文件中使用了模板函数,需要预先将所需的模板函数进行登记:

func GetUserID(id int64) string {
	return fmt.Sprintf("ID_%d", id)
}

func main() {
	web, err := wego.NewWeb()
	if err != nil{
		log.Error(err)
		return
	}

	wego.AddTemplFunc("GetUserID", GetUserID)
	web.GET("/templfunc", (c *wego.WebContext) {
        var user User
        user.ID = 1
        user.Name = "lisi"
        user.Age = 12
        c.WriteHTML(200, "./views/index.html", user)
     })

	err = web.Run(":8080")
	if err != nil {
		log.Error(err)
	}
}
func setCookie(c *wego.WebContext)  {
	val, err := c.Input.Cookie("demo")
	if err != nil {
		log.Error(err)
	}
	cookie := &http.Cookie{
		Name:     "demo",
		Value:    "test",
		Path:     "/",
		HttpOnly: true,
	}
	c.SetCookie(cookie)
}

重定向

func main() {
	web, err := wego.NewWeb()
	if err != nil{
		log.Error(err)
		return
	}

	web.GET("/redirect", func(c *wego.WebContext) {
		c.Redirect(302, "/index")
	})

	err = web.Run(":8080")
	if err != nil {
		log.Error(err)
	}
}

错误处理

func main() {
	web, err := wego.NewWeb()
	if err != nil{
		log.Error(err)
		return
	}

	web.GET("/abort", func(c *wego.WebContext) {
		name := c.Param.GetString("name")
		if name.Error != nil {
			c.AbortWithError(500, name.Error)
			return
		}
		c.WriteText(200, "hello " + name.Value)
	})

	err = web.Run(":8080")
	if err != nil {
		log.Error(err)
	}
}

使用配置文件

  • 首先定义一个简单的配置文件
#应用名称
app_name = demo
#mysql数据库的配置参数
mysql = root:rootpwd@tcp(127.0.0.1:3306)/demp?charset=utf8

[server]
#http监听端口
http_port = 8080
  • 使用InitWeb()函数初始化Web服务器
func main() {
    web, err := wego.InitWeb()
	if err != nil{
		log.Error(err)
		return
	}

	err = web.Run()
	if err != nil {
		log.Error(err)
	}
}

说明:调用InitWeb()函数时可以指定一个配置文件,若没有指定配置文件,则使用缺省的配置文件:./app.conf。

获取业务参数

调用InitWeb()后wego会自动将系统参数解析到WebEngine.Config中,业务参数则需要用户自己调用配置数据的GetXXX函数来获取。例如:

func main() {
	web, err := wego.InitWeb()
	if err != nil{
		log.Error(err)
		return
	}

	mysql_cnn := web.Config.GetString("mysql")
	if mysql_cnn.Error != nil {
		log.Error(mysql_cnn.Error)
		return
	}
	log.Info(mysql_cnn.Value)

	err = web.Run()
	if err != nil {
		log.Error(err)
	}
}

使用Session

  • 首选定义配置文件:
#应用名称
app_name = demo

[server]
#http监听端口
http_port = 8080

[session]
#session 是否开启
session_on = true
#session类型:cookie、cache
session_store=cookie
#客户端的cookie的名称
cookie_name = "wego"
#session 过期时间, 单位秒
life_time = 3600
#session数据的hash字符串
hash_key = demohash
  • 然后在入口函数中加载配置文件
func main() {
	web, err := wego.NewWeb()
	if err != nil{
		log.Error(err)
		return
	}

	web.GET("/login", login)
	web.GET("/index", index)

	err = web.Run(":8080")
	if err != nil {
		log.Error(err)
	}
}
  • 然后再login处理器函数中保存session数据:
func login(c *wego.WebContext)  {
	c.Session.Set("uid", 1)
	c.Session.Save()
	c.Redirect(302, "/index")
}
  • 然后index处理器函数中就可以访问session数据了:
func index(c *wego.WebContext)  {
	id , _ := c.Session.GetInt("uid")
	c.WriteTextF(200, "uid=%d", id)
}

输出日志

package main
import log "wego/dlog"
func main()  {
	log.Debug("This is a Debug Message")
	log.Info("This is a Info Message")
}
//执行后的输出结果为:
//2021/11/30 07:20:06 [D] main.go:31 This is a Debug Message
//2021/11/30 07:20:06 [I] main.go:32 This is a Debug Info

Documentation

Index

Constants

View Source
const (
	MethodGet    = "GET"
	MethodPost   = "POST"
	MethodPut    = "PUT"
	MethodPatch  = "PATCH"
	MethodDelete = "DELETE"
	MethodPath   = "PATH"
)
View Source
const ContentTypeHTML = "text/html; charset=utf-8"
View Source
const ContentTypeJSON = "application/json; charset=utf-8"
View Source
const ContentTypeText = "text/plain; charset=utf-8"
View Source
const ContentTypeXML = "application/xml; charset=utf-8"

Variables

View Source
var RouteCtxKey string = "RouteContext"

Functions

func AddTemplFunc

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

func CreateSid added in v0.4.6

func CreateSid() string

func CreateSidTmp added in v0.4.6

func CreateSidTmp() (string, error)

func DecodeBase64

func DecodeBase64(value []byte) ([]byte, error)

func EncodeBase64

func EncodeBase64(value []byte) []byte

func GetNameOfFunction

func GetNameOfFunction(f interface{}) string

func GetStatusPrintColor

func GetStatusPrintColor(code int) string

func HandlerNull

func HandlerNull(c *WebContext)

空handler

func ParseTime

func ParseTime(value string) (time.Time, error)

func SetDebugLogLevel

func SetDebugLogLevel(l Level)

func SplitAndTrim

func SplitAndTrim(str string, sep string) (string, string, bool)

func SplitString

func SplitString(str string, sep string) (string, string, bool)

func StringToBytes

func StringToBytes(s string) []byte

func TimeFormat

func TimeFormat(t time.Time, layout string) (datestring string)

Types

type AfterExecer

type AfterExecer interface {
	AfterExec(ctx *WebContext)
}

type BeforeExecer

type BeforeExecer interface {
	BeforeExec(ctx *WebContext)
}

type ContextData

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

func (*ContextData) Get

func (c *ContextData) Get(key string) (interface{}, bool)

func (*ContextData) GetBool

func (c *ContextData) GetBool(key string) (bool, error)

func (*ContextData) GetFloat64

func (s *ContextData) GetFloat64(key string) (float64, error)

func (*ContextData) GetInt64

func (s *ContextData) GetInt64(key string) (int64, error)

func (*ContextData) GetString

func (c *ContextData) GetString(key string) (string, error)

func (*ContextData) GetTime

func (c *ContextData) GetTime(key string) (time.Time, error)

func (*ContextData) Set

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

type DlogConfig

type DlogConfig struct {
	//日志输出类型配置,0 终端 1 文件
	Output int `ini:"output"`
	//日志输出级别: 0 OFF 1 FATAL 2 ERROR 3 WARN 4 INFO 5 DEBUG
	Level int `ini:"level;default=5"`
	//日志文件存储路径,缺省:logs
	Path string `ini:"path;default=logs"`
	//是否在日志里面显示源码文件名和行号,默认 true
	ShowCaller bool `ini:"show_caller;default=true"`
	//是否将json、xml展开显示
	ShowIndent bool `ini:"show_indent;default=true"`
}

type FilterInfo

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

type FlashStat

type FlashStat int
const (
	FLASH_OK FlashStat = iota
	FLASH_ERROR
)

type FormParam

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

func (*FormParam) GetBool

func (this *FormParam) GetBool(key string, defaultValue ...bool) ValidBool

func (*FormParam) GetFloat

func (this *FormParam) GetFloat(key string, defaultValue ...float64) ValidFloat

func (*FormParam) GetInt

func (this *FormParam) GetInt(key string, defaultValue ...int) ValidInt

func (*FormParam) GetInt32

func (this *FormParam) GetInt32(key string, defaultValue ...int32) ValidInt32

func (*FormParam) GetInt64

func (this *FormParam) GetInt64(key string, defaultValue ...int64) ValidInt64

func (*FormParam) GetString

func (this *FormParam) GetString(key string, defaultValue ...string) ValidString

func (*FormParam) GetStruct

func (this *FormParam) GetStruct(ptr interface{}) error

func (*FormParam) GetTime

func (this *FormParam) GetTime(key string, format string, defaultValue ...time.Time) ValidTime

func (*FormParam) GetValue

func (this *FormParam) GetValue(key string) (string, bool)

func (*FormParam) GetValues

func (this *FormParam) GetValues(key string) ([]string, bool)

func (*FormParam) Init

func (this *FormParam) Init(ctx *WebContext)

func (*FormParam) MustBool

func (this *FormParam) MustBool(key string, defaultValue ...bool) bool

func (*FormParam) MustFloat

func (this *FormParam) MustFloat(key string, defaultValue ...float64) float64

func (*FormParam) MustInt

func (this *FormParam) MustInt(key string, defaultValue ...int) int

func (*FormParam) MustInt32

func (this *FormParam) MustInt32(key string, defaultValue ...int32) int32

func (*FormParam) MustInt64

func (this *FormParam) MustInt64(key string, defaultValue ...int64) int64

func (*FormParam) MustString

func (this *FormParam) MustString(key string, defaultValue ...string) string

func (*FormParam) MustTime

func (this *FormParam) MustTime(key string, format string, defaultValue ...time.Time) time.Time

func (*FormParam) Reset

func (this *FormParam) Reset()

func (*FormParam) SetValue

func (this *FormParam) SetValue(key string, val string)

type FuncGetValues

type FuncGetValues func(string, bool) ([]string, bool)

将urql参数解析到struct 只进行struct的的一层解析

type HandlerFunc

type HandlerFunc func(*WebContext)

func Recovery

func Recovery() HandlerFunc

type HandlerType

type HandlerType int
const (
	FT_CTL_HANDLER HandlerType = iota
	FT_CTX_HANDLER
	FT_RAW_HANDLER
)

type HttpHandler

type HttpHandler func(http.ResponseWriter, *http.Request)

type KlogConfig

type KlogConfig struct {
	//是否开启Klog, 默认为 false
	KlognOn bool `ini:"klog_on"`
	//日志文件存储路径,缺省:logs
	Path string `ini:"path;default=logs"`
	//文件轮换类型:0 天 1 小时
	Rotate int `ini:"rotate"`
}

type Level

type Level int
const (
	LOG_OFF Level = iota
	LOG_FATAL
	LOG_ERROR
	LOG_WARN
	LOG_INFO
	LOG_DEBUG
)

func (Level) String

func (lv Level) String() string

type LogPrintCB

type LogPrintCB func(level int, msg string)

type MemcacheConfig

type MemcacheConfig struct {
	//逗号分隔的 memcached 主机列表
	Address string `ini:"address"`
}

type MemoryDbConfig

type MemoryDbConfig struct {
	//用于缓存的内存大小,单位:M, 缺省:0(不限制)
	MaxSize uint64 `ini:"max_size"`
}

type ParamItem

type ParamItem struct {
	Key string
	Val string
}

type ParamValue

type ParamValue interface {
	GetValue(key string) (string, bool)
	GetValues(key string) ([]string, bool)
}

type PathParam

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

func (*PathParam) GetBool

func (this *PathParam) GetBool(key string, defaultValue ...bool) ValidBool

func (*PathParam) GetFloat

func (this *PathParam) GetFloat(key string, defaultValue ...float64) ValidFloat

func (*PathParam) GetInt

func (this *PathParam) GetInt(key string, defaultValue ...int) ValidInt

func (*PathParam) GetInt32

func (this *PathParam) GetInt32(key string, defaultValue ...int32) ValidInt32

func (*PathParam) GetInt64

func (this *PathParam) GetInt64(key string, defaultValue ...int64) ValidInt64

func (*PathParam) GetString

func (this *PathParam) GetString(key string, defaultValue ...string) ValidString

func (*PathParam) GetStruct

func (this *PathParam) GetStruct(ptr interface{}) error

func (*PathParam) GetTime

func (this *PathParam) GetTime(key string, format string, defaultValue ...time.Time) ValidTime

func (*PathParam) GetValue

func (this *PathParam) GetValue(key string) (string, bool)

func (*PathParam) GetValues

func (this *PathParam) GetValues(key string) ([]string, bool)

func (*PathParam) Init

func (this *PathParam) Init()

func (*PathParam) MustBool

func (this *PathParam) MustBool(key string, defaultValue ...bool) bool

func (*PathParam) MustFloat

func (this *PathParam) MustFloat(key string, defaultValue ...float64) float64

func (*PathParam) MustInt

func (this *PathParam) MustInt(key string, defaultValue ...int) int

func (*PathParam) MustInt32

func (this *PathParam) MustInt32(key string, defaultValue ...int32) int32

func (*PathParam) MustInt64

func (this *PathParam) MustInt64(key string, defaultValue ...int64) int64

func (*PathParam) MustString

func (this *PathParam) MustString(key string, defaultValue ...string) string

func (*PathParam) MustTime

func (this *PathParam) MustTime(key string, format string, defaultValue ...time.Time) time.Time

func (*PathParam) Reset

func (this *PathParam) Reset()

func (*PathParam) SetValue

func (this *PathParam) SetValue(key string, val string)

type RedisConfig

type RedisConfig struct {
	//Redis地址
	Address string `ini:"address"`
	//Redis登录密码
	DbPwd string `ini:"db_pwd"`
	//Redis数据库号码
	DbNum int `ini:"db_num"`
}

type RouteGroup

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

func (*RouteGroup) AddFilter

func (group *RouteGroup) AddFilter(name string, handler HandlerFunc) bool

func (*RouteGroup) AfterExec

func (group *RouteGroup) AfterExec(handler HandlerFunc)

func (*RouteGroup) BeforExec

func (group *RouteGroup) BeforExec(handler HandlerFunc)

func (*RouteGroup) DELETE

func (group *RouteGroup) DELETE(pattern string, handler interface{}) *RouteInfo

func (*RouteGroup) GET

func (group *RouteGroup) GET(pattern string, handler interface{}) *RouteInfo

func (*RouteGroup) InitRoot

func (group *RouteGroup) InitRoot(engine *WebEngine)

func (*RouteGroup) NewGroup

func (group *RouteGroup) NewGroup(path string) *RouteGroup

func (*RouteGroup) PATCH

func (group *RouteGroup) PATCH(pattern string, handler interface{}) *RouteInfo

func (*RouteGroup) PATH

func (group *RouteGroup) PATH(pattern string, handler interface{}) *RouteInfo

func (*RouteGroup) POST

func (group *RouteGroup) POST(pattern string, handler interface{}) *RouteInfo

func (*RouteGroup) PUT

func (group *RouteGroup) PUT(pattern string, handler interface{}) *RouteInfo

func (*RouteGroup) StaticFile

func (group *RouteGroup) StaticFile(relativePath, filepath string) *RouteInfo

func (*RouteGroup) StaticPath

func (group *RouteGroup) StaticPath(relativePath string, root string) *RouteInfo

type RouteInfo

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

func (*RouteInfo) AfterExec

func (r *RouteInfo) AfterExec(handler HandlerFunc) *RouteInfo

func (*RouteInfo) BeforExec

func (r *RouteInfo) BeforExec(handler HandlerFunc) *RouteInfo

func (*RouteInfo) GetHandlerName

func (r *RouteInfo) GetHandlerName() string

func (*RouteInfo) SkipAfterHook added in v0.4.6

func (r *RouteInfo) SkipAfterHook()

func (*RouteInfo) SkipBeforHook added in v0.4.6

func (r *RouteInfo) SkipBeforHook()

func (*RouteInfo) SkipHook added in v0.4.6

func (r *RouteInfo) SkipHook()

type RouteTree

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

type ServerConfig

type ServerConfig struct {
	//是否启用 HTTPS,默认是false
	UseHttps bool `ini:"use_https"`
	//Http监听地址,默认为空
	HttpAddr string `ini:"http_addr"`
	//Http监听端口,默认为 8080
	HttpPort uint `ini:"http_port;default=8080"`
	//Https监听地址,默认为空
	HttpsAddr string `ini:"https_addr"`
	//Https监听端口,默认为 10443
	HttpsPort uint `ini:"https_port;default=10443"`
	//HTTPS证书路径
	HttpsCertFile string `ini:"cert_file"`
	//HTTPS证书 keyfile 的路径
	HttpsKeyFile string `ini:"key_file"`
	//设置 HTTP 的超时时间
	ReadTimeout time.Duration `ini:"read_timeout"`
	//设置 HTTP 的超时时间
	WriteTimeout time.Duration `ini:"write_timeout"`
	//POST请求的默认内存缓存大小,单位:M
	MaxBody int64 `ini:"max_body"`
	//是否开启 gzip,输出的内容会进行 gzip,根据Accept-Encoding来判断
	EnableGzip bool `ini:"gzip_on"`
	//压缩长度阈值,只有超过gzip_size的会被压缩返回
	GzipSize int64 `ini:"gzip_size"`
}

type SessionConfig

type SessionConfig struct {
	//缓是否开启session, 默认为 false
	SessionOn bool `ini:"session_on"`
	//session类型:cookie、cache
	SessionStore string `ini:"session_store;default=cookie"`
	//客户端的cookie的名称前缀
	CookieName string `ini:"cookie_name;default=wego"`
	//保存session数据的cookie域名, 默认空
	Domain string `ini:"domain"`
	//session 过期时间,单位:秒,默认值是3600
	LifeTime uint `ini:"life_time;default=3600"`
	//设置cookie的SameSite属性
	SameSite http.SameSite `ini:"samesite"`
	//session数据的hash字符串,若session的存储类型为cookie,则必须提供
	HashKey string `ini:"hash_key"`
}

type SessionData

type SessionData map[string]string

type SessionEngine

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

func (*SessionEngine) CreateSid

func (this *SessionEngine) CreateSid() (string, error)

func (*SessionEngine) Init

func (this *SessionEngine) Init(store cache.CacheStore)

func (*SessionEngine) ReadData

func (this *SessionEngine) ReadData(ctx context.Context, sid string) ([]byte, error)

func (*SessionEngine) SaveData

func (this *SessionEngine) SaveData(ctx context.Context, sid string, data []byte) error

func (*SessionEngine) SetCookieName

func (this *SessionEngine) SetCookieName(cookieName string)

func (*SessionEngine) SetMaxAge

func (this *SessionEngine) SetMaxAge(max_age uint)

type SessionInfo

type SessionInfo struct {
	Sid  string
	Data SessionData
	Edit bool
	// contains filtered or unexported fields
}

func (*SessionInfo) Clear

func (this *SessionInfo) Clear()

func (*SessionInfo) Delete

func (this *SessionInfo) Delete(key string)

func (*SessionInfo) Get

func (this *SessionInfo) Get(key string) (string, bool)

func (*SessionInfo) GetBool

func (this *SessionInfo) GetBool(key string) (bool, error)

func (*SessionInfo) GetFloat

func (this *SessionInfo) GetFloat(key string) (float64, error)

func (*SessionInfo) GetInt

func (this *SessionInfo) GetInt(key string) (int64, error)

func (*SessionInfo) GetString

func (this *SessionInfo) GetString(key string) (string, error)

func (*SessionInfo) GetStuct

func (this *SessionInfo) GetStuct(key string, ptr interface{}) error

func (*SessionInfo) GetTime

func (this *SessionInfo) GetTime(key string) (time.Time, error)

func (*SessionInfo) Read

func (this *SessionInfo) Read() error

func (*SessionInfo) Reset

func (this *SessionInfo) Reset()

func (*SessionInfo) Save

func (this *SessionInfo) Save() error

func (*SessionInfo) Set

func (this *SessionInfo) Set(key string, value interface{})

type ShutdownFunc

type ShutdownFunc func()

type SimpleLogger

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

func NewSimpleLogger

func NewSimpleLogger() *SimpleLogger

func (*SimpleLogger) Debug

func (lg *SimpleLogger) Debug(v ...interface{})

func (*SimpleLogger) Debugf

func (lg *SimpleLogger) Debugf(format string, v ...interface{})

func (*SimpleLogger) Error

func (lg *SimpleLogger) Error(v ...interface{})

func (*SimpleLogger) Errorf

func (lg *SimpleLogger) Errorf(format string, v ...interface{})

func (*SimpleLogger) Fatal

func (lg *SimpleLogger) Fatal(v ...interface{})

func (*SimpleLogger) Fatalf

func (lg *SimpleLogger) Fatalf(format string, v ...interface{})

func (*SimpleLogger) Info

func (lg *SimpleLogger) Info(v ...interface{})

func (*SimpleLogger) Infof

func (lg *SimpleLogger) Infof(format string, v ...interface{})

func (*SimpleLogger) Output

func (lg *SimpleLogger) Output(level_str string, msg string) error

func (*SimpleLogger) SetLevel

func (lg *SimpleLogger) SetLevel(l Level)

func (*SimpleLogger) Warn

func (lg *SimpleLogger) Warn(v ...interface{})

func (*SimpleLogger) Warnf

func (lg *SimpleLogger) Warnf(format string, v ...interface{})

type SkipFlag added in v1.0.7

type SkipFlag int
const (
	SKIP_HOOK_NULL   SkipFlag = 0
	SKIP_HOOK_BEFORE SkipFlag = 1
	SKIP_HOOK_AFTER  SkipFlag = 2
	SKIP_HOOK_ALL    SkipFlag = 3
)

type TagInfo

type TagInfo struct {
	FieldName string
	HasValue  bool
	DefValue  string
}

func GetTagInfo

func GetTagInfo(ff reflect.StructField, tag string) TagInfo

获取struct的字段信息

type TreeNode

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

func (*TreeNode) AddRoute

func (n *TreeNode) AddRoute(method string, url_path string, pval *RouteInfo)

func (*TreeNode) GetRoute

func (n *TreeNode) GetRoute(method string, url_path string, params *PathParam) *RouteInfo

type TreeNodeX

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

func (*TreeNodeX) AddRoute

func (n *TreeNodeX) AddRoute(method string, url_path string, pval *RouteInfo)

func (*TreeNodeX) GetRoute

func (n *TreeNodeX) GetRoute(method string, url_path string, params *PathParam) *RouteInfo

type ValidBool

type ValidBool struct {
	Value bool
	Error error
}

type ValidFloat

type ValidFloat struct {
	Value float64
	Error error
}

type ValidInt

type ValidInt struct {
	Value int
	Error error
}

type ValidInt32

type ValidInt32 struct {
	Value int32
	Error error
}

type ValidInt64

type ValidInt64 struct {
	Value int64
	Error error
}

type ValidString

type ValidString struct {
	Value string
	Error error
}

type ValidTime

type ValidTime struct {
	Value time.Time
	Error error
}

type WebConfig

type WebConfig struct {
	wini.ConfigData
	//应用名称
	AppName string `ini:"app_name"`
	//服务器名称
	ServerName string `ini:"server_name"`
	//缓是否开启缓存
	CacheOn bool `ini:"cache_on"`
	//cache类型:redis、memcache、memory
	CacheStore string `ini:"cache_store;default=memory"`
	//是否显示请求日志,默认为 true
	ShowUrlLog bool `ini:"show_url_log;default=true"`
	//是否显示请求日志,默认为 true
	ShowSqlLog bool `ini:"show_sql_log;default=true"`
	//设置调试日志级别:0 OFF 1 FATAL 2 ERROR 3 WARN 4 INFO 5 DEBUG
	ShowDebugLog int `ini:"show_debug_log"`
	//防JSON劫持的前缀字符串
	JsonPrefix string `ini:"json_prefix"`
	//获取client ip的header
	IPHeader string `ini:"ip_header"`
	//Web服务配置
	ServerParam ServerConfig `ini:"server"`
	//Session配置
	SessionParam SessionConfig `ini:"session"`
	//内存缓存配置
	MemoryDbParam MemoryDbConfig `ini:"memory"`
	//Redis缓存配置
	RedisParam RedisConfig `ini:"redis"`
	//Memcache缓存配置
	MemcacheParam MemcacheConfig `ini:"memcache"`
	//日志模块配置
	DlogParam DlogConfig `ini:"dlog"`
	//统计日志配置
	KlogParam KlogConfig `ini:"klog"`
}

func (*WebConfig) InitCache

func (this *WebConfig) InitCache() error

通过配置参数初始化Cache

func (*WebConfig) InitDlog

func (this *WebConfig) InitDlog() error

通过配置参数初始化Dlog

func (*WebConfig) InitKlog

func (this *WebConfig) InitKlog() error

通过配置参数初始化Dlog

func (*WebConfig) InitSession

func (this *WebConfig) InitSession(sess *SessionEngine) error

通过配置参数初始化Session

func (*WebConfig) LoadConfig

func (this *WebConfig) LoadConfig(file_name ...string) error

加载配置文件

func (*WebConfig) NewCookieStore

func (this *WebConfig) NewCookieStore() (cache.CacheStore, error)

通过配置参数初创建CookieStore

func (*WebConfig) NewMemcacheStore

func (this *WebConfig) NewMemcacheStore() (cache.CacheStore, error)

通过配置参数初创建MemcacheStore

func (*WebConfig) NewMemoryStore

func (this *WebConfig) NewMemoryStore() (cache.CacheStore, error)

通过配置参数初创建MemoryStore

func (*WebConfig) NewRedisStore

func (this *WebConfig) NewRedisStore() (cache.CacheStore, error)

通过配置参数初创建RedisStore

type WebContext

type WebContext struct {
	Config *WebConfig

	Input      WebRequest
	Output     WebResponse
	Route      *RouteInfo
	Path       string
	Param      WebParam
	RouteParam PathParam
	QueryParam FormParam
	FormParam  FormParam
	Data       ContextData
	Session    SessionInfo
	Start      time.Time
	// contains filtered or unexported fields
}

func GetWebContext

func GetWebContext(r *http.Request) *WebContext

func (*WebContext) Abort

func (c *WebContext) Abort(code int)

func (*WebContext) Abort401

func (c *WebContext) Abort401()

func (*WebContext) Abort500

func (c *WebContext) Abort500()

func (*WebContext) AbortWithError

func (c *WebContext) AbortWithError(code int, err error)

func (*WebContext) AbortWithHtml

func (c *WebContext) AbortWithHtml(code int, filenames string, data interface{})

func (*WebContext) AbortWithJson

func (c *WebContext) AbortWithJson(code int, obj interface{})

func (*WebContext) AbortWithTemplate

func (c *WebContext) AbortWithTemplate(code int, templ *template.Template, data interface{})

func (*WebContext) AbortWithText

func (c *WebContext) AbortWithText(code int, value string)

func (*WebContext) AbortWithTextF

func (c *WebContext) AbortWithTextF(code int, format string, values ...interface{})

func (*WebContext) AbortWithXml

func (c *WebContext) AbortWithXml(code int, obj interface{})

func (*WebContext) AcceptWebsocket added in v1.1.3

func (c *WebContext) AcceptWebsocket(opts *gows.AcceptOptions, headers map[string]string) (*gows.WebSocket, error)

websocket握手

func (*WebContext) Ended

func (c *WebContext) Ended() bool

func (*WebContext) GetFile

func (c *WebContext) GetFile(name string) (*multipart.FileHeader, error)

func (*WebContext) GetFiles

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

func (*WebContext) Next

func (c *WebContext) Next()

func (*WebContext) ReadBody

func (c *WebContext) ReadBody() ([]byte, error)

func (*WebContext) ReadJSON

func (c *WebContext) ReadJSON(obj interface{}) error

func (*WebContext) ReadXML

func (c *WebContext) ReadXML(obj interface{}) error

func (*WebContext) Redirect

func (c *WebContext) Redirect(code int, localurl string)

func (*WebContext) SaveToFile

func (c *WebContext) SaveToFile(file *multipart.FileHeader, path string) error

func (*WebContext) SetCookie

func (c *WebContext) SetCookie(ck *http.Cookie)

Domain:定义Cookie的生效作用域,只有当域名和路径同时满足的时候,浏览器才会将Cookie发送给Server。 Expires:过期时间,绝对时间点。 Max-Age:收到报文后多久的过期时间,单位是秒。设置为0时立刻失效。 HttpOnly:如设为True,JavaScript这些脚本无法访问,即有效减少 XSS 攻击 Secure:如设置secure为true,浏览器只会在HTTPS和SSL等安全协议中传输Cookie。 SameSite:可以防范 CSRF 攻击。

SameSite=None:无论是否跨站都会发送 Cookie,
SameSite=Lax:允许部分第三方请求携带 Cookie,
SameSite=Strict:仅允许同站请求携带 Cookie,即当前网页 URL 与请求目标 URL 完全一致

func (*WebContext) SetHeader

func (c *WebContext) SetHeader(key string, value string)

func (*WebContext) Status

func (c *WebContext) Status(code int)

func (*WebContext) UseGzip

func (c *WebContext) UseGzip(flag bool, min_size ...int64) *WebContext

func (*WebContext) Write

func (c *WebContext) Write(code int, contentType string, data []byte)

func (*WebContext) WriteFile

func (c *WebContext) WriteFile(filePath string, fileName ...string)

func (*WebContext) WriteHTML

func (c *WebContext) WriteHTML(code int, filename string, data interface{})

func (*WebContext) WriteHTMLS

func (c *WebContext) WriteHTMLS(code int, filenames []string, data interface{})

func (*WebContext) WriteHtmlBytes

func (c *WebContext) WriteHtmlBytes(code int, data []byte)

func (*WebContext) WriteIndentedJSON

func (c *WebContext) WriteIndentedJSON(code int, obj interface{})

美化JSON的输出,可以使用json.MarshalIndent方法对obj进行编码

func (*WebContext) WriteIndentedXML

func (c *WebContext) WriteIndentedXML(code int, obj interface{})

func (*WebContext) WriteJSON

func (c *WebContext) WriteJSON(code int, obj interface{})

func (*WebContext) WriteJSONP

func (c *WebContext) WriteJSONP(code int, obj interface{})

输出JSONP,使用callback参数名作为接收回调函数的名称

func (*WebContext) WriteLayoutHTML

func (c *WebContext) WriteLayoutHTML(code int, layout_file string, content_file string, data interface{})

func (*WebContext) WriteNoContent

func (c *WebContext) WriteNoContent(code int, contentType string)

func (*WebContext) WriteSecureJSON

func (c *WebContext) WriteSecureJSON(code int, obj interface{})

防JSON劫持缺省的前缀是while(1);

func (*WebContext) WriteTemplate

func (c *WebContext) WriteTemplate(code int, templ *template.Template, data interface{})

func (*WebContext) WriteText

func (c *WebContext) WriteText(code int, data string)

func (*WebContext) WriteTextBytes

func (c *WebContext) WriteTextBytes(code int, data []byte)

func (*WebContext) WriteTextF

func (c *WebContext) WriteTextF(code int, format string, values ...interface{})

func (*WebContext) WriteXML

func (c *WebContext) WriteXML(code int, obj interface{})

type WebEngine

type WebEngine struct {
	RouteGroup
	//路由树对象
	Route RouteTree
	//html tepmplates缓存
	Templates WebTemplates
	//session引擎
	Session SessionEngine
	//配置参数
	Config WebConfig

	//获取Ip的header
	IPHeaders []string
	// contains filtered or unexported fields
}

func InitWeb

func InitWeb(file_name ...string) (*WebEngine, error)

func InitWebWithFile added in v1.0.4

func InitWebWithFile(file_name string) (*WebEngine, error)

func NewWeb

func NewWeb() (*WebEngine, error)

func (*WebEngine) BeforRouter

func (web *WebEngine) BeforRouter(handler HandlerFunc)

func (*WebEngine) InitRoute404

func (web *WebEngine) InitRoute404()

func (*WebEngine) Run

func (web *WebEngine) Run(addr ...string) (err error)

func (*WebEngine) RunHTTP

func (web *WebEngine) RunHTTP(addr string) error

func (*WebEngine) RunTLS

func (web *WebEngine) RunTLS(addr string, certFile string, keyFile string) error

func (*WebEngine) ServeHTTP

func (web *WebEngine) ServeHTTP(w http.ResponseWriter, req *http.Request)

func (*WebEngine) SetHandler401

func (web *WebEngine) SetHandler401(handler HandlerFunc)

func (*WebEngine) SetHandler404

func (web *WebEngine) SetHandler404(handler HandlerFunc)

func (*WebEngine) SetHandler500

func (web *WebEngine) SetHandler500(handler HandlerFunc)

func (*WebEngine) SetShutdown

func (web *WebEngine) SetShutdown(hook ShutdownFunc)

type WebFlash

type WebFlash struct {
	Stat FlashStat
	Data map[string]string
}

func NewFlash

func NewFlash() *WebFlash

func ReadFlash

func ReadFlash(ctx *WebContext) *WebFlash

func (*WebFlash) ReadData

func (this *WebFlash) ReadData(ctx *WebContext) error

func (*WebFlash) SaveData

func (this *WebFlash) SaveData(ctx *WebContext) error

func (*WebFlash) SaveErrorData

func (this *WebFlash) SaveErrorData(ctx *WebContext) error

func (*WebFlash) SaveSuccessData

func (this *WebFlash) SaveSuccessData(ctx *WebContext) error

type WebParam

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

func (*WebParam) GetBool

func (this *WebParam) GetBool(key string, defaultValue ...bool) ValidBool

func (*WebParam) GetFloat

func (this *WebParam) GetFloat(key string, defaultValue ...float64) ValidFloat

func (*WebParam) GetInt

func (this *WebParam) GetInt(key string, defaultValue ...int) ValidInt

func (*WebParam) GetInt32

func (this *WebParam) GetInt32(key string, defaultValue ...int32) ValidInt32

func (*WebParam) GetInt64

func (this *WebParam) GetInt64(key string, defaultValue ...int64) ValidInt64

func (*WebParam) GetString

func (this *WebParam) GetString(key string, defaultValue ...string) ValidString

func (*WebParam) GetStruct

func (this *WebParam) GetStruct(ptr interface{}) error

func (*WebParam) GetTime

func (this *WebParam) GetTime(key string, format string, defaultValue ...time.Time) ValidTime

func (*WebParam) GetValue

func (this *WebParam) GetValue(key string) (string, bool)

func (*WebParam) GetValues

func (this *WebParam) GetValues(key string) ([]string, bool)

func (*WebParam) MustBool

func (this *WebParam) MustBool(key string, defaultValue ...bool) bool

func (*WebParam) MustFloat

func (this *WebParam) MustFloat(key string, defaultValue ...float64) float64

func (*WebParam) MustInt

func (this *WebParam) MustInt(key string, defaultValue ...int) int

func (*WebParam) MustInt32

func (this *WebParam) MustInt32(key string, defaultValue ...int32) int32

func (*WebParam) MustInt64

func (this *WebParam) MustInt64(key string, defaultValue ...int64) int64

func (*WebParam) MustString

func (this *WebParam) MustString(key string, defaultValue ...string) string

func (*WebParam) MustTime

func (this *WebParam) MustTime(key string, format string, defaultValue ...time.Time) time.Time

type WebRequest

type WebRequest struct {
	*http.Request
	// contains filtered or unexported fields
}

func (*WebRequest) ClientIP

func (this *WebRequest) ClientIP() string

func (*WebRequest) ContentType

func (this *WebRequest) ContentType() string

func (*WebRequest) Cookie

func (this *WebRequest) Cookie(name string) (string, error)

func (*WebRequest) GetHeader

func (this *WebRequest) GetHeader(key string) string

func (*WebRequest) Host

func (this *WebRequest) Host() string

func (*WebRequest) Method

func (this *WebRequest) Method() string

func (*WebRequest) Referer

func (this *WebRequest) Referer() string

func (*WebRequest) RemoteIP

func (this *WebRequest) RemoteIP() string

func (*WebRequest) URI

func (this *WebRequest) URI() string

func (*WebRequest) URL

func (this *WebRequest) URL() string

func (*WebRequest) UserAgent

func (this *WebRequest) UserAgent() string

type WebResponse

type WebResponse struct {
	http.ResponseWriter
	StatusCode int
	// contains filtered or unexported fields
}

func (*WebResponse) Flush

func (w *WebResponse) Flush() error

func (*WebResponse) GetStatus

func (w *WebResponse) GetStatus() int

func (*WebResponse) SetStatus

func (w *WebResponse) SetStatus(code int)

func (*WebResponse) Write

func (w *WebResponse) Write(data []byte) (int, error)

func (*WebResponse) WriteHeader

func (w *WebResponse) WriteHeader(code int)

func (*WebResponse) WroteHeader

func (w *WebResponse) WroteHeader() bool

type WebState

type WebState struct {
	Status int
	Error  error
}

func (*WebState) Reset

func (this *WebState) Reset()

func (*WebState) Set

func (this *WebState) Set(code int, err error)

type WebStatus

type WebStatus int
const (
	STATUS_BEG WebStatus = iota
	STATUS_END
)

type WebTemplates

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

func (*WebTemplates) Init

func (this *WebTemplates) Init()

func (*WebTemplates) SetDelim

func (this *WebTemplates) SetDelim(left, right string)

Directories

Path Synopsis
mod/memcache
Package memcache provides a client for the memcached cache server.
Package memcache provides a client for the memcached cache server.
mod/redis
Package redis is a client for the Redis database.
Package redis is a client for the Redis database.

Jump to

Keyboard shortcuts

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