lessgo

package module
v0.7.0 Latest Latest
Warning

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

Go to latest
Published: Jun 1, 2016 License: MIT Imports: 37 Imported by: 0

README

#Lessgo Web Framework GoDoc GitHub release

Lessgo Favicon

##概述 Lessgo是一款Go语言开发的简单、稳定、高效、灵活的 web开发框架。它的项目组织形式经过精心设计,实现前后端分离、系统与业务分离,完美兼容MVC与MVVC等多种开发模式,非常利于企业级应用与API接口的开发。当然,最值得关注的是它突破性支持运行时路由重建,开发者可在Admin后台轻松配置路由,并实现启用/禁用模块或操作、添加/移除中间件等!同时,它以ApiHandler与ApiMiddleware为项目基本组成单元,可实现编译期或运行时的自由搭配组合,也令开发变得更加灵活富有趣味性。

官方QQ群:Go-Web 编程 42730308 Go-Web 编程群

##适用场景

  • 网站
  • web应用
  • Restful API服务应用
  • 企业应用

##当前版本

  • V0.6.0
  • 发布日期:2016.05.17

##最新功能特性

  • 使用简单、运行稳定高效(核心架构来自对echo真正意义的二次开发)
  • 兼容流行系统模式如:MVC、MVVC、Restful...
  • httprouter真实路由配合强大的虚拟路由层,不仅性能优秀更可同时支持在源码或admin中动态配置
  • 多异构数据库支持,且用户可以选择xorm或者gorm两种引擎(当然愿意,用户还可以同时使用两种引擎)
  • 优化的项目目录组织最佳实践,满足复杂企业应用需要
  • 集成统一的系统日志(system、database独立完整的日志)
  • 提供Session管理(优化beego框架中的session包)
  • 强大的前端模板渲染引擎(pongo2)
  • 天生支持运行时可更新的API测试网页(swagger2.0)
  • 配置文件自动补填默认值,并按字母排序
  • 支持热编译
  • 支持热升级
  • 另外灵活的扩展包中还包含HOTP、TOTP、UUID以及各种条码生成工具等常用工具包

Lessgo Server Lessgo Server

##框架下载

go get -u github.com/lessgo/lessgo
go get -u github.com/lessgo/lessgoext/...

##框架构成

##代码示例

  • main.go
import (
    "github.com/lessgo/lessgo"
    "github.com/lessgo/lessgoext/swagger"

    _ "github.com/lessgo/lessgoext/dbservice/xorm"
    // _ "github.com/lessgo/lessgoext/dbservice/gorm"

    _ "github.com/lessgo/demo/middleware"
    _ "github.com/lessgo/demo/router"
)

func main() {
    // 开启自动api文档,false表示仅允许内网访问
    swagger.Reg(false)
    // 指定根目录URL
    lessgo.SetHome("/home")
    // 开启网络服务
    lessgo.Run()
}
  • 定义一个较复杂的操作
import (
    . "github.com/lessgo/lessgo"
    "github.com/lessgo/demo/sysmodel/admin"
)

var Index = ApiHandler{
    Desc:   "后台管理登录操作",
    Method: "GET|PUT",
    Params: []Param{
        {"user", "path", true, "henry", "用户名"},
        {"password", "path", true, "12345678", "密码"},
    },
    Handler: func(c *Context) error {
        // 测试读取cookie
        id, err := c.Request().Cookie(Config.Session.SessionName)
        c.Log().Info("cookie中的%v: %#v (%v)", Config.Session.SessionName, id, err)

        // 测试session
        c.Log().Info("从session读取上次请求的输入: %#v", c.GetSession("info"))

        c.SetSession("info", map[string]interface{}{
            "user":     c.Param("user"),
            "password": c.Param("password"),
        })

        return c.Render(200,
            "sysview/admin/login/index.tpl",
            map[string]interface{}{
                "name":       c.Param("user"),
                "password":   c.Param("password"),
                "repeatfunc": admin.Login.Repeatfunc,
            },
        )
    },
}.Reg()
  • 一个简单的数据模型
import (
    "strings"
)
type login struct{}
var Login = login{}

func (_ login) Repeatfunc(s string, count int) string {
    return strings.Repeat(s, count)
}
  • 一个简单的中间件
var ShowHeader = lessgo.ApiMiddleware{
    Name:   "显示Header",
    Desc:   "显示Header测试",
    Config: nil,
    Middleware: func(c *lessgo.Context) error {
        c.Log().Info("测试中间件-显示Header:%v", c.Request().Header)
        return nil
    },
}.Reg()
  • 在源码中定义路由
package router

import (
    "github.com/lessgo/lessgo"

    "github.com/lessgo/demo/bizhandler/home"
    "github.com/lessgo/demo/middleware"
)

func init() {
    lessgo.Root(
        lessgo.Leaf("/websocket", home.WebSocket, middleware.ShowHeader),
        lessgo.Branch("/home", "前台",
            lessgo.Leaf("/index", home.Index, middleware.ShowHeader),
        ).Use(middleware.Print),
    )
}

##系统文档

##项目架构 Lessgo Web Framework

##项目目录结构

─Project 项目开发目录
├─config 配置文件目录
│  ├─app.config 系统应用配置文件
│  └─db.config 数据库配置文件
├─common 后端公共目录
│  └─... 如utils等其他
├─middleware 后端公共中间件目录
├─static 前端公共目录 (url: /static)
│  ├─tpl 公共tpl模板目录
│  ├─js 公共js目录 (url: /static/js)
│  ├─css 公共css目录 (url: /static/css)
│  ├─img 公共img目录 (url: /static/img)
│  └─plugin 公共js插件 (url: /static/plugin)
├─uploads 默认上传下载目录
├─router 源码路由配置
│  ├─sysrouter.go 系统模块路由文件
│  ├─bizrouter.go 业务模块路由文件
├─syshandler 系统模块后端目录
│  ├─xxx 子模块目录
│  │  ├─example.go example操作
│  │  └─... xxx的子模块目录
│  └─... 其他子模块目录
├─sysmodel 系统模块数据模型目录
├─sysview 系统模块前端目录 (url: /sys)
│  ├─xxx 与syshandler对应的子模块目录 (url: /sys/xxx)
│  │  ├─example.tpl 相应操作的模板文件
│  │  ├─example2.html 无需绑定操作的静态html文件
│  │  ├─xxx.css css文件(可有多个)
│  │  ├─xxx.js js文件(可有多个)
│  │  └─... xxx的子模块目录
├─bizhandler 业务模块后端目录
│  ├─xxx 子模块目录
│  │  ├─example.go example操作
│  │  └─... xxx的子模块目录
│  └─... 其他子模块目录
├─bizmodel 业务模块数据模型目录
├─bizview 业务模块前端目录 (url: /biz)
│  ├─xxx 与bizhandler对应的子模块目录 (url: /biz/xxx)
│  │  ├─example.tpl 相应操作的模板文件
│  │  ├─example2.html 无需绑定操作的静态html文件
│  │  ├─xxx.css css文件(可有多个)
│  │  ├─xxx.js js文件(可有多个)
│  │  └─... xxx的子模块目录
├─database 默认数据库文件存储目录
├─logger 运行日志输出目录
└─main.go 应用入口文件

##贡献者名单

贡献者 贡献概要
henrylee2cn 代码的主要实现者 (第一作者)
changyu72 架构的主要设计者 (第二作者)
LeSou

##开源协议 Lessgo 项目采用商业应用友好的 MIT 协议发布。

Documentation

Overview

Package lessgo implements a simple, stable, efficient and flexible web framework for Go.

Author1: https://github.com/henrylee2cn Author2: https://github.com/changyu72

Index

Constants

View Source
const (
	CONNECT = "CONNECT"
	DELETE  = "DELETE"
	GET     = "GET"
	HEAD    = "HEAD"
	OPTIONS = "OPTIONS"
	PATCH   = "PATCH"
	POST    = "POST"
	PUT     = "PUT"
	TRACE   = "TRACE"

	WS  = "WS" // websocket "GET"
	ANY = "*"  // exclusion of all methods out of "WS"
)

HTTP methods

