pgo

package module
v0.1.6 Latest Latest
Warning

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

Go to latest
Published: Jul 10, 2019 License: Apache-2.0 Imports: 27 Imported by: 0

README

PGO

PGO应用框架即"Pinguo GO application framework",是Camera360广告服务端团队研发的一款简单、高性能、组件化的GO应用框架。受益于GO语言高性能与原生协程,业务从php+yii2升级到PGO后,线上表现单机处理能力提高10倍。PGO吸收了php-yii2/php-msf/go-gin等框架的设计思想,平衡了开发效率和运行性能,使用PGO可快速地开发出高性能的web应用程序。

参考文档:pgo-docs

应用示例:pgo-demo

基准测试

主要测试PGO框架与php-yii2,php-msf,go-gin的性能差异。

说明:

  • 测试机为4核8G虚拟机
  • php版本为7.1.24, 开启opcache
  • go版本为1.11.2, GOMAXPROCS=4
  • swoole版本1.9.21, worker_num=4, reactor_num=2
  • 输出均为字符串{"code": 200, "message": "success","data": "hello world"}
  • 命令: ab -n 1000000 -c 100 -k 'http://target-ip:8000/welcome'
分类 QPS 平均响应时间(ms) CPU
php-yii2 2715 36.601 72%
php-msf 20053 4.575 73%
go-gin 41798 2.339 55%
go-pgo 33902 2.842 64%

结论:

  • pgo相比yii2性能提升10+倍, 对低于php7的版本性能还要翻倍。
  • pgo相比msf性能提升70%, 相较于msf的yield模拟的协程,pgo协程理解和使用更简单。
  • pgo相比gin性能降低19%, 但pgo内置多种常用组件,工程化做得更好,使用方式类似yii2和msf。

环境要求

  • GO 1.10+
  • Make 3.8+
  • Linux/MacOS/Cygwin
  • Glide 0.13+ (建议)
  • GoLand 2018 (建议)

项目目录

规范:

  • 一个项目为一个独立的目录,不使用GO全局工作空间。
  • 项目的GOPATH为项目根目录,不要依赖系统的GOPATH。
  • 除GO标准库外,所有外部依赖代码放入"src/vendor"。
  • 项目源码文件与目录使用大写驼峰(CamelCase)形式。
<project>
├── bin/                # 编译程序目录
├── conf/               # 配置文件目录
│   ├── production/     # 环境配置目录
│   │   ├── app.yaml
│   │   └── params.yaml
│   ├── testing/
│   ├── app.yaml        # 项目配置文件
│   └── params.yaml     # 自定义配置文件
├── makefile            # 编译打包
├── runtime/            # 运行时目录
├── public/             # 静态资源目录
├── view/               # 视图模板目录
└── src/                # 项目源码目录
    ├── Command/        # 命令行控制器目录
    ├── Controller/     # HTTP控制器目录
    ├── Lib/            # 项目基础库目录
    ├── Main/           # 项目入口目录
    ├── Model/          # 模型目录(数据交互)
    ├── Service/        # 服务目录(业务逻辑)
    ├── Struct/         # 结构目录(数据定义)
    ├── Test/           # 测试目录
    ├── vendor/         # 第三方依赖目录
    ├── glide.lock      # 项目依赖锁文件
    └── glide.yaml      # 项目依赖配置文件

依赖管理

建议使用glide做为依赖管理工具(类似php的composer),不使用go官方的dep工具

安装(mac):brew install glide

使用(调用目录为项目的src目录):

glide init              # 初始化项目
glide get <pkg>         # 下载pkg并添加依赖
    --all-dependencies  # 下载pkg的所有依赖
glide get <pkg>#v1.2    # 下载指定版本的pkg
glide install           # 根据lock文件下载依赖
glide update            # 更新依赖包

