lessgo

package module
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Jan 6, 2017 License: MIT Imports: 40 Imported by: 15

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.7.0
  • 发布日期:2016.06.01

最新功能特性

  • 使用简单、运行稳定高效(核心架构来自对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/henrylee2cn/lessgo
go get -u github.com/henrylee2cn/less
go get -u github.com/henrylee2cn/lessgoext/...

框架构成

代码示例

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

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

    _ "github.com/henrylee2cn/lessgo_demo/middleware"
    _ "github.com/henrylee2cn/lessgo_demo/router"
)

func main() {
    // 开启自动api文档,通过config/apidoc_allow.myconfig进行配置
    swagger.Reg()
    // 指定根目录URL
    lessgo.SetHome("/home")
    // 开启网络服务
    lessgo.Run()
}
  • 定义一个较复杂的操作
import (
    . "github.com/henrylee2cn/lessgo"
    "github.com/henrylee2cn/lessgo_demo/sysmodel/admin"
)

var Index = ApiHandler{
    Desc:   "后台管理登录操作",
    Method: "POST|PUT",
    Params: []Param{
        {"user", "formData", true, "henry11111", "用户名"},
        {"user", "query", true, "henry22222", "用户名"},
        {"user", "path", true, "henry33333", "用户名"},
        {"password", "formData", true, "1111111111", "密码"},
        {"password", "query", true, "2222222222", "密码"},
        {"password", "path", true, "3333333333", "密码"},
    },
    Handler: func(c *Context) error {
        // 测试读取cookie
        id := c.CookieParam(Config.Session.SessionName)
        c.Log().Info("cookie中的%v: %#v", Config.Session.SessionName, id)

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

        c.SetSession("info", map[string]interface{}{
            "user":     c.FormParam("user"),
            "password": c.FormParam("password"),
        })
        c.Log().Info("path用户名: %#v", c.PathParam("user"))
        c.Log().Info("query用户名: %#v", c.QueryParam("user"))
        c.Log().Info("formData用户名: %#v", c.FormParam("user"))
        c.Log().Info("path密码: %#v", c.PathParam("password"))
        c.Log().Info("query密码: %#v", c.QueryParam("password"))
        c.Log().Info("formData密码: %#v", c.FormParam("password"))

        return c.Render(200,
            "sysview/admin/login/index.tpl",
            map[string]interface{}{
                "name":       c.FormParam("user"),
                "password":   c.FormParam("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/henrylee2cn/lessgo"

    "github.com/henrylee2cn/lessgo_demo/bizhandler/home"
    "github.com/henrylee2cn/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 源码路由配置
│  ├─sys_router.go 系统模块路由文件
│  ├─biz_router.go 业务模块路由文件
├─sys_handler 系统模块后端目录
│  ├─xxx 子模块目录
│  │  ├─example.go example操作
│  │  └─... xxx的子模块目录
│  └─... 其他子模块目录
├─sys_model 系统模块数据模型目录
├─sys_view 系统模块前端目录 (url: /sys)
│  ├─xxx 与sys_handler对应的子模块目录 (url: /sys/xxx)
│  │  ├─example.tpl 相应操作的模板文件
│  │  ├─example2.html 无需绑定操作的静态html文件
│  │  ├─xxx.css css文件(可有多个)
│  │  ├─xxx.js js文件(可有多个)
│  │  └─... xxx的子模块目录
├─biz_handler 业务模块后端目录
│  ├─xxx 子模块目录
│  │  ├─example.go example操作
│  │  └─... xxx的子模块目录
│  └─... 其他子模块目录
├─biz_model 业务模块数据模型目录
├─biz_view 业务模块前端目录 (url: /biz)
│  ├─xxx 与biz_handler对应的子模块目录 (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 = "biz_handler"
	BIZ_MODEL_DIR   = "biz_model"
	BIZ_VIEW_DIR    = "biz_view"
	SYS_HANDLER_DIR = "sys_handler"
	SYS_MODEL_DIR   = "sys_model"
	SYS_VIEW_DIR    = "sys_view"
	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.8"
	ADDRESS = "https://github.com/henrylee2cn/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 = func() *config {
		fmt.Printf("%s\n(%s)\n\n", banner, ADDRESS)
		c := newConfig()
		err := c.LoadMainConfig()
		if err != nil {
			fmt.Println(err)
		}
		return c
	}()

	// 全局运行日志实例(来自数据库的日志除外)
	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) 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.pvalues[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-Credentials", "true")
		c.response.Header().Set("Access-Control-Allow-Origin", c.HeaderParam("Origin"))

		return nil
	},
}.Reg()
View Source
var FilterTemplate = ApiMiddleware{
	Name: "过滤前端模板",
	Desc: "过滤前端模板,不允许直接访问",
	Middleware: func(next HandlerFunc) HandlerFunc {
		return func(c *Context) 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 (

	// 文件上传默认内存缓存大小,默认值是64MB。
	MaxMemory int64 = 64 * MB
)
View Source
var RequestLogger = ApiMiddleware{
	Name: "系统运行日志打印",
	Desc: "RequestLogger returns a middleware that logs HTTP requests.",
	Middleware: func(next HandlerFunc) HandlerFunc {
		return func(c *Context) error {
			var u = c.request.URL.String()
			start := time.Now()
			if err := next(c); err != nil {
				c.Failure(500, err)
			}
			stop := time.Now()

			method := c.request.Method
			if u == "" {
				u = "/"
			}

			n := c.response.Status()
			var code string
			if runtime.GOOS == "linux" {
				code = strconv.Itoa(n)
			} else {
				code = color.Green(n)
				switch {
				case n >= 500:
					code = color.Red(n)
				case n >= 400:
					code = color.Magenta(n)
				case n >= 300:
					code = color.Cyan(n)
				}
			}

			Log.Debug("%15s | %7s | %s | %8d | %10s | %s", c.RealRemoteAddr(), method, code, c.response.Size(), stop.Sub(start), u)
			return nil
		}
	},
}.Reg()

Functions

func AfterUse

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

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

func BeforeUse

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

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

func CanMemoryCache added in v1.0.0

func CanMemoryCache() bool

判断文件缓存是否开启

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) 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 DisableMemoryCache added in v1.0.0

func DisableMemoryCache()

关闭文件缓存

func DisableServer

func DisableServer()

关闭网站服务

func EnableMemoryCache added in v1.0.0

func EnableMemoryCache()

启用文件缓存

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 PreUse

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

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

func ReadSingleConfig added in v0.7.0

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

func RefreshMemoryCache added in v1.0.0

func RefreshMemoryCache()

主动刷新缓存文件

func ReregisterRouter

func ReregisterRouter(reasons ...string)

Reregister real router

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(graceExitCallback ...func() error)

运行服务 @param graceExitCallback设置优雅关闭或重启时的收尾函数

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 SetFailureHandler added in v1.0.0

func SetFailureHandler(fn func(c *Context, code int, errString string) error)

设置失败状态默认的响应操作(内部有默认实现)

func SetHome

func SetHome(homeurl string)

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

func SetPanicStackFunc added in v1.0.0

func SetPanicStackFunc(fn func(rcv interface{}) string)

设置获取请求过程中恐慌Stack信息的函数(内部有默认实现)

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 TemplateVariable added in v1.0.0

func TemplateVariable(name string, fn interface{})

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中保持一致
	HTTP200 []Result             // (可选)HTTP Status Code 为200时的响应结果
	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

注册操作

type ApiMiddleware

type ApiMiddleware struct {
	Name       string // 全局唯一
	Desc       string
	Params     []Param     // (可选)参数说明列表(应该只声明当前中间件用到的参数),path参数类型的先后顺序与url中保持一致
	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) Clone added in v1.0.0

func (a *ApiMiddleware) Clone() *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) CanMemoryCache added in v1.0.0

func (this *App) CanMemoryCache() bool

判断文件缓存是否开启

func (*App) Debug added in v0.7.0

func (this *App) Debug() bool

Debug returns debug mode (enabled or disabled).

func (*App) IsClose added in v1.0.0

func (this *App) IsClose() bool

return the server status.

func (*App) Log added in v0.7.0

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

func (*App) MemoryCache added in v1.0.0

func (this *App) MemoryCache() *MemoryCache

获取文件缓存对象

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) SetFailureHandler added in v1.0.0

func (this *App) SetFailureHandler(fn func(c *Context, code int, errString string) error)

set the default failuer handler.

func (*App) SetGraceExitFunc added in v1.0.0

func (this *App) SetGraceExitFunc(fn func() error)

Set the graceful exit or restart callback function.

func (*App) SetPanicStackFunc added in v1.0.0

func (this *App) SetPanicStackFunc(fn func(rcv interface{}) string)

设置获取请求过程中恐慌Stack信息的函数

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

func (*App) SetStatus added in v1.0.0

func (this *App) SetStatus(serving bool)

set the server status.

func (*App) TemplateVariable added in v1.0.0

func (this *App) TemplateVariable(name string, fn interface{})

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 CommJSON added in v1.0.0

type CommJSON Result

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) AddCookie added in v1.0.0

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

AddCookie adds cookie for response. The provided cookie must have a valid Name. Invalid cookies may be silently dropped.

func (*Context) AddCookieParam added in v1.0.0

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

AddCookieParam adds a cookie to the request.

func (*Context) AddFormParam added in v1.0.0

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

AddFormParam adds the form param. It appends to any existing values associated with key.

func (*Context) AddHeader added in v1.0.0

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

AddHeader sets header for response. It appends to any existing values associated with key.

func (*Context) AddHeaderParam added in v1.0.0

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

AddHeaderParam sets request header. It appends to any existing values associated with key.

func (*Context) AddQueryParam added in v1.0.0

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

AddQueryParam adds the the query param. It appends to any existing values associated with key.

func (*Context) Attachment

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

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

func (*Context) Bind

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

Bind binds the request body into provided type `container`. 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) CookieParam added in v1.0.0