View Source
const (
	MIMEApplicationJSON                  = "application/json"
	MIMEApplicationJSONCharsetUTF8       = MIMEApplicationJSON + "; " + charsetUTF8
	MIMEApplicationJavaScript            = "application/javascript"
	MIMEApplicationJavaScriptCharsetUTF8 = MIMEApplicationJavaScript + "; " + charsetUTF8
	MIMEApplicationXML                   = "application/xml"
	MIMEApplicationXMLCharsetUTF8        = MIMEApplicationXML + "; " + charsetUTF8
	MIMEApplicationForm                  = "application/x-www-form-urlencoded"
	MIMEApplicationProtobuf              = "application/protobuf"
	MIMEApplicationMsgpack               = "application/msgpack"
	MIMETextHTML                         = "text/html"
	MIMETextHTMLCharsetUTF8              = MIMETextHTML + "; " + charsetUTF8
	MIMETextPlain                        = "text/plain"
	MIMETextPlainCharsetUTF8             = MIMETextPlain + "; " + charsetUTF8
	MIMEMultipartForm                    = "multipart/form-data"
	MIMEOctetStream                      = "application/octet-stream"
)

MIME types

View Source
const (
	HeaderAcceptEncoding                = "Accept-Encoding"
	HeaderAuthorization                 = "Authorization"
	HeaderContentDisposition            = "Content-Disposition"
	HeaderContentEncoding               = "Content-Encoding"
	HeaderContentLength                 = "Content-Length"
	HeaderContentType                   = "Content-Type"
	HeaderCookie                        = "Cookie"
	HeaderSetCookie                     = "Set-Cookie"
	HeaderIfModifiedSince               = "If-Modified-Since"
	HeaderLastModified                  = "Last-Modified"
	HeaderLocation                      = "Location"
	HeaderUpgrade                       = "Upgrade"
	HeaderVary                          = "Vary"
	HeaderWWWAuthenticate               = "WWW-Authenticate"
	HeaderXForwardedProto               = "X-Forwarded-Proto"
	HeaderXHTTPMethodOverride           = "X-HTTP-Method-Override"
	HeaderXForwardedFor                 = "X-Forwarded-For"
	HeaderXRealIP                       = "X-Real-IP"
	HeaderServer                        = "Server"
	HeaderOrigin                        = "Origin"
	HeaderAccessControlRequestMethod    = "Access-Control-Request-Method"
	HeaderAccessControlRequestHeaders   = "Access-Control-Request-Headers"
	HeaderAccessControlAllowOrigin      = "Access-Control-Allow-Origin"
	HeaderAccessControlAllowMethods     = "Access-Control-Allow-Methods"
	HeaderAccessControlAllowHeaders     = "Access-Control-Allow-Headers"
	HeaderAccessControlAllowCredentials = "Access-Control-Allow-Credentials"
	HeaderAccessControlExposeHeaders    = "Access-Control-Expose-Headers"
	HeaderAccessControlMaxAge           = "Access-Control-Max-Age"

	// Security
	HeaderStrictTransportSecurity = "Strict-Transport-Security"
	HeaderXContentTypeOptions     = "X-Content-Type-Options"
	HeaderXXSSProtection          = "X-XSS-Protection"
	HeaderXFrameOptions           = "X-Frame-Options"
	HeaderContentSecurityPolicy   = "Content-Security-Policy"
	HeaderXCSRFToken              = "X-CSRF-Token"
)

Headers

View Source
const (
	BIZ_HANDLER_DIR = "bizhandler"
	BIZ_MODEL_DIR   = "bizmodel"
	BIZ_VIEW_DIR    = "bizview"
	SYS_HANDLER_DIR = "syshandler"
	SYS_MODEL_DIR   = "sysmodel"
	SYS_VIEW_DIR    = "sysview"
	STATIC_DIR      = "static"
	IMG_DIR         = STATIC_DIR + "/img"
	JS_DIR          = STATIC_DIR + "/js"
	CSS_DIR         = STATIC_DIR + "/css"
	TPL_DIR         = STATIC_DIR + "/tpl"
	PLUGIN_DIR      = STATIC_DIR + "/plugin"
	UPLOADS_DIR     = "uploads"
	COMMON_DIR      = "common"
	MIDDLEWARE_DIR  = "middleware"
	ROUTER_DIR      = "router"

	TPL_EXT         = ".tpl"
	STATIC_HTML_EXT = ".html"

	CONFIG_DIR        = "config"
	APPCONFIG_FILE    = CONFIG_DIR + "/app.config"
	ROUTERCONFIG_FILE = CONFIG_DIR + "/virtrouter.config"
	LOG_FILE          = "logger/lessgo.log"
)

项目固定目录文件名称

View Source
const (
	NAME    = "Lessgo"
	VERSION = "0.7.0"
	ADDRESS = "https://github.com/lessgo/lessgo"
)
View Source
const (
	ROOT int = iota
	GROUP
	HANDLER
)

虚拟路由节点类型

View Source
const (
	MB = 1 << 20
)

Variables

View Source
var (
	ErrUnsupportedMediaType        = NewHTTPError(http.StatusUnsupportedMediaType)
	ErrNotFound                    = NewHTTPError(http.StatusNotFound)
	ErrUnauthorized                = NewHTTPError(http.StatusUnauthorized)
	ErrMethodNotAllowed            = NewHTTPError(http.StatusMethodNotAllowed)
	ErrStatusRequestEntityTooLarge = NewHTTPError(http.StatusRequestEntityTooLarge)
	ErrStatusInternalServerError   = NewHTTPError(http.StatusInternalServerError)
	ErrRendererNotRegistered       = errors.New("renderer not registered")
	ErrInvalidRedirectCode         = errors.New("invalid redirect status code")
	ErrCookieNotFound              = errors.New("cookie not found")
)

Errors