快速开始

  1. 拷贝makefile

    非IDE环境(命令行)下,推荐使用make做为编译打包的控制工具,从pgopgo-demo将makefile复制到项目目录下。

    make start      # 编译并运行当前工程
    make stop       # 停止当前工程的进程
    make build      # 仅编译当前工程
    make update     # 更新glide依赖(递归更新)
    make install    # 安装glide.lock文件锁定的依赖包
    make pgo        # 安装pgo框架到当前工程
    make init       # 初始化工程目录
    make help       # 输出帮助信息
    
  2. 创建项目目录(以下三种方法均可)

    • 执行make init创建目录
    • 参见《项目目录》手动创建
    • pgo-demo克隆目录结构
  3. 修改配置文件(conf/app.yaml)

    name: "pgo-demo"
    GOMAXPROCS: 2
    runtimePath: "@app/runtime"
    publicPath: "@app/public"
    viewPath: "@app/view"
    server:
        httpAddr: "0.0.0.0:8000"
        readTimeout: "30s"
        writeTimeout: "30s"
    components:
        log:
            levels: "ALL"
            targets:
                info:
                    class: "@pgo/FileTarget"
                    levels: "DEBUG,INFO,NOTICE"
                    filePath: "@runtime/info.log"
                error:
                    class: "@pgo/FileTarget"
                    levels: "WARN,ERROR,FATAL"
                    filePath: "@runtime/error.log"
                console: 
                    class: "@pgo/ConsoleTarget"
                    levels: "ALL"
    
  4. 安装PGO(以下两种方法均可)

    • 在项目根目录执行make pgo安装PGO
    • 在项目根目录执行export GOPATH=$GOPATH:$(pwd) && cd src && glide get github.com/pinguo/pgo && glide update
  5. 创建Service(src/Service/Welcome.go)

    package Service
    
    import (
        "fmt"
    
        "github.com/pinguo/pgo"
    )
    
    type Welcome struct {
        pgo.Object
    }
    
    // 框架自动调用的构造函数(可选)
    func (w *Welcome) Construct() {
        fmt.Printf("call in Service/Welcome.Construct\n")
    }
    
    // 框架自动调用的初始函数(可选)
    func (w *Welcome) Init() {
        fmt.Printf("call in Service/Welcome.Init\n")
    }
    
    func (w *Welcome) SayHello(name string, age int, sex string) {
        fmt.Printf("call in  Service/Welcome.SayHello, name:%s age:%d sex:%s\n", name, age, sex)
    }
    
  6. 注册Service(src/Service/Init.go)

    package Service
    
    import "github.com/pinguo/pgo"
    
    func init() {
        container := pgo.App.GetContainer()
    
        // 注册类
        container.Bind(&Welcome{})
    
        // 除控制器目录外,其它包的init函数中应该只注册该包的类,
        // 而不应该包含子包。
    }
    
    
  7. 创建控制器(src/Controller/WelcomeController.go)

    package Controller
    
    import (
        "Service"
        "net/http"
    
        "github.com/pinguo/pgo"
    )
    
    type WelcomeController struct {
        pgo.Controller
    }
    
    // 默认动作为index, 通过/welcome或/welcome/index调用
    func (w *WelcomeController) ActionIndex() {
        w.OutputJson("hello world", http.StatusOK)
    }
    
    // URL路由动作,根据url自动映射控制器及方法,不需要配置.
    // url的最后一段为动作名称,不存在则为index,
    // url的其余部分为控制器名称,不存在则为index,
    // 例如:/welcome/say-hello,控制器类名为
    // Controller/WelcomeController 动作方法名为ActionSayHello
    func (w *WelcomeController) ActionSayHello() {
        ctx := w.GetContext() // 获取PGO请求上下文件
    
        // 验证参数,提供参数名和默认值,当不提供默认值时,表明该参数为必选参数。
        // 详细验证方法参见Validate.go
        name := ctx.ValidateParam("name").Min(5).Max(50).Do() // 验证GET/POST参数(string),为空或验证失败时panic
        age := ctx.ValidateQuery("age", 20).Int().Min(1).Max(100).Do() // 只验证GET参数(int),为空或失败时返回20
        ip := ctx.ValidatePost("ip", "").IPv4().Do() // 只验证POST参数(string), 为空或失败时返回空字符串
    
        // 打印日志
        ctx.Info("request from welcome, name:%s, age:%d, ip:%s", name, age, ip)
        ctx.PushLog("clientIp", ctx.GetClientIp()) // 生成clientIp=xxxxx在pushlog中
    
        // 调用业务逻辑,一个请求生命周期内的对象都要通过GetObject()获取,
        // 这样可自动查找注册的类,并注入请求上下文(Context)到对象中。
        svc := w.GetObject("Service/Welcome").(*Service.Welcome)
    
        // 添加耗时到profile日志中
        ctx.ProfileStart("Welcome.SayHello")
        svc.SayHello(name, age, ip)
        ctx.ProfileStop("Welcome.SayHello")
    
        data := pgo.Map{
            "name": name,
            "age": age,
            "ip": ip,
        }
    
        // 输出json数据
        w.OutputJson(data, http.StatusOK)
    }
    
    // 正则路由动作,需要配置Router组件(components.router.rules)
    // 规则中捕获的参数通过动作函数参数传递,没有则为空字符串.
    // eg. "^/reg/eg/(\\w+)/(\\w+)$ => /welcome/regexp-example"
    func (w *WelcomeController) ActionRegexpExample(p1, p2 string) {
        data := pgo.Map{"p1": p1, "p2": p2}
        w.OutputJson(data, http.StatusOK)
    }
    
    // RESTFULL动作,url中没有指定动作名,使用请求方法作为动作的名称(需要大写)
    // 例如:GET方法请求ActionGET(), POST方法请求ActionPOST()
    func (w *WelcomeController) ActionGET() {
        w.GetContext().End(http.StatusOK, []byte("call restfull GET"))
    }
    
  8. 注册控制器(src/Controller/Init.go)

    package Controller
    
    import "github.com/pinguo/pgo"
    
    func init() {
        container := pgo.App.GetContainer()
        container.Bind(&WelcomeController{})
    }
    
  9. 创建程序入口(src/Main/main.go)

    package main
    
    import (
        _ "Controller" // 导入控制器
    
        "github.com/pinguo/pgo"
    )
    
    func main() {
        pgo.Run() // 运行程序
    }
    
  10. 编译运行

    make update
    make start
    curl http://127.0.0.1:8000/welcome
    
其它

参见pgo-docs

Documentation

Index

Constants

View Source
const (
	ModeWeb            = 1
	ModeCmd            = 2
	DefaultEnv         = "develop"
	DefaultController  = "Index"
	DefaultAction      = "Index"
	DefaultHttpAddr    = "0.0.0.0:8000"
	DefaultTimeout     = 30 * time.Second
	DefaultHeaderBytes = 1 << 20
	ControllerWeb      = "Controller"
	ControllerCmd      = "Command"
	ConstructMethod    = "Construct"
	InitMethod         = "Init"
	VendorPrefix       = "vendor/"
	VendorLength       = 7
	ActionPrefix       = "Action"
	ActionLength       = 6
	TraceMaxDepth      = 10
	MaxPlugins         = 32
	MaxCacheObjects    = 100
)
View Source
const (
	LevelNone   = 0x00
	LevelDebug  = 0x01
	LevelInfo   = 0x02
	LevelNotice = 0x04
	LevelWarn   = 0x08
	LevelError  = 0x10
	LevelFatal  = 0x20
	LevelAll    = 0xFF
)

Variables

View Source
var (
	App = &Application{}

	EmptyObject struct{}
)

Functions

func Configure