func (c *Context) CookieParam(key string) *http.Cookie

CookieParam returns the named cookie provided in the request.

func (*Context) CookieParams added in v1.0.0

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

CookieParams 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) DelCookie added in v1.0.0

func (c *Context) DelCookie()

DelCookie deletes cookie for response.

func (*Context) DelHeader added in v1.0.0

func (c *Context) DelHeader(key string)

DelHeader deletes the values associated with key for response.

func (*Context) DelSession

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

DelSession removes value from session.

func (*Context) DestroySession

func (c *Context) DestroySession()

DestroySession cleans session data and session cookie.

func (*Context) Failure added in v1.0.0

func (c *Context) Failure(code int, err error) error

Failure writes http failure status, example 403, 404, 405, 500 and so on.

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(key string) (multipart.File, *multipart.FileHeader, error)

FormFile returns the multipart form file for the provided key.

func (*Context) FormParam added in v1.0.0

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

FormParam returns the form field value for the provided key.

func (*Context) FormParams

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

FormParams returns the form field value with "[]string" for the provided key.

func (*Context) FormValues added in v1.0.0

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

FormValues returns the form params as url.Values.

func (*Context) Get

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

Set saves data in the context.

func (*Context) GetSession

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

GetSession gets value from session.

func (*Context) HTML

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