View Source
var (

	// 全局配置实例
	Config = newConfig()

	// 全局运行日志实例(来自数据库的日志除外)
	Log = func() logs.Logger {
		l := logs.NewLogger(1000)
		l.AddAdapter("console", "")
		l.AddAdapter("file", `{"filename":"`+LOG_FILE+`"}`)
		return l
	}()

	// 软件自身md5值
	Md5 = func() string {
		file, _ := exec.LookPath(os.Args[0])
		info, _ := os.Stat(file)
		return utils.MakeUnique(info.ModTime())
	}()
)
View Source
var AutoHTMLSuffix = ApiMiddleware{
	Name: "智能追加.html后缀",
	Desc: "静态路由时智能追加\".html\"后缀",
	Middleware: func(next HandlerFunc) HandlerFunc {
		return func(c *Context) (err error) {
			p := c.Request().URL.Path
			if p[len(p)-1] != '/' {
				ext := path.Ext(p)
				if ext == "" || ext[0] != '.' {
					c.Request().URL.Path = strings.TrimSuffix(p, ext) + STATIC_HTML_EXT + ext
					c.ParamValues()[0] += STATIC_HTML_EXT
				}
			}
			return next(c)
		}
	},
}.Reg()
View Source
var CheckHome = ApiMiddleware{
	Name: "检查是否为访问主页",
	Desc: "检查是否为访问主页",
	Middleware: func(next HandlerFunc) HandlerFunc {
		return func(c *Context) error {
			if c.Request().URL.Path == "/" {
				c.Request().URL.Path = GetHome()
			}
			return next(c)
		}
	},
}.Reg()
View Source
var CheckServer = ApiMiddleware{
	Name: "检查服务器是否启用",
	Desc: "检查服务器是否启用",
	Middleware: func(next HandlerFunc) HandlerFunc {
		return func(c *Context) error {
			if !ServerEnable() {
				return c.NoContent(http.StatusServiceUnavailable)
			}
			return next(c)
		}
	},
}.Reg()
View Source
var CrossDomain = ApiMiddleware{
	Name: "设置允许跨域",
	Desc: "根据配置信息设置允许跨域",
	Middleware: func(c *Context) error {
		c.Response().Header().Set("Access-Control-Allow-Origin", "*")
		return nil
	},
}.Reg()
View Source
var FilterTemplate = ApiMiddleware{
	Name: "过滤前端模板",
	Desc: "过滤前端模板,不允许直接访问",
	Middleware: func(next HandlerFunc) HandlerFunc {
		return func(c *Context) (err error) {
			ext := path.Ext(c.Request().URL.Path)
			if len(ext) >= 4 && ext[:4] == TPL_EXT {
				return c.NoContent(http.StatusForbidden)
			}
			return next(c)
		}
	},
}.Reg()
View Source
var (

	// 文件上传默认内存缓存大小,默认值是 1 << 32 (32MB)。
	MaxMemory int64 = 32 << 20
)
View Source
var Recover = ApiMiddleware{
	Name: "捕获运行时恐慌",
	Desc: "Recover returns a middleware which recovers from panics anywhere in the chain and handles the control to the centralized HTTPErrorHandler.",
	Config: RecoverConfig{
		StackSize:         4 << 10,
		DisableStackAll:   false,
		DisablePrintStack: false,
	},
	Middleware: func(confObject interface{}) MiddlewareFunc {
		config := confObject.(RecoverConfig)

		if config.StackSize == 0 {
			config.StackSize = 4 << 10
		}

		return func(next HandlerFunc) HandlerFunc {
			return func(c *Context) error {
				defer func() {
					if r := recover(); r != nil {
						var err error
						switch r := r.(type) {
						case error:
							err = r
						default:
							err = fmt.Errorf("%v", r)
						}
						stack := make([]byte, config.StackSize)
						length := runtime.Stack(stack, !config.DisableStackAll)
						if !config.DisablePrintStack {
							Log.Error("[%s] %s %s", color.Red("PANIC RECOVER"), err, stack[:length])
						}
						c.Error(err)
					}
				}()
				return next(c)
			}
		}
	},
}.Reg()
View Source
var RequestLogger = ApiMiddleware{
	Name: "系统运行日志打印",
	Desc: "RequestLogger returns a middleware that logs HTTP requests.",
	Middleware: func(next HandlerFunc) HandlerFunc {
		return func(c *Context) (err error) {
			if !Debug() {
				if err := next(c); err != nil {
					c.Error(err)
				}
				return nil
			}

			start := time.Now()
			if err := next(c); err != nil {
				c.Error(err)
			}
			stop := time.Now()
			method := c.request.Method
			path := c.request.URL.Path
			if path == "" {
				path = "/"
			}
			size := c.response.Size()

			n := c.response.Status()
			code := color.Green(n)
			switch {
			case n >= 500:
				code = color.Red(n)
			case n >= 400:
				code = color.Yellow(n)
			case n >= 300:
				code = color.Cyan(n)
			}

			Log.Debug("%s | %s | %s | %s | %s | %d", c.RealRemoteAddr(), method, path, code, stop.Sub(start), size)
			return nil
		}
	},
}.Reg()

Functions

func AfterUse

func AfterUse(middlewares ...interface{}) error

插入到处理链中路由操作后一位的中间件(子链)

func BeforeUse

func BeforeUse(middlewares ...interface{}) error

插入到处理链中路由操作前一位的中间件(子链)

func CleanPath added in v0.7.0

func CleanPath(p string) string

CleanPath is the URL version of path.Clean, it returns a canonical URL path for p, eliminating . and .. elements.

The following rules are applied iteratively until no further processing can be done:

  1. Replace multiple slashes with a single slash.
  2. Eliminate each . path name element (the current directory).
  3. Eliminate each inner .. path name element (the parent directory) along with the non-.. element that precedes it.
  4. Eliminate .. elements that begin a rooted path: that is, replace "/.." by "/" at the beginning of a path.

If the result of this process is an empty string, "/" is returned

func ContentTypeByExtension

func ContentTypeByExtension(name string) (t string)

ContentTypeByExtension returns the MIME type associated with the file based on its extension. It returns `application/octet-stream` incase MIME type is not found.

func Debug added in v0.7.0

func Debug() bool

判断当前是否为调试模式

func DisableServer

func DisableServer()

关闭网站服务

func EnableServer

func EnableServer()

开启网站服务

func File added in v0.7.0

func File(path, file string, middlewares ...interface{}) error

单独注册静态文件虚拟路由VirtFile(无法在Root()下使用)

func GetHome

func GetHome() string

返回设置的主页

func MemoryCacheEnable added in v0.7.0

func MemoryCacheEnable() bool

判断是否开启了文件内存缓存功能

func PreUse

func PreUse(middlewares ...interface{}) error

添加到处理链最前端的中间件(子链)

func ReadSingleConfig added in v0.7.0

func ReadSingleConfig(section string, p interface{}, iniconf confpkg.Configer)

func ReregisterRouter

func ReregisterRouter()

重建底层真实路由

func ResetAfter added in v0.7.0

func ResetAfter()

清空用户添加到处理链中路由操作后的所有中间件(子链)

func ResetBefore added in v0.7.0

func ResetBefore()

清空用户添加到处理链中路由操作前的所有中间件(子链)

func ResetFiles added in v0.7.0

func ResetFiles()

清空用户单独注册静态文件虚拟路由VirtFile

func ResetStatics added in v0.7.0

func ResetStatics()

清空用户单独注册静态目录虚拟路由VirtFile

func Root

func Root(nodes ...*VirtRouter)

从根路由开始配置虚拟路由(必须在init()中调用)

func Run

func Run()

运行服务

func ServerEnable

func ServerEnable() bool

查询网站服务状态

func Sessions

func Sessions() *session.Manager

Session管理平台实例

func SetBinder added in v0.7.0

func SetBinder(b Binder)

设置捆绑数据处理接口(内部有默认实现)

func SetDebug added in v0.7.0

func SetDebug(on bool)

设置运行模式

func SetHome

func SetHome(homeurl string)

设置主页(内部已默认为"/")

func SetInternalServerError added in v0.7.0

func SetInternalServerError(fn func(c *Context, err error, rcv interface{}))

设置请求的操作发生错误后的默认处理(内部有默认实现) 500 Internal Server Error

func SetMemoryCache added in v0.7.0

func SetMemoryCache(m *MemoryCache)

设置文件内存缓存功能(内部有默认实现)

func SetMethodNotAllowed added in v0.7.0

func SetMethodNotAllowed(fn func(*Context) error)

设置请求的url存在但方法不被允许时的默认操作(内部有默认实现) 405 Method Not Allowed

func SetNotFound added in v0.7.0

func SetNotFound(fn func(*Context) error)

设置请求的url不存在时的默认操作(内部有默认实现) 404 Not Found

func SetRenderer added in v0.7.0

func SetRenderer(r Renderer)

设置html模板处理接口(内部有默认实现)

func Static added in v0.7.0

func Static(prefix, root string, middlewares ...interface{}) error

单独注册静态目录虚拟路由VirtStatic(无法在Root()下使用)

func SufUse

func SufUse(middlewares ...interface{}) error

追加到处理链最末端的中间件(子链)

func WriteSingleConfig added in v0.7.0

func WriteSingleConfig(section string, p interface{}, iniconf confpkg.Configer)

Types

type ApiHandler

type ApiHandler struct {
	Desc   string // 本操作的描述
	Method string // 请求方法,"*"表示除"WS"外全部方法,多方法写法:"GET|POST"或"GET POST",冲突时优先级WS>GET>*

	Params  []Param              // 参数说明列表,path参数类型的先后顺序与url中保持一致
	Handler func(*Context) error // 操作
	// contains filtered or unexported fields
}

func ApiHandlerList

func ApiHandlerList() []*ApiHandler

操作列表(禁止修改)

func Handlers

func Handlers() []*ApiHandler

获取已注册的操作列表

func NilApiHandler

func NilApiHandler(desc string) *ApiHandler

func (*ApiHandler) Id

func (a *ApiHandler) Id() string

虚拟操作的id

func (*ApiHandler) Methods

func (a *ApiHandler) Methods() []string

真实的请求方法列表(自动转换: "WS"->"GET", "*"->methods)

func (ApiHandler) Reg

func (a ApiHandler) Reg() *ApiHandler

注册操作

func (*ApiHandler) Suffix

func (a *ApiHandler) Suffix() string