func Configure(obj interface{}, config map[string]interface{})

Configure configure object using the given configuration, obj is a pointer or reflect.Value of a pointer, config is the configuration map for properties.

func ConstructAndInit

func ConstructAndInit(obj interface{}, config map[string]interface{}, params ...interface{})

ConstructAndInit construct and initialize object, obj is a pointer or reflect.Value of a pointer, config is configuration map for properties, params is optional parameters for Construct method.

func CreateObject

func CreateObject(class interface{}, params ...interface{}) interface{}

CreateObject create object using the given configuration, class can be a string or a map contain "class" field, if a map is specified, fields except "class" will be treated as properties of the object to be created, params is optional parameters for Construct method.

func Decode

func Decode(data interface{}, ptr interface{})

Decode data bytes to ptr

func Encode

func Encode(data interface{}) []byte

Encode encode data to bytes

func GetAlias

func GetAlias(alias string) string

GetAlias resolve path alias, eg. @runtime/app.log => /path/to/runtime/app.log

func LevelToString

func LevelToString(level int) string

LevelToString convert int level to string

func Run

func Run()

Run run app

func SetAlias

func SetAlias(alias, path string)

SetAlias set path alias, eg. @app => /path/to/base

func StringToLevel

func StringToLevel(level string) int

StringToLevel convert string to int level

func TimeRun

func TimeRun() time.Duration

TimeRun time duration since app run

Types

type Application

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

Application the pgo app, initialization steps: 1. import pgo: pgo.init() 2. customize app: optional 3. pgo.Run(): serve

configuration: name: "app-name" GOMAXPROCS: 2 runtimePath: "@app/runtime" publicPath: "@app/public" viewPath: "@viewPath" container: {} server: {} components: {}

func (*Application) Construct

func (app *Application) Construct()

func (*Application) Get

func (app *Application) Get(id string) interface{}

Get get component by id

func (*Application) GetBasePath

func (app *Application) GetBasePath() string

GetBasePath get base path, default is parent of executable

func (*Application) GetConfig

func (app *Application) GetConfig() *Config

GetConfig get config component

func (*Application) GetContainer

func (app *Application) GetContainer() *Container

GetContainer get container component

func (*Application) GetEnv

func (app *Application) GetEnv() string

GetEnv get running env

func (*Application) GetI18n

func (app *Application) GetI18n() *I18n

GetI18n get i18n component

func (*Application) GetLog

func (app *Application) GetLog() *Log

GetLog get log component

func (*Application) GetMode

func (app *Application) GetMode() int

GetMode get running mode, web:1, cmd:2

func (*Application) GetName

func (app *Application) GetName() string

GetName get app name, default is executable name

func (*Application) GetPublicPath

func (app *Application) GetPublicPath() string

GetPublicPath get public path, default is @app/public

func (*Application) GetRouter

func (app *Application) GetRouter() *Router

GetRouter get router component

func (*Application) GetRuntimePath

func (app *Application) GetRuntimePath() string

GetRuntimePath get runtime path, default is @app/runtime

func (*Application) GetServer

func (app *Application) GetServer() *Server

GetServer get server component

func (*Application) GetStatus

func (app *Application) GetStatus() *Status

GetStatus get status component

func (*Application) GetStopBefore

func (app *Application) GetStopBefore() *StopBefore

GetStopBefore get stopBefore component

func (*Application) GetView

func (app *Application) GetView() *View

GetView get view component

func (*Application) GetViewPath

func (app *Application) GetViewPath() string

GetViewPath get view path, default is @app/view

func (*Application) Init

func (app *Application) Init()

type BoolValidator

type BoolValidator struct {
	Name   string
	UseDft bool
	Value  bool
}

BoolValidator validator for bool value

func ValidateBool

func ValidateBool(data interface{}, name string, dft ...interface{}) *BoolValidator

validate bool value

func (*BoolValidator) Do

func (b *BoolValidator) Do() bool

func (*BoolValidator) Must

func (b *BoolValidator) Must(v bool) *BoolValidator

type Config

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

Config the config component

func (*Config) AddParser

func (c *Config) AddParser(ext string, parser IConfigParser)

AddParser add parser for file with ext extension

func (*Config) AddPath

func (c *Config) AddPath(path string)

AddPath add path to end of search paths

func (*Config) Construct

func (c *Config) Construct()

func (*Config) Get

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

Get get value by dot separated key, the first part of key is file name without extension. if key is empty, all loaded config will be returned.

func (*Config) GetBool

func (c *Config) GetBool(key string, dft bool) bool

GetBool get bool value from config, key is dot separated config key, dft is default value if key not exists.

func (*Config) GetFloat

func (c *Config) GetFloat(key string, dft float64) float64

GetFloat get float value from config, key is dot separated config key, dft is default value if key not exists.

func (*Config) GetInt

func (c *Config) GetInt(key string, dft int) int

GetInt get int value from config, key is dot separated config key, dft is default value if key not exists.

func (*Config) GetSliceBool added in v0.1.4

func (c *Config) GetSliceBool(key string) []bool

GetSliceBool get []bool value from config, key is dot separated config key, nil is default value if key not exists.

func (*Config) GetSliceFloat added in v0.1.4

func (c *Config) GetSliceFloat(key string) []float64

GetSliceFloat get []float value from config, key is dot separated config key, nil is default value if key not exists.

func (*Config) GetSliceInt added in v0.1.4

func (c *Config) GetSliceInt(key string) []int

GetSliceInt get []int value from config, key is dot separated config key, nil is default value if key not exists.

func (*Config) GetSliceString added in v0.1.4

func (c *Config) GetSliceString(key string) []string

GetSliceString get []string value from config, key is dot separated config key, nil is default value if key not exists.

func (*Config) GetString