HTML sends an HTTP response with status code.

func (*Context) Header added in v1.0.0

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

Header returns the response header.

func (*Context) HeaderParam added in v1.0.0

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

HeaderParam returns request header value for the provided key.

func (*Context) HeaderParams added in v1.0.0

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

HeaderParams returns request header value with "[]string" for the provided key.

func (*Context) HeaderValues added in v1.0.0

func (c *Context) HeaderValues() http.Header

HeaderValues returns the request header.

func (*Context) IsTLS added in v0.7.0

func (c *Context) IsTLS() bool

func (*Context) JSON

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

JSON sends a JSON response with status code.

func (*Context) JSONBlob

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

JSONBlob sends a JSON blob response with status code.

func (*Context) JSONMsg

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

JSON with default format.

func (*Context) JSONP

func (c *Context) JSONP(code int, callback string, i interface{}) 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{}) 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) Markdown added in v1.0.0

func (c *Context) Markdown(file string, hasCatalog ...bool) error

Markdown parses markdown file and generates html in github style

func (*Context) NoContent

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

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

func (*Context) Path

func (c *Context) Path() string

Path returns the registered path for the handler.

func (*Context) PathParam added in v1.0.0

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

PathParam returns path param by key.

func (*Context) PathParamByIndex added in v1.0.0