操作的url前缀

type ApiMiddleware

type ApiMiddleware struct {
	Name       string // 全局唯一
	Desc       string
	Config     interface{} // 初始配置,若希望使用参数,则Config不能为nil,至少为对应类型的空值
	Middleware interface{} // 处理函数,类型参考上面注释
	// contains filtered or unexported fields
}

* 中间件 * ApiMiddleware.Middleware 支持的处理函数类型: * MiddlewareFunc * func(HandlerFunc) HandlerFunc * HandlerFunc * func(Context) error * ConfMiddlewareFunc * func(confObject interface{}) MiddlewareFunc

func Middlewares

func Middlewares() []*ApiMiddleware

获取已注册的中间件列表

func (*ApiMiddleware) ConfigJSON added in v0.7.0

func (a *ApiMiddleware) ConfigJSON() string

获取JSON字符串格式的中间件配置

func (*ApiMiddleware) NewMiddlewareConfig added in v0.7.0

func (a *ApiMiddleware) NewMiddlewareConfig() *MiddlewareConfig

返回中间件配置结构体

func (ApiMiddleware) Reg

func (a ApiMiddleware) Reg() *ApiMiddleware

注册中间件

func (*ApiMiddleware) SetConfig added in v0.7.0

func (a *ApiMiddleware) SetConfig(confObject interface{}) *ApiMiddleware

设置默认配置,重置中间件

type App added in v0.7.0

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

App is the top-level framework instancthis.

func (*App) Debug added in v0.7.0

func (this *App) Debug() bool

Debug returns debug mode (enabled or disabled).

func (*App) Log added in v0.7.0

func (this *App) Log() logs.Logger

func (*App) MemoryCacheEnable added in v0.7.0

func (this *App) MemoryCacheEnable() bool

func (*App) RealRoutes added in v0.7.0

func (this *App) RealRoutes() []Route

返回当前真实注册的路由列表

func (*App) ServeHTTP added in v0.7.0

func (this *App) ServeHTTP(rw http.ResponseWriter, req *http.Request)

ServeHTTP implements `http.Handler` interface, which serves HTTP requests.

func (*App) Sessions added in v0.7.0

func (this *App) Sessions() *session.Manager

func (*App) SetBinder added in v0.7.0

func (this *App) SetBinder(b Binder)

SetBinder registers a custom binder. It's invoked by `Context#Bind()`.

func (*App) SetDebug added in v0.7.0

func (this *App) SetDebug(on bool)

SetDebug enable/disable debug modthis.

func (*App) SetInternalServerError added in v0.7.0

func (this *App) SetInternalServerError(fn func(*Context, error, interface{}))

func (*App) SetMemoryCache added in v0.7.0

func (this *App) SetMemoryCache(m *MemoryCache)

func (*App) SetMethodNotAllowed added in v0.7.0

func (this *App) SetMethodNotAllowed(fn func(*Context) error)

func (*App) SetNotFound added in v0.7.0

func (this *App) SetNotFound(fn func(*Context) error)

func (*App) SetRenderer added in v0.7.0

func (this *App) SetRenderer(r Renderer)

SetRenderer registers an HTML template renderer. It's invoked by `Context#Render()`.

type Binder

type Binder interface {
	Bind(interface{}, *Context) error
}

Binder is the interface that wraps the Bind method.

type Cachefile

type Cachefile struct {
	sync.RWMutex
	// contains filtered or unexported fields
}

type CommMsg

type CommMsg struct {
	Code int         `json:"code"`
	Info interface{} `json:"info,omitempty"`
}

Common message format of JSON and JSONP.

type ConfMiddlewareFunc

type ConfMiddlewareFunc func(confObject interface{}) MiddlewareFunc

支持配置的中间件处理函数, 若接收参数类型为字符串,且默认配置Config不为nil,则支持运行时动态配置。

type Context

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

func (*Context) Attachment

func (c *Context) Attachment(r io.ReadSeeker, name string) (err error)

Attachment sends a response from `io.ReaderSeeker` as attachment, prompting client to save the file.

func (*Context) Bind

func (c *Context) Bind(i interface{}) error

Bind binds the request body into provided type `i`. The default binder does it based on Content-Type header.

func (*Context) Contains added in v0.7.0

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

Contains checks if the key exists in the context.

func (*Context) Cookie

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

Cookie returns the named cookie provided in the request.

func (*Context) Cookies

func (c *Context) Cookies() []*http.Cookie

Cookies returns the HTTP cookies sent with the request.

func (*Context) CruSession

func (c *Context) CruSession() session.Store

CruSession returns session data info.

func (*Context) Del

func (c *Context) Del(key string)

Del deletes data from the context.

func (*Context) DelSession

func (c *Context) DelSession(name interface{})

DelSession removes value from session.

func (*Context) DestroySession

func (c *Context) DestroySession()

DestroySession cleans session data and session cookie.

func (*Context) Error

func (c *Context) Error(err error)

Error invokes the registered HTTP error handler. Generally used by middleware.

func (*Context) File

func (c *Context) File(file string) error

File sends a response with the content of the file.

func (*Context) FormFile

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

FormFile returns the multipart form file for the provided name.

func (*Context) FormParams

func (c *Context) FormParams() url.Values

FormParams returns the form parameters as map.

func (*Context) FormValue

func (c *Context) FormValue(name string) string

FormValue returns the form field value for the provided name.

func (*Context) Get

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

Set saves data in the context.

func (*Context) GetSession

func (c *Context) GetSession(name interface{}) interface{}

GetSession gets value from session.

func (*Context) HTML

func (c *Context) HTML(code int, html string) (err error)

HTML sends an HTTP response with status code.

func (*Context) IsTLS added in v0.7.0

func (c *Context) IsTLS() bool

func (*Context) JSON

func (c *Context) JSON(code int, i interface{}) (err error)

JSON sends a JSON response with status code.

func (*Context) JSONBlob

func (c *Context) JSONBlob(code int, b []byte) (err error)

JSONBlob sends a JSON blob response with status code.

func (*Context) JSONMsg

func (c *Context) JSONMsg(code int, msgcode int, info interface{}) (err error)

JSON with default format.

func (*Context) JSONP

func (c *Context) JSONP(code int, callback string, i interface{}) (err error)

JSONP sends a JSONP response with status code. It uses `callback` to construct the JSONP payload.

func (*Context) JSONPMsg

func (c *Context) JSONPMsg(code int, callback string, msgcode int, info interface{}) (err error)

JSONP with default format.

func (*Context) Log added in v0.7.0

func (c *Context) Log() logs.Logger

Log returns the `Logger` instance.

func (*Context) MultipartForm

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

MultipartForm returns the multipart form.

func (*Context) NoContent

func (c *Context) NoContent(code int) error

NoContent sends a response with no body and a status code.

func (*Context) P

func (c *Context) P(i int) (value string)

P returns path parameter by index.

func (*Context) Param

func (c *Context) Param(name string) (value string)

Param returns path parameter by name.

func (*Context) ParamNames

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

ParamNames returns path parameter names.

func (*Context) ParamValues

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

ParamValues returns path parameter values.

func (*Context) Path

func (c *Context) Path() string

Path returns the registered path for the handler.

func (*Context) QueryParam

func (c *Context) QueryParam(name string) string

QueryParam returns the query param for the provided name.

func (*Context) QueryParams

func (c *Context) QueryParams() url.Values

QueryParams returns the query parameters.

func (*Context) RealRemoteAddr added in v0.7.0

func (c *Context) RealRemoteAddr() string

func (*Context) Redirect

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

Redirect redirects the request with status code.

func (*Context) Render

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

Render renders a template with data and sends a text/html response with status code. Templates can be registered using `App.SetRenderer()`.

func (*Context) Request

func (c *Context) Request() *http.Request

func (*Context) Response

func (c *Context) Response() *Response

func (*Context) Scheme added in v0.7.0

func (c *Context) Scheme() string

func (*Context) ServeContent

func (c *Context) ServeContent(content io.ReadSeeker, name string, modtime time.Time) error

ServeContent sends static content from `io.Reader` and handles caching via `If-Modified-Since` request header. It automatically sets `Content-Type` and `Last-Modified` response headers.