func (c *Config) GetString(key string, dft string) string

GetString get string value from config, key is dot separated config key, dft is default value if key not exists.

func (*Config) Load

func (c *Config) Load(name string)

Load load config file under the search paths. file under env sub path will be merged.

func (*Config) Set

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

Set set value by dot separated key, if key is empty, the value will set to root, if val is nil, the key will be deleted.

type ConsoleTarget

type ConsoleTarget struct {
	Target
}

ConsoleTarget target for console

func (*ConsoleTarget) Construct

func (c *ConsoleTarget) Construct()

func (*ConsoleTarget) Flush

func (c *ConsoleTarget) Flush(final bool)

Flush flush log to stdout

func (*ConsoleTarget) Process

func (c *ConsoleTarget) Process(item *LogItem)

Process write log to stdout

type Container

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

Container the container component, configuration: container:

enablePool: true

func (*Container) Bind

func (c *Container) Bind(i interface{})

Bind bind template object to class, param i must be a pointer of struct.

func (*Container) Construct

func (c *Container) Construct()

func (*Container) Get

func (c *Container) Get(name string, config map[string]interface{}, params ...interface{}) reflect.Value

Get get new class object. name is class name, config is properties map, params is optional construct parameters.

func (*Container) GetInfo

func (c *Container) GetInfo(name string) interface{}

GetInfo get class binding info

func (*Container) GetType

func (c *Container) GetType(name string) reflect.Type

GetType get class reflect type

func (*Container) Has

func (c *Container) Has(name string) bool

Has check if the class exists in container

func (*Container) Put

func (c *Container) Put(name string, rv reflect.Value)

Put put back reflect value to object pool

func (*Container) SetEnablePool

func (c *Container) SetEnablePool(enable bool)

SetEnablePool set context based object pool enable or not, default is enabled.

type Context

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

Context pgo request context, context is not goroutine safe, copy context to use in other goroutines

func (*Context) Abort

func (c *Context) Abort()

Abort stop running plugin chain

func (*Context) Copy

func (c *Context) Copy() *Context

Copy copy context

func (*Context) End

func (c *Context) End(status int, data []byte)

send response

func (*Context) GetActionId

func (c *Context) GetActionId() string

GetActionId

func (*Context) GetClientIp

func (c *Context) GetClientIp() string

GetClientIp get client ip

func (*Context) GetControllerId

func (c *Context) GetControllerId() string

GetControllerId

func (*Context) GetCookie

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

GetCookie get first cookie value by name

func (*Context) GetCookieAll

func (c *Context) GetCookieAll() map[string]string

GetCookieAll get first value of all cookies

func (*Context) GetElapseMs

func (c *Context) GetElapseMs() int

GetElapseMs get elapsed ms since request start

func (*Context) GetHeader

func (c *Context) GetHeader(name, dft string) string

GetHeader get first header value by name,name is case-insensitive

func (*Context) GetHeaderAll

func (c *Context) GetHeaderAll() map[string]string

GetHeaderAll get first value of all headers

func (*Context) GetInput

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

SetInput

func (*Context) GetLogId

func (c *Context) GetLogId() string

GetLogId get log id of current context

func (*Context) GetMethod

func (c *Context) GetMethod() string

GetMethod get request method

func (*Context) GetOutput

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

GetOutput

func (*Context) GetParam

func (c *Context) GetParam(name, dft string) string

GetParam get first param value by name, post take precedence over get

func (*Context) GetParamAll

func (c *Context) GetParamAll() map[string]string

GetParamAll get first value of all params, post take precedence over get

func (*Context) GetParamArray

func (c *Context) GetParamArray(name string) []string

GetParamArray get array value from GET/POST

func (*Context) GetParamMap

func (c *Context) GetParamMap(name string) map[string]string

GetParamMap get map value from GET/POST

func (*Context) GetPath

func (c *Context) GetPath() string

GetPath get request path

func (*Context) GetPost

func (c *Context) GetPost(name, dft string) string

GetPost get first post value by name

func (*Context) GetPostAll

func (c *Context) GetPostAll() map[string]string

GetPostAll get first value of all posts

func (*Context) GetPostArray

func (c *Context) GetPostArray(name string) []string

GetPostArray get array value from POST

func (*Context) GetPostMap

func (c *Context) GetPostMap(name string) map[string]string

GetPostMap get map value from POST

func (*Context) GetQuery

func (c *Context) GetQuery(name, dft string) string

GetQuery get first url query value by name

func (*Context) GetQueryAll

func (c *Context) GetQueryAll() map[string]string

GetQueryAll get first value of all url queries

func (*Context) GetQueryArray

func (c *Context) GetQueryArray(name string) []string

GetQueryArray get array value from GET

func (*Context) GetQueryMap

func (c *Context) GetQueryMap(name string) map[string]string

GetQueryMap get map value from GET

func (*Context) GetSize

func (c *Context) GetSize() int

GetSize get response size

func (*Context) GetStatus

func (c *Context) GetStatus() int

GetStatus get response status

func (*Context) GetUserData

func (c *Context) GetUserData(key string, dft interface{}) interface{}

GetUserData get user data from current context

func (*Context) Next

func (c *Context) Next()

Next start running plugin chain

func (*Context) SetActionId

func (c *Context) SetActionId(id string)

SetActionId

func (*Context) SetControllerId

func (c *Context) SetControllerId(id string)

SetControllerId

func (*Context) SetCookie

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

convenient way to set response cookie

func (*Context) SetHeader

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

set response header, no effect if any header has sent

func (*Context) SetInput

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

SetInput

func (*Context) SetOutput

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

SetOutput

func (*Context) SetUserData

func (c *Context) SetUserData(key string, data interface{})

SetUserData set user data to current context

func (*Context) ValidateParam