func (c *Context) PathParamByIndex(i int) string

PathParamByIndex returns path param by index.

func (*Context) PathParamKeys added in v1.0.0

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

PathParamKeys returns path param keys.

func (*Context) PathParamValues added in v1.0.0

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

PathParamValues returns path param values.

func (*Context) QueryParam

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

QueryParam returns the query param for the provided key.

func (*Context) QueryParams

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

QueryParams returns the query param with "[]string".

func (*Context) QueryValues added in v1.0.0

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

QueryValues returns all query params.

func (*Context) RealRemoteAddr added in v0.7.0

func (c *Context) RealRemoteAddr() string

获取客户端真实IP

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{}) 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) ResponseWriter added in v1.0.0

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

func (*Context) ReverseProxy added in v1.0.0

func (c *Context) ReverseProxy(targetUrlBase string, pathAppend bool) error

ReverseProxy routes URLs to the scheme, host, and base path provided in targetUrlBase. If pathAppend is "true" and the targetUrlBase's path is "/base" and the incoming request was for "/dir", the target request will be for /base/dir.

func (*Context) SaveFile added in v1.0.0

func (c *Context) SaveFile(key string, cover bool, newfname ...string) (fileUrl string, size int64, err error)

SaveFile saves the file *Context.FormFile to UPLOADS_DIR, character "?" indicates that the original file name. for example newfname="a/?" -> UPLOADS_DIR/a/fname.

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.ReadSeeker` 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 sets cookie for response.

func (*Context) SetFormParam added in v1.0.0

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

SetFormParam sets the form param. It replaces any existing values.

func (*Context) SetHeader added in v1.0.0

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

SetHeader sets header for response. It replaces any existing values.

func (*Context) SetHeaderParam added in v1.0.0

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

SetHeaderParam sets request header. It replaces any existing values.

func (*Context) SetPath

func (c *Context) SetPath(p string)

SetPath sets the registered path for the handler.

func (*Context) SetPathParam added in v1.0.0

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

SetPathParam sets path param.

func (*Context) SetQueryParam added in v1.0.0

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

SetQueryParam sets the query param. It replaces any existing values.

func (*Context) SetRequestBody added in v0.7.0

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

func (*Context) SetResponse added in v1.0.0

func (c *Context) SetResponse(resp *Response)

func (*Context) SetSession

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

SetSession puts value into session.

func (*Context) SetWs added in v1.0.0

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

设置websocket实例

func (*Context) String

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

String sends a string response with status code.

func (*Context) Write added in v1.0.0

func (c *Context) Write(b []byte) (int, error)

Write writes the data to the connection as part of an HTTP reply. If WriteHeader has not yet been called, Write calls WriteHeader(http.StatusOK) before writing the data. If the Header does not contain a Content-Type line, Write adds a Content-Type set to the result of passing the initial 512 bytes of written data to DetectContentType.

func (*Context) WriteHeader added in v1.0.0

func (c *Context) 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 (*Context) Ws added in v1.0.0

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

获取websocket实例

func (*Context) WsClose added in v1.0.0

func (c *Context) WsClose() error

关闭websocket

func (*Context) WsRecvJSON

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

接收JSON格式的websocket信息

func (*Context) WsRecvString added in v1.0.0

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

接收string格式的websocket信息

func (*Context) WsSendJSON

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

发送JSON格式的websocket信息

func (*Context) WsSendString added in v1.0.0

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

发送string格式的websocket信息

func (*Context) XML

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

XML sends an XML response with status code.

func (*Context) XMLBlob

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

XMLBlob sends a XML blob response with status code.

type FailureHandlerFunc added in v1.0.0

type FailureHandlerFunc func(c *Context, code int, errString string) error

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() (err error)

type Listen

type Listen struct {
	Address       string
	ReadTimeout   int64
	WriteTimeout  int64
	EnableTLS     bool
	TLSAddress    string
	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) ([]byte, os.FileInfo, bool)

返回文件字节流、文件信息、文件是否存在

func (*MemoryCache) SetEnable

func (m *MemoryCache) SetEnable(bl bool)

func (*MemoryCache) TriggerScan added in v1.0.0

func (m *MemoryCache) TriggerScan()

主动触发扫描本地文件

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) GetApiMiddleware added in v1.0.0

func (m *MiddlewareConfig) GetApiMiddleware() *ApiMiddleware

获取*ApiMiddleware

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 PanicStackFunc added in v1.0.0

type PanicStackFunc func(rcv interface{}) string

type Param

type Param struct {
	Name     string      // (必填)参数名
	In       string      // (必填)参数出现位置
	Required bool        // (必填)是否必填
	Model    interface{} // (必填)参数值,API文档中依此推断参数值类型,同时作为默认值,当为nil时表示file文件上传
	Desc     string      // (可选)参数描述
}

type Pongo2Render

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

Pongo2Render is a custom lessgo template renderer using Pongo2.

func NewPongo2Render

func NewPongo2Render(caching bool) *Pongo2Render

New creates a new Pongo2Render instance with custom Options.

func (*Pongo2Render) FromCache added in v1.0.0

func (p *Pongo2Render) FromCache(fname string) (*pongo2.Template, error)

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.

func (*Pongo2Render) TemplateVariable added in v1.0.0

func (p *Pongo2Render) TemplateVariable(name string, v interface{})

type Renderer

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

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) AddCookie added in v1.0.0

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

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

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.

func (*Response) Committed

func (resp *Response) Committed() bool

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

func (*Response) DelCookie added in v1.0.0

func (r *Response) DelCookie()

DelCookie sets Set-Cookie header.

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.

func (*Response) Header

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

Header returns the header map that will be sent by WriteHeader. 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.

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.

func (*Response) SetCookie

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

SetCookie sets a Set-Cookie header.

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) (int, error)

Write writes the data to the connection as part of an HTTP reply. If WriteHeader has not yet been called, Write calls WriteHeader(http.StatusOK) before writing the data. If the Header does not contain a Content-Type line, Write adds a Content-Type set to the result of passing the initial 512 bytes of written data to DetectContentType.

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 Result added in v1.0.0

type Result struct {
	Code int         `json:"code"`           // (必填)返回结果码
	Info interface{} `json:"info,omitempty"` // (可选)返回结果格式参考或描述

}

type ReverseProxys added in v1.0.0

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

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

	sync.RWMutex
	// 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 Tpl added in v1.0.0

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

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 GetVirtRouterByPath added in v1.0.0

func GetVirtRouterByPath(path string) (*VirtRouter, bool)

根据path获取虚拟路由节点

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) GetMiddlewareConfig added in v1.0.0

func (vr *VirtRouter) GetMiddlewareConfig(name string) (*MiddlewareConfig, bool)

获取虚拟路由节点的中间件

func (*VirtRouter) HTTP200 added in v1.0.0

func (vr *VirtRouter) HTTP200() []Result

操作的返回结果说明列表

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) Sort added in v1.0.0

func (v *VirtRouter) Sort() *VirtRouter

节点排序

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/henrylee2cn/lessgo/config/xml" "github.com/henrylee2cn/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/henrylee2cn/lessgo/config/xml" "github.com/henrylee2cn/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/henrylee2cn/lessgo/config/yaml" "github.com/henrylee2cn/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/henrylee2cn/lessgo/config/yaml" "github.com/henrylee2cn/lessgo/config" ) cnf, err := config.NewConfig("yaml", "config.yaml") more docs http://beego.me/docs/module/config.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
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
Blackfriday markdown processor.
Blackfriday markdown processor.
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/henrylee2cn/lessgo/session/couchbase" "github.com/henrylee2cn/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/henrylee2cn/lessgo/session/couchbase" "github.com/henrylee2cn/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/henrylee2cn/lessgo/session/memcache" "github.com/henrylee2cn/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/henrylee2cn/lessgo/session/memcache" "github.com/henrylee2cn/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/henrylee2cn/lessgo/session/mysql" "github.com/henrylee2cn/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/henrylee2cn/lessgo/session/mysql" "github.com/henrylee2cn/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/henrylee2cn/lessgo/session/postgresql" "github.com/henrylee2cn/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/henrylee2cn/lessgo/session/postgresql" "github.com/henrylee2cn/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/henrylee2cn/lessgo/session/redis" "github.com/henrylee2cn/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/henrylee2cn/lessgo/session/redis" "github.com/henrylee2cn/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 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