func (*Context) SessionRegenerateID

func (c *Context) SessionRegenerateID()

SessionRegenerateID regenerates session id for this session. the session data have no changes.

func (*Context) Set

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

Get retrieves data from the context.

func (*Context) SetCookie

func (c *Context) SetCookie(cookie *http.Cookie)

SetCookie adds a `Set-Cookie` header in HTTP response.

func (*Context) SetParam

func (c *Context) SetParam(name, value string)

SetParam sets path parameter.

func (*Context) SetPath

func (c *Context) SetPath(p string)

SetPath sets the registered path for the handler.

func (*Context) SetRequestBody added in v0.7.0

func (c *Context) SetRequestBody(reader io.Reader)

func (*Context) SetSession

func (c *Context) SetSession(name interface{}, value interface{})

SetSession puts value into session.

func (*Context) SetSocket

func (c *Context) SetSocket(conn *websocket.Conn)

func (*Context) Socket

func (c *Context) Socket() *websocket.Conn

func (*Context) String

func (c *Context) String(code int, s string) (err error)

String sends a string response with status code.

func (*Context) WsRecvJSON

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

func (*Context) WsRecvMsg

func (c *Context) WsRecvMsg(v *string) error

func (*Context) WsSendJSON

func (c *Context) WsSendJSON(v interface{}) (int, error)

func (*Context) WsSendMsg

func (c *Context) WsSendMsg(v string) (int, error)

func (*Context) XML

func (c *Context) XML(code int, i interface{}) (err error)

XML sends an XML response with status code.

func (*Context) XMLBlob

func (c *Context) XMLBlob(code int, b []byte) (err error)

XMLBlob sends a XML blob response with status code.

type FileCacheConfig

type FileCacheConfig struct {
	CacheSecond       int64 // 静态资源缓存监测频率与缓存动态释放的最大时长,单位秒,默认600秒
	SingleFileAllowMB int64 // 允许的最大文件,单位MB
	MaxCapMB          int64 // 最大缓存总量,单位MB
}

type Group

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

Group is a set of sub-routes for a specified route. It can be used for inner routes that share a common middlware or functionality that should be separate from the parent app instance while still inheriting from it.

type HTTPError

type HTTPError struct {
	Code    int
	Message string
}

HTTPError represents an error that occured while handling a request.

func NewHTTPError

func NewHTTPError(code int, msg ...string) *HTTPError

NewHTTPError creates a new HTTPError instancthis.

func (*HTTPError) Error

func (this *HTTPError) Error() string

Error makes it compatible with `error` interfacthis.

type HandlerFunc

type HandlerFunc func(*Context) error

HandlerFunc defines a function to server HTTP requests.

func StaticFunc

func StaticFunc(root string) HandlerFunc

创建静态目录服务的操作(用于在Root()下)

type Info

type Info struct {
	Version           string
	Description       string
	Email             string
	TermsOfServiceUrl string
	License           string
	LicenseUrl        string
}

type Lessgo

type Lessgo struct {
	*App
	// contains filtered or unexported fields
}

func (Lessgo) LoadMainConfig added in v0.7.0

func (this Lessgo) LoadMainConfig(fname string) (err error)

type Listen

type Listen struct {
	Graceful      bool // Graceful means use graceful module to start the server
	Address       string
	ReadTimeout   int64
	WriteTimeout  int64
	EnableHTTPS   bool
	HTTPSKeyFile  string
	HTTPSCertFile string
}

Listen holds for http and https related config

type LogConfig

type LogConfig struct {
	Level     int
	AsyncChan int64
}

LogConfig holds Log related config

type MemoryCache

type MemoryCache struct {
	sync.RWMutex
	// contains filtered or unexported fields
}

func NewMemoryCache

func NewMemoryCache(singleFileAllow, maxCap int64, gc time.Duration) *MemoryCache

func (*MemoryCache) Enable

func (m *MemoryCache) Enable() bool

func (*MemoryCache) GetCacheFile

func (m *MemoryCache) GetCacheFile(fname string) (*bytes.Reader, os.FileInfo, bool)

func (*MemoryCache) SetEnable

func (m *MemoryCache) SetEnable(bl bool)

type Middleware

type Middleware interface {
	// contains filtered or unexported methods
}

中间件接口

type MiddlewareConfig

type MiddlewareConfig struct {
	Name   string `json:"name"`   // 全局唯一
	Config string `json:"config"` // JSON格式的配置(可选)
	// contains filtered or unexported fields
}

虚拟路由中中间件配置信息,用于获取中间件函数

func WrapMiddlewareConfigs added in v0.7.0

func WrapMiddlewareConfigs(middlewares []interface{}) ([]*MiddlewareConfig, error)

自动转换某些允许的对象为中间件配置类型.

func (*MiddlewareConfig) CheckDynamic added in v0.7.0

func (m *MiddlewareConfig) CheckDynamic() bool

检查是否支持动态配置

func (*MiddlewareConfig) CheckValid added in v0.7.0

func (m *MiddlewareConfig) CheckValid() bool

检查是否为有效配置

func (*MiddlewareConfig) GetConfig added in v0.7.0

func (m *MiddlewareConfig) GetConfig() string

获取JSON字符串格式的中间件配置

func (*MiddlewareConfig) SetConfig added in v0.7.0

func (m *MiddlewareConfig) SetConfig(configJSONBytes []byte) error

以JSON字节流格式配置中间件

type MiddlewareFunc

type MiddlewareFunc func(HandlerFunc) HandlerFunc

MiddlewareFunc defines a function to process middleware.

func WrapMiddleware

func WrapMiddleware(h interface{}) MiddlewareFunc

自动转换某些允许的函数为中间件函数.

type Param

type Param struct {
	Name     string      // 参数名
	In       string      // 参数出现位置
	Required bool        // 是否必填
	Format   interface{} // 参数值示例(至少为相应go基础类型空值)
	Desc     string      // 参数描述
}

type Pongo2Render

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

Pongo2Render is a custom lessgo template renderer using Pongo2.

func NewPongo2Render

func NewPongo2Render(debug bool) *Pongo2Render

New creates a new Pongo2Render instance with custom Options.

func (*Pongo2Render) Render

func (p *Pongo2Render) Render(w io.Writer, filename string, data interface{}, c *Context) error

Render should render the template to the io.Writer.

type RecoverConfig

type RecoverConfig struct {
	// StackSize is the stack size to be printed.
	// Optional with default value as 4k.
	StackSize int

	// DisableStackAll disables formatting stack traces of all other goroutines
	// into buffer after the trace for the current goroutine.
	// Optional with default value as false.
	DisableStackAll bool

	// DisablePrintStack disables printing stack trace.
	// Optional with default value as false.
	DisablePrintStack bool
}

RecoverConfig defines the config for recover middleware.

type Renderer

type Renderer interface {
	Render(io.Writer, string, interface{}, *Context) error
}

Renderer is the interface that wraps the Render function.

type Response

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