func (c *Context) ValidateParam(name string, dft ...interface{}) *StringValidator

validate get/post param, return string validator

func (*Context) ValidatePost

func (c *Context) ValidatePost(name string, dft ...interface{}) *StringValidator

validate post param, return string validator

func (*Context) ValidateQuery

func (c *Context) ValidateQuery(name string, dft ...interface{}) *StringValidator

validate query param, return string validator

type Controller

type Controller struct {
	Object
}

Controller the base class of web and cmd controller

func (*Controller) AfterAction

func (c *Controller) AfterAction(action string)

AfterAction after action hook

func (*Controller) BeforeAction

func (c *Controller) BeforeAction(action string)

BeforeAction before action hook

func (*Controller) GetBindInfo

func (c *Controller) GetBindInfo(v interface{}) interface{}

GetBindInfo get action map as extra binding info

func (*Controller) HandlePanic

func (c *Controller) HandlePanic(v interface{})

HandlePanic process unhandled action panic

func (*Controller) OutputJson

func (c *Controller) OutputJson(data interface{}, status int, msg ...string)

OutputJson output json response

func (*Controller) OutputJsonp

func (c *Controller) OutputJsonp(callback string, data interface{}, status int, msg ...string)

OutputJsonp output jsonp response

func (*Controller) OutputView

func (c *Controller) OutputView(view string, data interface{}, contentType ...string)

OutputView output rendered view

func (*Controller) Redirect

func (c *Controller) Redirect(location string, permanent bool)

Redirect output redirect response

type Exception

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

Exception panic as exception

func NewException

func NewException(status int, msg ...interface{}) *Exception

NewException create new exception with status and message

func (*Exception) Error

func (e *Exception) Error() string

Error implement error interface

func (*Exception) GetMessage

func (e *Exception) GetMessage() string

GetMessage get exception message string

func (*Exception) GetStatus

func (e *Exception) GetStatus() int

GetStatus get exception status code

type File

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

File file plugin, this plugin only handle file in @public directory, request url with empty or excluded extension will not be handled.

func (*File) HandleRequest

func (f *File) HandleRequest(ctx *Context)

func (*File) SetExcludeExtensions

func (f *File) SetExcludeExtensions(v []interface{})

type FileTarget

type FileTarget struct {
	Target
	// contains filtered or unexported fields
}

FileTarget target for file, configuration: info:

class: "@pgo/FileTarget"
levels: "DEBUG,INFO,NOTICE"
filePath: "@runtime/info.log"
maxLogFile: 10
maxBufferByte: 10485760
maxBufferLine: 10000
rotate: "daily"

func (*FileTarget) Construct

func (f *FileTarget) Construct()

func (*FileTarget) Flush

func (f *FileTarget) Flush(final bool)

Flush flush log buffer to file

func (*FileTarget) Init

func (f *FileTarget) Init()

func (*FileTarget) Process

func (f *FileTarget) Process(item *LogItem)

Process check and rotate log file if rotate is enable, write log to buffer, flush buffer to file if buffer is full.

func (*FileTarget) SetFilePath

func (f *FileTarget) SetFilePath(filePath string)

SetFilePath set file path, default "@runtime/app.log"

func (*FileTarget) SetMaxBufferByte

func (f *FileTarget) SetMaxBufferByte(maxBufferByte int)

SetMaxBufferByte set max buffer bytes, default 10MB

func (*FileTarget) SetMaxBufferLine

func (f *FileTarget) SetMaxBufferLine(maxBufferLine int)

SetMaxBufferLine set max buffer lines, default 10000

func (*FileTarget) SetMaxLogFile

func (f *FileTarget) SetMaxLogFile(maxLogFile int)

SetMaxLogFile set max log backups, default 10

func (*FileTarget) SetRotate

func (f *FileTarget) SetRotate(rotate string)

SetRotate set rotate policy(none, hourly, daily), default "daily"

type FloatSliceValidator

type FloatSliceValidator struct {
	Name  string
	Value []float64
}

FloatSliceValidator validator for float slice value

func (*FloatSliceValidator) Do

func (f *FloatSliceValidator) Do() []float64

type FloatValidator

type FloatValidator struct {
	Name   string
	UseDft bool
	Value  float64
}

FloatValidator validator for float value

func ValidateFloat

func ValidateFloat(data interface{}, name string, dft ...interface{}) *FloatValidator

validate float value

func (*FloatValidator) Do

func (f *FloatValidator) Do() float64

func (*FloatValidator) Max

func (*FloatValidator) Min

type Gzip

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

Gzip gzip compression plugin

func (*Gzip) Construct

func (g *Gzip) Construct()

func (*Gzip) HandleRequest

func (g *Gzip) HandleRequest(ctx *Context)

type I18n

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

I18n the internationalization component, language format is ll-CC or ll, lower case lang code, upper case area code. lang file name format is i18n_{lang}.json, and located in conf directory, configuration: i18n:

sourceLang: "en"
targetLang: [ "en", "zh-CN", "zh-TW"]

func (*I18n) Construct

func (i *I18n) Construct()

func (*I18n) SetSourceLang

func (i *I18n) SetSourceLang(lang string)

SetSourceLang set language of source

func (*I18n) SetTargetLang

func (i *I18n) SetTargetLang(targets []interface{})

SetTargetLang set language of target

func (*I18n) Translate

func (i *I18n) Translate(message, lang string, params ...interface{}) string

Translate message to target lang, lang format is one of the following: 1. accept-language header value: zh-CN,zh;q=0.9,en;q=0.8,zh-TW;q=0.7 2. ll-CC: lower case lang code and upper case area code, zh-CN 3. ll: lower case of lang code without area code, zh

type IBind

type IBind interface {
	GetBindInfo(v interface{}) interface{}
}

type ICache

type ICache interface {
	Get(key string) *Value
	MGet(keys []string) map[string]*Value
	Set(key string, value interface{}, expire ...time.Duration) bool
	MSet(items map[string]interface{}, expire ...time.Duration) bool
	Add(key string, value interface{}, expire ...time.Duration) bool
	MAdd(items map[string]interface{}, expire ...time.Duration) bool
	Del(key string) bool
	MDel(keys []string) bool
	Exists(key string) bool
	Incr(key string, delta int) int
}

type IConfigParser

type IConfigParser interface {
	Parse(path string) map[string]interface{}
}

type IController

type IController interface {
	BeforeAction(action string)
	AfterAction(action string)
	HandlePanic(v interface{})
}

type IEvent

type IEvent interface {
	HandleEvent(event string, ctx *Context, args ...interface{})
}

type IFormatter

type IFormatter interface {
	Format(item *LogItem) string
}

type IObject

type IObject interface {
	SetContext(ctx *Context)
	GetContext() *Context
	GetObject(class interface{}, params ...interface{}) interface{}
}

type IPlugin

type IPlugin interface {
	HandleRequest(ctx *Context)
}

type ITarget

type ITarget interface {
	Process(item *LogItem)
	Flush(final bool)
}

type IntSliceValidator

type IntSliceValidator struct {
	Name  string
	Value []int
}

IntSliceValidator validator for int slice value

func (*IntSliceValidator) Do

func (i *IntSliceValidator) Do() []int

type IntValidator

type IntValidator struct {
	Name   string
	UseDft bool
	Value  int
}

IntValidator validator for int value

func ValidateInt

func ValidateInt(data interface{}, name string, dft ...interface{}) *IntValidator

validate int value

func (*IntValidator) Do

func (i *IntValidator) Do() int

func (*IntValidator) Enum

func (i *IntValidator) Enum(enums ...int) *IntValidator

func (*IntValidator) Max

func (i *IntValidator) Max(v int) *IntValidator

func (*IntValidator) Min

func (i *IntValidator) Min(v int) *IntValidator

type Item

type Item struct {
	Action reflect.Value
	Params []reflect.Value
}

type JsonConfigParser

type JsonConfigParser struct {
}

JsonConfigParser parser for json config

func (*JsonConfigParser) Parse

func (j *JsonConfigParser) Parse(path string) map[string]interface{}

Parse parse json config, environment value like ${env||default} will expand

type JsonValidator

type JsonValidator struct {
	Name   string
	UseDft bool
	Value  map[string]interface{}
}

JsonValidator validator for json value

func (*JsonValidator) Do

func (j *JsonValidator) Do() map[string]interface{}

func (*JsonValidator) Has

func (j *JsonValidator) Has(key string) *JsonValidator

type Log

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

Log the log component, configuration: log:

levels: "ALL"
traceLevels: "DEBUG"
chanLen: 1000
flushInterval: "60s"
targets:
    info:
        class: "@pgo/FileTarget"
        levels: "DEBUG,INFO,NOTICE"
        filePath: "@runtime/info.log"
        maxLogFile: 10
        rotate: "daily"
    error: {
        class: "@pgo/FileTarget"
        levels: "WARN,ERROR,FATAL"
        filePath: "@runtime/error.log"
        maxLogFile: 10
        rotate: "daily"

func (*Log) Construct

func (d *Log) Construct()

func (*Log) Flush

func (d *Log) Flush()

Flush close msg chan and wait loop end

func (*Log) GetLogger

func (d *Log) GetLogger(name, logId string) *Logger

GetLogger get a new logger with name and id specified

func (*Log) GetProfiler

func (d *Log) GetProfiler() *Profiler

GetProfiler get a new profiler

func (*Log) Init

func (d *Log) Init()

func (*Log) SetChanLen

func (d *Log) SetChanLen(len int)

SetChanLen set length of log channel, default 1000

func (*Log) SetFlushInterval

func (d *Log) SetFlushInterval(v string)

SetFlushInterval set interval to flush log, default "60s"

func (*Log) SetLevels

func (d *Log) SetLevels(v interface{})

SetLevels set levels to handle, default "ALL"

func (*Log) SetTargets

func (d *Log) SetTargets(targets map[string]interface{})

SetTargets set output target, ConsoleTarget will be used if no targets specified

func (*Log) SetTraceLevels

func (d *Log) SetTraceLevels(v interface{})

SetTraceLevels set levels to trace, default "DEBUG"

type LogItem

type LogItem struct {
	When    time.Time
	Level   int
	Name    string
	LogId   string
	Trace   string
	Message string
}

LogItem represent an item of log

type Logger

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

Logger

func GLogger

func GLogger() *Logger

GLogger get global logger

func (*Logger) Debug

func (l *Logger) Debug(format string, v ...interface{})

func (*Logger) Error

func (l *Logger) Error(format string, v ...interface{})

func (*Logger) Fatal

func (l *Logger) Fatal(format string, v ...interface{})

func (*Logger) Info

func (l *Logger) Info(format string, v ...interface{})

func (*Logger) Notice

func (l *Logger) Notice(format string, v ...interface{})

func (*Logger) Warn

func (l *Logger) Warn(format string, v ...interface{})

type Map

type Map map[string]interface{}

Map alias for map[string]interface{}

type Object

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

Object base class of context based object

func (*Object) GetContext

func (o *Object) GetContext() *Context

GetContext get context of this object

func (*Object) GetObject

func (o *Object) GetObject(class interface{}, params ...interface{}) interface{}

GetObject create new object and inject context

func (*Object) SetContext

func (o *Object) SetContext(ctx *Context)

SetContext set context of this object

type Profiler

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

Profiler

func (*Profiler) Counting

func (p *Profiler) Counting(key string, hit, total int)

Counting add counting info, the counting string is key=sum(hit)/sum(total)

func (*Profiler) GetCountingString

func (p *Profiler) GetCountingString() string

GetCountingString get counting info string

func (*Profiler) GetProfileString

func (p *Profiler) GetProfileString() string

GetProfileString get profile info string

func (*Profiler) GetPushLogString

func (p *Profiler) GetPushLogString() string

GetPushLogString get push log string

func (*Profiler) ProfileAdd

func (p *Profiler) ProfileAdd(key string, elapse time.Duration)

ProfileAdd add profile info, the profile string is key=sum(elapse)/count

func (*Profiler) ProfileStart

func (p *Profiler) ProfileStart(key string)

ProfileStart mark start of profile

func (*Profiler) ProfileStop

func (p *Profiler) ProfileStop(key string)

ProfileStop mark stop of profile

func (*Profiler) PushLog

func (p *Profiler) PushLog(key string, v interface{})

PushLog add push log, the push log string is key=Util.ToString(v)

type Response

type Response struct {
	http.ResponseWriter
	// contains filtered or unexported fields
}

Response http.ResponseWriter wrapper

func (*Response) ReadFrom

func (r *Response) ReadFrom(src io.Reader) (n int64, e error)

ReadFrom is here to optimize copying from a regular file to a *net.TCPConn with sendfile.

func (*Response) Write

func (r *Response) Write(data []byte) (n int, e error)

Write write data to underlying http.ResponseWriter and record num bytes that has written.

func (*Response) WriteHeader

func (r *Response) WriteHeader(status int)

WriteHeader cache status code until first write operation.

func (*Response) WriteString

func (r *Response) WriteString(s string) (n int, e error)

WriteString write string data to underlying http.ResponseWriter and record num bytes that has written.

type Router

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

Router the router component, configuration: router:

rules:
    - "^/foo/all$ => /foo/index"
    - "^/api/user/(\d+)$ => /api/user"

func (*Router) AddRoute

func (r *Router) AddRoute(pattern, route string)

AddRoute add one route, the captured group will be passed to action method as function params

func (*Router) Construct

func (r *Router) Construct()

func (*Router) Resolve

func (r *Router) Resolve(path string) (route string, params []string)

Resolve path to route and action params, then format route to CamelCase

func (*Router) SetRules

func (r *Router) SetRules(rules []interface{})

SetRules set rule list, format: `^/api/user/(\d+)$ => /api/user`

type Server

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

Server the server component, configuration: server:

httpAddr:  "0.0.0.0:8000"
debugAddr: "0.0.0.0:8100"
httpsAddr: "0.0.0.0:8443"
crtFile: "@app/conf/site.crt"
keyFile: "@app/conf/site.key"
maxHeaderBytes: 1048576
readTimeout:   "30s"
writeTimeout:  "30s"
statsInterval: "60s"
enableAccessLog: true
maxPostBodySize: 1048576

func (*Server) Construct

func (s *Server) Construct()

func (*Server) GetStats

func (s *Server) GetStats() *ServerStats

GetStats get server stats

func (*Server) HandleRequest

func (s *Server) HandleRequest(ctx *Context)

HandleRequest handle request of cmd or http, this method called in the last of plugin chain.

func (*Server) Serve

func (s *Server) Serve()

Serve request processing entry

func (*Server) ServeCMD

func (s *Server) ServeCMD()

ServeCMD serve command request

func (*Server) ServeHTTP

func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request)

ServeHTTP serve http request

func (*Server) SetCrtFile

func (s *Server) SetCrtFile(certFile string)

SetCrtFile set certificate file for https

func (*Server) SetDebugAddr

func (s *Server) SetDebugAddr(addr string)

SetDebugAddr set debug and pprof addr.

func (*Server) SetEnableAccessLog

func (s *Server) SetEnableAccessLog(v bool)

SetEnableAccessLog set access log enable or not

func (*Server) SetHttpAddr

func (s *Server) SetHttpAddr(addr string)

SetHttpAddr set http addr, if both httpAddr and httpsAddr are empty, "0.0.0.0:8000" will be used as httpAddr.

func (*Server) SetHttpsAddr

func (s *Server) SetHttpsAddr(addr string)

SetHttpsAddr set https addr.

func (*Server) SetKeyFile

func (s *Server) SetKeyFile(keyFile string)

SetKeyFile set private key file for https

func (*Server) SetMaxHeaderBytes

func (s *Server) SetMaxHeaderBytes(maxBytes int)

SetMaxHeaderBytes set max header bytes

func (*Server) SetMaxPostBodySize

func (s *Server) SetMaxPostBodySize(maxBytes int64)

SetMaxPostBodySize set max header bytes

func (*Server) SetPlugins

func (s *Server) SetPlugins(v []interface{})

SetPlugins set plugin names

func (*Server) SetReadTimeout

func (s *Server) SetReadTimeout(v string)

SetReadTimeout set timeout to read request

func (*Server) SetStatsInterval

func (s *Server) SetStatsInterval(v string)

SetStatsInterval set interval to output stats

func (*Server) SetWriteTimeout

func (s *Server) SetWriteTimeout(v string)

SetWriteTimeout set timeout to write response

type ServerStats

type ServerStats struct {
	MemMB   uint   // memory obtained from os
	NumReq  uint64 // number of handled requests
	NumGO   uint   // number of goroutines
	NumGC   uint   // number of gc runs
	TimeGC  string // total time of gc pause
	TimeRun string // total time of app runs
}

ServerStats server stats

type Status

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

Status the status component, configuration: status:

useI18n: false
mapping:
    11002: "Verify Sign Error"

func (*Status) Construct

func (s *Status) Construct()

func (*Status) GetText