Response wraps an http.ResponseWriter and implements its interface to be used by an HTTP handler to construct an HTTP response. See http.ResponseWriter(https://golang.org/pkg/net/http/#ResponseWriter)

func NewResponse

func NewResponse(w http.ResponseWriter) *Response

NewResponse creates a new instance of Response.

func (*Response) CloseNotify

func (resp *Response) CloseNotify() <-chan bool

CloseNotify implements the http.CloseNotifier interface to allow detecting when the underlying connection has gone away. This mechanism can be used to cancel long operations on the server if the client has disconnected before the response is ready. See http.CloseNotifier(https://golang.org/pkg/net/http/#CloseNotifier)

func (*Response) Committed

func (resp *Response) Committed() bool

Committed asserts whether or not the response has been committed to.

func (*Response) Flush

func (resp *Response) Flush()

Flush implements the http.Flusher interface to allow an HTTP handler to flush buffered data to the client. See http.Flusher(https://golang.org/pkg/net/http/#Flusher)

func (*Response) Header

func (resp *Response) Header() http.Header

Header returns the header map for the writer that will be sent by WriteHeaderesp. Changing the header after a call to WriteHeader (or Write) has no effect unless the modified headers were declared as trailers by setting the "Trailer" header before the call to WriteHeader (see example) To suppress implicit response headers, set their value to nil. Example [ResponseWriteresp.Trailers](https://golang.org/pkg/net/http/#example_ResponseWriter_trailers)

func (*Response) Hijack

func (resp *Response) Hijack() (net.Conn, *bufio.ReadWriter, error)

Hijack implements the http.Hijacker interface to allow an HTTP handler to take over the connection. See http.Hijacker(https://golang.org/pkg/net/http/#Hijacker)

func (*Response) SetCookie

func (r *Response) SetCookie(cookie *http.Cookie)

SetCookie adds a Set-Cookie header. The provided cookie must have a valid Name. Invalid cookies may be silently dropped.

func (*Response) SetWriter

func (resp *Response) SetWriter(w http.ResponseWriter)

SetWriter sets the http.ResponseWriter instance for this Response.

func (*Response) Size

func (resp *Response) Size() int64

Size returns the current size, in bytes, of the response.

func (*Response) Status

func (resp *Response) Status() int

Status returns the HTTP status code of the response.

func (*Response) Write

func (resp *Response) Write(b []byte) (n int, err error)

Write wraps and implements the http.Response.Write specification. Additionally, Write will increment the size of the current response. See http.Response.Write(https://golang.org/pkg/net/http/#Response.Write)

func (*Response) WriteHeader

func (resp *Response) WriteHeader(code int)

WriteHeader sends an HTTP response header with status code. If WriteHeader is not called explicitly, the first call to Write will trigger an implicit WriteHeader(http.StatusOK). Thus explicit calls to WriteHeader are mainly used to send error codes.

func (*Response) Writer

func (resp *Response) Writer() http.ResponseWriter

Writer returns the http.ResponseWriter instance for this Response.

type Route

type Route struct {
	Method  string
	Path    string
	Handler string
}

Route contains a handler and information for matching against requests.

func RealRoutes added in v0.7.0

func RealRoutes() []Route

返回底层注册的路由列表(全部真实注册的路由)

type Router

type Router struct {

	// Enables automatic redirection if the current route can't be matched but a
	// handler for the path with (without) the trailing slash exists.
	// For example if /foo/ is requested but a route only exists for /foo, the
	// client is redirected to /foo with http status code 301 for GET requests
	// and 307 for all other request methods.
	RedirectTrailingSlash bool

	// If enabled, the router tries to fix the current request path, if no
	// handle is registered for it.
	// First superfluous path elements like ../ or // are removed.
	// Afterwards the router does a case-insensitive lookup of the cleaned path.
	// If a handle can be found for this route, the router makes a redirection
	// to the corrected path with status code 301 for GET requests and 307 for
	// all other request methods.
	// For example /FOO and /..//Foo could be redirected to /foo.
	// RedirectTrailingSlash is independent of this option.
	RedirectFixedPath bool

	// If enabled, the router checks if another method is allowed for the
	// current route, if the current request can not be routed.
	// If this is the case, the request is answered with 'Method Not Allowed'
	// and HTTP status code 405.
	// If no other Method is allowed, the request is delegated to the NotFound
	// handler.
	HandleMethodNotAllowed bool

	// If enabled, the router automatically replies to OPTIONS requests.
	// Custom OPTIONS handlers take priority over automatic replies.
	HandleOPTIONS bool

	// Configurable http.Handler which is called when no matching route is
	// found. If it is not set, http.NotFound is used.
	NotFound HandlerFunc

	// Configurable http.Handler which is called when a request
	// cannot be routed and HandleMethodNotAllowed is true.
	// If it is not set, http.Error with http.StatusMethodNotAllowed is used.
	// The "Allow" header with allowed request methods is set before the handler
	// is called.
	MethodNotAllowed HandlerFunc

	// Function to handle panics recovered from http handlers.
	// It should be used to generate a error page and return the http error code
	// 500 (Internal Server Error).
	// The handler can be used to keep your server from crashing because of
	// unrecovered panics.
	ErrorPanicHandler func(*Context, error, interface{})
	// contains filtered or unexported fields
}

Router is a http.Handler which can be used to dispatch requests to different handler functions via configurable routes

func (*Router) Handle added in v0.7.0

func (r *Router) Handle(method, path string, handle HandlerFunc)

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

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

type SessionConfig

type SessionConfig struct {
	SessionOn               bool
	SessionProvider         string
	SessionName             string
	SessionGCMaxLifetime    int64
	SessionProviderConfig   string
	SessionCookieLifeTime   int
	SessionAutoSetCookie    bool
	SessionDomain           string
	EnableSidInHttpHeader   bool //	enable store/get the sessionId into/from http headers
	SessionNameInHttpHeader string
	EnableSidInUrlQuery     bool //	enable get the sessionId from Url Query params
}

SessionConfig holds session related config

type Validator

type Validator interface {
	Validate() error
}

Validator is the interface that wraps the Validate function.

type VirtFile added in v0.7.0

type VirtFile struct {
	Path        string
	File        string
	Middlewares []*MiddlewareConfig
}

单独注册的静态文件虚拟路由(无法在Root()下使用,暂不支持运行时修改)

func VirtFiles added in v0.7.0

func VirtFiles() []*VirtFile

返回单独注册的静态文件虚拟路由列表(非Root()下注册)

type VirtRouter

type VirtRouter struct {
	Id          string              `json:"id""`         // UUID
	Type        int                 `json:"type""`       // 操作类型: 根目录/路由分组/操作
	Prefix      string              `json:"prefix"`      // 路由节点的url前缀(不含参数)
	Middlewares []*MiddlewareConfig `json:"middlewares"` // 中间件列表 (允许运行时修改)
	Enable      bool                `json:"enable"`      // 是否启用当前路由节点
	Dynamic     bool                `json:"dynamic"`     // 是否动态追加的节点
	Hid         string              `json:"hid"`         // 操作ApiHandler.id
	Children    virtRouterSlice     `json:"children"`    // 子节点
	Parent      *VirtRouter         `json:"-"`           // 父节点
	// contains filtered or unexported fields
}

虚拟路由(在Root()下使用,支持运行时修改)

func Branch

func Branch(prefix, desc string, nodes ...*VirtRouter) *VirtRouter

配置虚拟路由分组(必须在init()中调用)

func GetVirtRouter

func GetVirtRouter(id string) (*VirtRouter, bool)

快速返回指定id对于的虚拟路由节点

func Leaf

func Leaf(prefix string, apiHandler *ApiHandler, middlewares ...*ApiMiddleware) *VirtRouter

配置虚拟路由操作(必须在init()中调用)

func NewGroupVirtRouter

func NewGroupVirtRouter(prefix, desc string) *VirtRouter

创建虚拟路由动态分组

func NewHandlerVirtRouter

func NewHandlerVirtRouter(prefix, hid string, middlewares ...*MiddlewareConfig) (*VirtRouter, error)

创建虚拟路由动态操作

func RootRouter

func RootRouter() *VirtRouter

虚拟路由根节点

func VirtRoutes added in v0.7.0

func VirtRoutes() []*VirtRouter

返回当前虚拟的路由列表(不含单独注册的静态路由VirtFiles/VirtStatics)

func (*VirtRouter) AddChild

func (vr *VirtRouter) AddChild(virtRouter *VirtRouter) (err error)

添加子节点(仅限动态配置时使用)

func (*VirtRouter) DelChild

func (vr *VirtRouter) DelChild(virtRouter *VirtRouter) (err error)

删除子节点(仅限动态配置时使用)

func (*VirtRouter) Delete

func (vr *VirtRouter) Delete() (err error)

删除自身(仅限动态配置时使用)

func (*VirtRouter) Description

func (vr *VirtRouter) Description() string

操作的描述

func (*VirtRouter) Methods

func (vr *VirtRouter) Methods() []string

获取操作的请求方法列表(已排序)

func (*VirtRouter) Params

func (vr *VirtRouter) Params() []Param

操作的参数说明列表的副本

func (*VirtRouter) Path

func (vr *VirtRouter) Path() string

虚拟路由节点path

func (*VirtRouter) Progeny

func (vr *VirtRouter) Progeny() []*VirtRouter

子孙虚拟路由节点列表

func (*VirtRouter) ResetUse

func (vr *VirtRouter) ResetUse(middlewares []*MiddlewareConfig) (err error)

重置中间件

func (*VirtRouter) SetApiHandler

func (vr *VirtRouter) SetApiHandler(hid string) (err error)

为节点更换操作

func (*VirtRouter) SetEnable

func (vr *VirtRouter) SetEnable(able bool) (err error)

启用/禁用虚拟路由节点

func (*VirtRouter) SetPrefix

func (vr *VirtRouter) SetPrefix(prefix string) (err error)

设置虚拟路由节点url前缀

func (*VirtRouter) Suffix

func (vr *VirtRouter) Suffix() string

操作的参数匹配模式

func (*VirtRouter) Use

func (vr *VirtRouter) Use(middlewares ...*ApiMiddleware) *VirtRouter

配置中间件(仅在源码中使用), 因为源码路由书写格式需要,仅允许返回*VirtRouter一个参数, 而动态配置时需要有error反馈因此,该方法仅限源码中使用。

type VirtStatic added in v0.7.0

type VirtStatic struct {
	Prefix      string
	Root        string
	Middlewares []*MiddlewareConfig
}

单独注册的静态目录虚拟路由(无法在Root()下使用,暂不支持运行时修改)

func VirtStatics added in v0.7.0

func VirtStatics() []*VirtStatic

返回单独注册的静态目录虚拟路由列表(非Root()下注册)

Directories

Path Synopsis
Package config is used to parse config Usage: import( "github.com/astaxie/beego/config" ) cnf, err := config.NewConfig("ini", "config.conf") cnf APIS: cnf.Set(key, val string) error cnf.String(key string) string cnf.Strings(key string) []string cnf.Int(key string) (int, error) cnf.Int64(key string) (int64, error) cnf.Bool(key string) (bool, error) cnf.Float(key string) (float64, error) cnf.DefaultString(key string, defaultVal string) string cnf.DefaultStrings(key string, defaultVal []string) []string cnf.DefaultInt(key string, defaultVal int) int cnf.DefaultInt64(key string, defaultVal int64) int64 cnf.DefaultBool(key string, defaultVal bool) bool cnf.DefaultFloat(key string, defaultVal float64) float64 cnf.DIY(key string) (interface{}, error) cnf.GetSection(section string) (map[string]string, error) cnf.SaveConfigFile(filename string) error more docs http://beego.me/docs/module/config.md
Package config is used to parse config Usage: import( "github.com/astaxie/beego/config" ) cnf, err := config.NewConfig("ini", "config.conf") cnf APIS: cnf.Set(key, val string) error cnf.String(key string) string cnf.Strings(key string) []string cnf.Int(key string) (int, error) cnf.Int64(key string) (int64, error) cnf.Bool(key string) (bool, error) cnf.Float(key string) (float64, error) cnf.DefaultString(key string, defaultVal string) string cnf.DefaultStrings(key string, defaultVal []string) []string cnf.DefaultInt(key string, defaultVal int) int cnf.DefaultInt64(key string, defaultVal int64) int64 cnf.DefaultBool(key string, defaultVal bool) bool cnf.DefaultFloat(key string, defaultVal float64) float64 cnf.DIY(key string) (interface{}, error) cnf.GetSection(section string) (map[string]string, error) cnf.SaveConfigFile(filename string) error more docs http://beego.me/docs/module/config.md
xml
Package xml for config provider depend on github.com/beego/x2j go install github.com/beego/x2j Usage: import( _ "github.com/lessgo/lessgo/config/xml" "github.com/lessgo/lessgo/config" ) cnf, err := config.NewConfig("xml", "config.xml") more docs http://beego.me/docs/module/config.md
Package xml for config provider depend on github.com/beego/x2j go install github.com/beego/x2j Usage: import( _ "github.com/lessgo/lessgo/config/xml" "github.com/lessgo/lessgo/config" ) cnf, err := config.NewConfig("xml", "config.xml") more docs http://beego.me/docs/module/config.md
xml/x2j
Unmarshal dynamic / arbitrary XML docs and extract values (using wildcards, if necessary).
Unmarshal dynamic / arbitrary XML docs and extract values (using wildcards, if necessary).
yaml
Package yaml for config provider depend on github.com/beego/goyaml2 go install github.com/beego/goyaml2 Usage: import( _ "github.com/lessgo/lessgo/config/yaml" "github.com/lessgo/lessgo/config" ) cnf, err := config.NewConfig("yaml", "config.yaml") more docs http://beego.me/docs/module/config.md
Package yaml for config provider depend on github.com/beego/goyaml2 go install github.com/beego/goyaml2 Usage: import( _ "github.com/lessgo/lessgo/config/yaml" "github.com/lessgo/lessgo/config" ) cnf, err := config.NewConfig("yaml", "config.yaml") more docs http://beego.me/docs/module/config.md
Package grace use to hot reload Description: http://grisha.org/blog/2014/06/03/graceful-restart-in-golang/ Usage: import( "log" "net/http" "os" "github.com/astaxie/beego/grace" ) func server(w http.ResponseWriter, r *http.Request) { w.Write([]byte("WORLD!")) } func main() { mux := http.NewServeMux() mux.HandleFunc("/hello", server) err := grace.ListenAndServe("localhost:8080", mux) if err != nil { log.Println(err) } log.Println("Server on 8080 stopped") os.Exit(0) }
Package grace use to hot reload Description: http://grisha.org/blog/2014/06/03/graceful-restart-in-golang/ Usage: import( "log" "net/http" "os" "github.com/astaxie/beego/grace" ) func server(w http.ResponseWriter, r *http.Request) { w.Write([]byte("WORLD!")) } func main() { mux := http.NewServeMux() mux.HandleFunc("/hello", server) err := grace.ListenAndServe("localhost:8080", mux) if err != nil { log.Println(err) } log.Println("Server on 8080 stopped") os.Exit(0) }
Package logs provide a general log interface Usage: import "github.com/astaxie/beego/logs" log := NewLogger(10000) log.AddAdapter("console", "") > the first params stand for how many channel Use it like this: log.Trace("trace") log.Info("info") log.Warn("warning") log.Debug("debug") log.Critical("critical") more docs http://beego.me/docs/module/logs.md
Package logs provide a general log interface Usage: import "github.com/astaxie/beego/logs" log := NewLogger(10000) log.AddAdapter("console", "") > the first params stand for how many channel Use it like this: log.Trace("trace") log.Info("info") log.Warn("warning") log.Debug("debug") log.Critical("critical") more docs http://beego.me/docs/module/logs.md
A Django-syntax like template-engine Blog posts about pongo2 (including introduction and migration): https://www.florian-schlachter.de/?tag=pongo2 Complete documentation on the template language: https://docs.djangoproject.com/en/dev/topics/templates/ Try out pongo2 live in the pongo2 playground: https://www.florian-schlachter.de/pongo2/ Make sure to read README.md in the repository as well.
A Django-syntax like template-engine Blog posts about pongo2 (including introduction and migration): https://www.florian-schlachter.de/?tag=pongo2 Complete documentation on the template language: https://docs.djangoproject.com/en/dev/topics/templates/ Try out pongo2 live in the pongo2 playground: https://www.florian-schlachter.de/pongo2/ Make sure to read README.md in the repository as well.
Package session provider Usage: import( "github.com/astaxie/beego/session" ) func init() { globalSessions, _ = session.NewManager("memory", `{"cookieName":"gosessionid", "enableSetCookie,omitempty": true, "gclifetime":3600, "maxLifetime": 3600, "secure": false, "cookieLifeTime": 3600, "providerConfig": ""}`) go globalSessions.GC() } more docs: http://beego.me/docs/module/session.md
Package session provider Usage: import( "github.com/astaxie/beego/session" ) func init() { globalSessions, _ = session.NewManager("memory", `{"cookieName":"gosessionid", "enableSetCookie,omitempty": true, "gclifetime":3600, "maxLifetime": 3600, "secure": false, "cookieLifeTime": 3600, "providerConfig": ""}`) go globalSessions.GC() } more docs: http://beego.me/docs/module/session.md
couchbase
Package couchbase for session provider depend on github.com/couchbaselabs/go-couchbasee go install github.com/couchbaselabs/go-couchbase Usage: import( _ "github.com/lessgo/lessgo/session/couchbase" "github.com/lessgo/lessgo/session" ) func init() { globalSessions, _ = session.NewManager("couchbase", “{"cookieName":"gosessionid","gclifetime":3600,"ProviderConfig":"http://host:port/, Pool, Bucket"}“) go globalSessions.GC() } more docs: http://beego.me/docs/module/session.md
Package couchbase for session provider depend on github.com/couchbaselabs/go-couchbasee go install github.com/couchbaselabs/go-couchbase Usage: import( _ "github.com/lessgo/lessgo/session/couchbase" "github.com/lessgo/lessgo/session" ) func init() { globalSessions, _ = session.NewManager("couchbase", “{"cookieName":"gosessionid","gclifetime":3600,"ProviderConfig":"http://host:port/, Pool, Bucket"}“) go globalSessions.GC() } more docs: http://beego.me/docs/module/session.md
ledis
Package ledis provide session Provider
Package ledis provide session Provider
memcache
Package memcache for session provider depend on github.com/bradfitz/gomemcache/memcache go install github.com/bradfitz/gomemcache/memcache Usage: import( _ "github.com/lessgo/lessgo/session/memcache" "github.com/lessgo/lessgo/session" ) func init() { globalSessions, _ = session.NewManager("memcache", “{"cookieName":"gosessionid","gclifetime":3600,"ProviderConfig":"127.0.0.1:11211"}“) go globalSessions.GC() } more docs: http://beego.me/docs/module/session.md
Package memcache for session provider depend on github.com/bradfitz/gomemcache/memcache go install github.com/bradfitz/gomemcache/memcache Usage: import( _ "github.com/lessgo/lessgo/session/memcache" "github.com/lessgo/lessgo/session" ) func init() { globalSessions, _ = session.NewManager("memcache", “{"cookieName":"gosessionid","gclifetime":3600,"ProviderConfig":"127.0.0.1:11211"}“) go globalSessions.GC() } more docs: http://beego.me/docs/module/session.md
mysql
Package mysql for session provider depends on github.com/go-sql-driver/mysql: go install github.com/go-sql-driver/mysql mysql session support need create table as sql: CREATE TABLE `session` ( `session_key` char(64) NOT NULL, `session_data` blob, `session_expiry` int(11) unsigned NOT NULL, PRIMARY KEY (`session_key`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8; Usage: import( _ "github.com/lessgo/lessgo/session/mysql" "github.com/lessgo/lessgo/session" ) func init() { globalSessions, _ = session.NewManager("mysql", “{"cookieName":"gosessionid","gclifetime":3600,"ProviderConfig":"[username[:password]@][protocol[(address)]]/dbname[?param1=value1&...&paramN=valueN]"}“) go globalSessions.GC() } more docs: http://beego.me/docs/module/session.md
Package mysql for session provider depends on github.com/go-sql-driver/mysql: go install github.com/go-sql-driver/mysql mysql session support need create table as sql: CREATE TABLE `session` ( `session_key` char(64) NOT NULL, `session_data` blob, `session_expiry` int(11) unsigned NOT NULL, PRIMARY KEY (`session_key`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8; Usage: import( _ "github.com/lessgo/lessgo/session/mysql" "github.com/lessgo/lessgo/session" ) func init() { globalSessions, _ = session.NewManager("mysql", “{"cookieName":"gosessionid","gclifetime":3600,"ProviderConfig":"[username[:password]@][protocol[(address)]]/dbname[?param1=value1&...&paramN=valueN]"}“) go globalSessions.GC() } more docs: http://beego.me/docs/module/session.md
postgres
Package postgres for session provider depends on github.com/lib/pq: go install github.com/lib/pq needs this table in your database: CREATE TABLE session ( session_key char(64) NOT NULL, session_data bytea, session_expiry timestamp NOT NULL, CONSTRAINT session_key PRIMARY KEY(session_key) ); will be activated with these settings in app.conf: SessionOn = true SessionProvider = postgresql SessionSavePath = "user=a password=b dbname=c sslmode=disable" SessionName = session Usage: import( _ "github.com/lessgo/lessgo/session/postgresql" "github.com/lessgo/lessgo/session" ) func init() { globalSessions, _ = session.NewManager("postgresql", “{"cookieName":"gosessionid","gclifetime":3600,"ProviderConfig":"user=pqgotest dbname=pqgotest sslmode=verify-full"}“) go globalSessions.GC() } more docs: http://beego.me/docs/module/session.md
Package postgres for session provider depends on github.com/lib/pq: go install github.com/lib/pq needs this table in your database: CREATE TABLE session ( session_key char(64) NOT NULL, session_data bytea, session_expiry timestamp NOT NULL, CONSTRAINT session_key PRIMARY KEY(session_key) ); will be activated with these settings in app.conf: SessionOn = true SessionProvider = postgresql SessionSavePath = "user=a password=b dbname=c sslmode=disable" SessionName = session Usage: import( _ "github.com/lessgo/lessgo/session/postgresql" "github.com/lessgo/lessgo/session" ) func init() { globalSessions, _ = session.NewManager("postgresql", “{"cookieName":"gosessionid","gclifetime":3600,"ProviderConfig":"user=pqgotest dbname=pqgotest sslmode=verify-full"}“) go globalSessions.GC() } more docs: http://beego.me/docs/module/session.md
redis
Package redis for session provider depend on github.com/garyburd/redigo/redis go install github.com/garyburd/redigo/redis Usage: import( _ "github.com/lessgo/lessgo/session/redis" "github.com/lessgo/lessgo/session" ) func init() { globalSessions, _ = session.NewManager("redis", “{"cookieName":"gosessionid","gclifetime":3600,"ProviderConfig":"127.0.0.1:7070"}“) go globalSessions.GC() } more docs: http://beego.me/docs/module/session.md
Package redis for session provider depend on github.com/garyburd/redigo/redis go install github.com/garyburd/redigo/redis Usage: import( _ "github.com/lessgo/lessgo/session/redis" "github.com/lessgo/lessgo/session" ) func init() { globalSessions, _ = session.NewManager("redis", “{"cookieName":"gosessionid","gclifetime":3600,"ProviderConfig":"127.0.0.1:7070"}“) go globalSessions.GC() } more docs: http://beego.me/docs/module/session.md
Package validation for validations import ( "github.com/astaxie/beego/validation" "log" ) type User struct { Name string Age int } func main() { u := User{"man", 40} valid := validation.Validation{} valid.Required(u.Name, "name") valid.MaxSize(u.Name, 15, "nameMax") valid.Range(u.Age, 0, 140, "age") if valid.HasErrors() { // validation does not pass // print invalid message for _, err := range valid.Errors { log.Println(err.Key, err.Message) } } // or use like this if v := valid.Max(u.Age, 140, "ageMax"); !v.Ok { log.Println(v.Error.Key, v.Error.Message) } } more info: http://beego.me/docs/mvc/controller/validation.md
Package validation for validations import ( "github.com/astaxie/beego/validation" "log" ) type User struct { Name string Age int } func main() { u := User{"man", 40} valid := validation.Validation{} valid.Required(u.Name, "name") valid.MaxSize(u.Name, 15, "nameMax") valid.Range(u.Age, 0, 140, "age") if valid.HasErrors() { // validation does not pass // print invalid message for _, err := range valid.Errors { log.Println(err.Key, err.Message) } } // or use like this if v := valid.Max(u.Age, 140, "ageMax"); !v.Ok { log.Println(v.Error.Key, v.Error.Message) } } more info: http://beego.me/docs/mvc/controller/validation.md
Package websocket implements a client and server for the WebSocket protocol as specified in RFC 6455.
Package websocket implements a client and server for the WebSocket protocol as specified in RFC 6455.

Jump to

Keyboard shortcuts

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