func (s *Status) GetText(status int, ctx *Context, dft ...string) string

GetText get status text

func (*Status) SetMapping

func (s *Status) SetMapping(m map[string]interface{})

SetMapping set mapping from status code to text

func (*Status) SetUseI18n

func (s *Status) SetUseI18n(useI18n bool)

SetUseI18n set whether to use i18n translation

type StopBefore

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

func (*StopBefore) Add

func (s *StopBefore) Add(obj interface{}, method string, dfParams ...[]interface{})

增加停止前执行的对象和方法

func (*StopBefore) Exec

func (s *StopBefore) Exec()

执行

type StringSliceValidator

type StringSliceValidator struct {
	Name   string
	UseDft bool
	Value  []string
}

StringSliceValidator validator for string slice value

func (*StringSliceValidator) Do

func (s *StringSliceValidator) Do() []string

func (*StringSliceValidator) Float

func (*StringSliceValidator) Int

func (*StringSliceValidator) Len

func (*StringSliceValidator) Max

func (*StringSliceValidator) Min

type StringValidator

type StringValidator struct {
	Name   string
	UseDft bool
	Value  string
}

StringValidator validator for string value

func ValidateString

func ValidateString(data interface{}, name string, dft ...interface{}) *StringValidator

validate string value

func (*StringValidator) Bool

func (s *StringValidator) Bool() *BoolValidator

func (*StringValidator) Do

func (s *StringValidator) Do() string

func (*StringValidator) Email

func (s *StringValidator) Email() *StringValidator

func (*StringValidator) Enum

func (s *StringValidator) Enum(enums ...string) *StringValidator

func (*StringValidator) Filter

func (s *StringValidator) Filter(f func(v, n string) string) *StringValidator

func (*StringValidator) Float

func (s *StringValidator) Float() *FloatValidator

func (*StringValidator) IPv4

func (s *StringValidator) IPv4() *StringValidator

func (*StringValidator) Int

func (s *StringValidator) Int() *IntValidator

func (*StringValidator) Json

func (s *StringValidator) Json() *JsonValidator

func (*StringValidator) Len

func (s *StringValidator) Len(v int) *StringValidator

func (*StringValidator) Max

func (s *StringValidator) Max(v int) *StringValidator

func (*StringValidator) Min

func (s *StringValidator) Min(v int) *StringValidator

func (*StringValidator) Mobile

func (s *StringValidator) Mobile() *StringValidator

func (*StringValidator) Password

func (s *StringValidator) Password() *StringValidator

func (*StringValidator) RegExp

func (s *StringValidator) RegExp(v interface{}) *StringValidator

func (*StringValidator) Slice

type Target

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

Target base class of output

func (*Target) Format

func (t *Target) Format(item *LogItem) string

Format format log item to string

func (*Target) IsHandling

func (t *Target) IsHandling(level int) bool

IsHandling check whether this target is handling the log item

func (*Target) SetFormatter

func (t *Target) SetFormatter(v interface{})

SetFormatter set user-defined log formatter, eg. "Lib/Log/Formatter"

func (*Target) SetLevels

func (t *Target) SetLevels(v interface{})

SetLevels set levels for target, eg. "DEBUG,INFO,NOTICE"

type Value

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

Value adapter for value of any type, provide uniform encoding and decoding.

func NewValue

func NewValue(data interface{}) *Value

func (*Value) Bool

func (v *Value) Bool() bool

Bool return underlying data as bool

func (*Value) Bytes

func (v *Value) Bytes() []byte

Bytes return underlying data as bytes

func (*Value) Data

func (v *Value) Data() interface{}

Data return underlying data

func (*Value) Decode

func (v *Value) Decode(ptr interface{})

Decode decode data bytes to ptr, panic if failed

func (*Value) Encode

func (v *Value) Encode() []byte

Encode encode data to bytes, panic if failed

func (*Value) Float

func (v *Value) Float() float64

Float return underlying data as float64

func (*Value) Int

func (v *Value) Int() int

Int return underlying data as int

func (*Value) MarshalJSON

func (v *Value) MarshalJSON() ([]byte, error)

func (*Value) String

func (v *Value) String() string

String return underlying data as string

func (*Value) TryDecode

func (v *Value) TryDecode(ptr interface{}) (err error)

TryDecode try decode data, err is not nil if panic

func (*Value) TryEncode

func (v *Value) TryEncode() (output []byte, err error)

TryEncode try encode data, err is not nil if panic

func (*Value) UnmarshalJSON

func (v *Value) UnmarshalJSON(b []byte) error

func (*Value) Valid

func (v *Value) Valid() bool

Valid check the underlying data is nil

type View

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

View the view component, configuration: view:

suffix: ".html"
commons:
    - "@view/common/header.html"
    - "@view/common/footer.html"

func (*View) AddFuncMap

func (v *View) AddFuncMap(funcMap template.FuncMap)

AddFuncMap add custom func map

func (*View) Construct

func (v *View) Construct()

func (*View) Display

func (v *View) Display(w io.Writer, view string, data interface{})

Display render view and display result

func (*View) Render

func (v *View) Render(view string, data interface{}) []byte

Render render view and return result

func (*View) SetCommons

func (v *View) SetCommons(commons []interface{})

SetCommons set common view files

func (*View) SetSuffix

func (v *View) SetSuffix(suffix string)

SetSuffix set view file suffix, default is ".html"

type YamlConfigParser

type YamlConfigParser struct {
}

YamlConfigParser parser for yaml config

func (*YamlConfigParser) Parse

func (y *YamlConfigParser) Parse(path string) map[string]interface{}

Parse parse yaml config, environment value like ${env||default} will expand

Directories

Path Synopsis
Client
Db

Jump to

Keyboard shortcuts

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