pgo2

package module
v0.1.140 Latest Latest
Warning

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

Go to latest
Published: Jan 28, 2021 License: Apache-2.0 Imports: 35 Imported by: 0

README

pgo2

pgo2应用框架即"Pinguo GO application framework 2.0",是Camera360服务端团队基于pgo2研发的一款简单、高性能、组件化的GO应用框架。受益于GO语言高性能与原生协程,使用pgo2可快速地开发出高性能的web应用程序。

参考文档:pgo2-docs

应用示例:pgo2-demo

基准测试

环境要求

  • GO 1.13+
  • Make 3.8+
  • Linux/MacOS/Cygwin
  • GoLand 2019 (建议)

项目目录

规范:

  • 基于go mod 按go规范执行。
<project>
├── bin/                # 编译程序目录
├── configs/            # 配置文件目录
│   ├── production/     # 环境配置目录
│   │   ├── app.yaml
│   │   └── params.yaml
│   ├── testing/
│   ├── app.yaml        # 项目配置文件
│   └── params.yaml     # 自定义配置文件
├── makefile            # 编译打包
├── runtime/            # 运行时目录 主要用于存储日志
├── assets/             # 非web相关资源
├── web/                # 静态资源目录
│   ├── static          # 静态资源
│   ├── template        # 视图模板目录
├── cmd/                # 项目入口目录
└── pkg/                # 项目源码目录
    ├── command/        # 命令行控制器目录
    ├── controller/     # HTTP控制器目录
    ├── lib/            # 项目基础库目录
    ├── model/          # 模型目录(数据交互)
    ├── service/        # 服务目录(业务逻辑)
    ├── structs/         # 结构目录(数据定义)

快速开始

  1. 拷贝makefile

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

    make start      # 编译并运行当前工程
    make stop       # 停止当前工程的进程
    make build      # 仅编译当前工程
    make update     # go mod get
    make install    # go mod download
    make pgo2       # 安装pgo2框架到当前工程
    make init       # 初始化工程目录
    make help       # 输出帮助信息
    
  2. 创建项目目录(以下三种方法均可)

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

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

    • 在项目根目录执行make pgo2安装pgo2
    • 在项目根目录执行go get -u github.com/pinguo/pgo2
  5. 创建service(pkg/service/Welcome.go)

    package service
    
    func NewWelcome() *Welcome{
       return &Welcome{}
    }
    
    type Welcome struct {
        pgo2.Object
    }
    
    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. 创建控制器(pkg/controller/welcomeController.go)

    package controller
    
    type WelcomeController struct {
        pgo2.Controller
    }
    
    func (w *WelcomeController) ActionIndex() {
        w.Json("hello world", http.StatusOK)
    }
    
    // URL路由动作,根据url自动映射控制器及方法,不需要配置.
    // 例如:/welcome/say-hello,控制器类名为
    // controller/welcomeController 动作方法名为ActionSayHello
    func (w *WelcomeController) ActionSayHello() {
        ctx := w.Context() // 获取pgo2请求上下文件
    
        // 验证参数,提供参数名和默认值,当不提供默认值时,表明该参数为必选参数。
        // 详细验证方法参见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.ClientIp()) // 生成clientIp=xxxxx在pushlog中
    
        // 调用业务逻辑,一个请求生命周期内的对象都要通过GetObj()获取,
        // 这样可自动查找注册的类,并注入请求上下文(Context)到对象中。
        svc := w.GetObj(service.NewWelcome()).(*Service.Welcome)
    
        // 添加耗时到profile日志中
        ctx.ProfileStart("Welcome.SayHello")
        svc.SayHello(name, age, ip)
        ctx.ProfileStop("Welcome.SayHello")
    
        data := map[string]interface{}{
            "name": name,
            "age": age,
            "ip": ip,
        }
    
        // 输出json数据
        w.Json(data, http.StatusOK)
    }
    
    // 正则路由动作,需要配置Router组件(components.router.rules)
    // 规则中捕获的参数通过动作函数参数传递,没有则为空字符串.
    // eg. "^/reg/eg/(\\w+)/(\\w+)$ => /welcome/regexp-example"
    func (w *WelcomeController) ActionRegexpExample(p1, p2 string) {
        data := map[string]interface{}{"p1": p1, "p2": p2}
        w.Json(data, http.StatusOK)
    }
    
    // RESTful动作,url中没有指定动作名,使用请求方法作为动作的名称(需要大写)
    // 例如:GET方法请求GET(), POST方法请求POST()
    func (w *WelcomeController) GET() {
       w.Context().End(http.StatusOK, []byte("call restfull GET"))
    }
    
  7. 创建程序入口(cmd/projectName/main.go)

    package main
    
    import (
        _ "pgo2-demo/pkg/controller" // 导入控制器
    
        "github.com/pinguo/pgo2"
    )
    
    func main() {
        pgo2.Run() // 运行程序
    }
    
  8. 编译运行

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

参见pgo2-docs

Documentation

Index

Constants

View Source
const (
	ModeWeb                = "web"
	ModeCmd                = "cmd"
	DefaultEnv             = "develop"
	DefaultControllerPath  = "index"
	DefaultActionPath      = "index"
	DefaultHttpAddr        = "0.0.0.0:8000"
	DefaultTimeout         = 30 * time.Second
	DefaultHeaderBytes     = 1 << 20
	ControllerWebPkg       = "controller"
	ControllerCmdPkg       = "command"
	ControllerWebType      = "Controller"
	ControllerCmdType      = "Command"
	ConstructMethod        = "Construct"
	PrepareMethod          = "Prepare"
	VendorPrefix           = "vendor/"
	VendorLength           = 7
	ActionPrefix           = "Action"
	ActionLength           = 6
	TraceMaxDepth          = 10
	MaxPlugins             = 32
	MaxCacheObjects        = 100
	ParamsFlagMethodPrefix = "ParamsFlag"
)
View Source
const (
	EnablePoolOn = "on"
)

Variables

View Source
var (
	EmptyObject struct{}
)

Functions

func GLogger

func GLogger() *logs.Logger

GLogger get global logger

func GetAlias

func GetAlias(alias string) string

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

func Run

func Run()

Run run app

func SetAlias

func SetAlias(alias, path string)

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

Types

type ActionInfo added in v0.1.130

type ActionInfo struct {
	ControllerName string                      // 控制器名
	Name           string                      // action名
	PkgPath        string                      // 包路径
	PkgName        string                      // 包名
	Desc           string                      // action描述
	ParamsDesc     map[string]*ActionInfoParam // 参数描述
}

type ActionInfoParam added in v0.1.130

type ActionInfoParam struct {
	Name     string
	DftValue string
	NameType string
	Usage    string
}

type Application

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

func App

func App(newApp ...bool) *Application

func NewApp

func NewApp() *Application

func (*Application) Arg

func (app *Application) Arg(name string) string

func (*Application) BasePath

func (app *Application) BasePath() string

BasePath base path, default is parent of executable

func (*Application) CmdMode added in v0.1.130

func (app *Application) CmdMode() bool

CmdMode

func (*Application) Component

func (app *Application) Component(id string, funcName iface.IComponentFunc, params ...map[string]interface{}) interface{}

Get get component by id

func (*Application) Config

func (app *Application) Config() config.IConfig

Config config component

func (*Application) Container

func (app *Application) Container() *Container

Container container component

func (*Application) Env

func (app *Application) Env() string

Env running env

func (*Application) GetObjPool

func (app *Application) GetObjPool(name string, ctx iface.IContext, params ...interface{}) iface.IObject

Get get pool class object. name is class name, ctx is context,

func (*Application) GetObjSingle

func (app *Application) GetObjSingle(name string, funcName iface.IObjSingleFunc, param ...interface{}) iface.IObject

Get get single class object. name is class name, ctx is context,

func (*Application) HasArg

func (app *Application) HasArg(name string) bool

func (*Application) I18n

func (app *Application) I18n() iface.II18n

I18n i18n component

func (*Application) Init

func (app *Application) Init(osArgs []string)

func (*Application) Log

func (app *Application) Log() *logs.Log

Log log component

func (*Application) Mode

func (app *Application) Mode() string

Mode running mode, web:1, cmd:2

func (*Application) Name

func (app *Application) Name() string

Name appName, default is executable name

func (*Application) PublicPath

func (app *Application) PublicPath() string

PublicPath public path, default is @app/public

func (*Application) Router

func (app *Application) Router() *Router

Router router component

func (*Application) RuntimePath

func (app *Application) RuntimePath() string

RuntimePath runtime path, default is @app/runtime

func (*Application) Server

func (app *Application) Server() *Server

Server server component

func (*Application) SetConfig

func (app *Application) SetConfig(config config.IConfig)

SetView set view component

func (*Application) SetI18n

func (app *Application) SetI18n(i18n iface.II18n)

SetI18n set i18n component

func (*Application) SetStatus

func (app *Application) SetStatus(status iface.IStatus)

SetStatus set status component

func (*Application) SetView

func (app *Application) SetView(view iface.IView)

SetView set view component

func (*Application) Status

func (app *Application) Status() iface.IStatus

Status status component

func (*Application) StopBefore

func (app *Application) StopBefore() *StopBefore

StopBefore stopBefore component

func (*Application) View

func (app *Application) View() iface.IView

View view component

func (*Application) ViewPath

func (app *Application) ViewPath() string

ViewPath view path, default is @app/view

type Container

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

func NewContainer

func NewContainer(enable string) *Container

Container the container component, configuration: container:

enablePool: on/off

func (*Container) Bind

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

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

func (*Container) Get

func (c *Container) Get(name string, ctx iface.IContext, 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) PathList

func (c *Container) PathList(prefix, suffix string) map[string]interface{}

PathList Gets a list of paths with the specified path prefix

func (*Container) Put

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

Put put back reflect value to object pool

type Context

type Context struct {
	logs.Profiler
	logs.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) ActionId

func (c *Context) ActionId() string

ActionId

func (*Context) Cache

func (c *Context) Cache(name string, rv reflect.Value)

cache object in context

func (*Context) ClientIp

func (c *Context) ClientIp() string

ClientIp get client ip

func (*Context) ControllerId

func (c *Context) ControllerId() string

ControllerId

func (*Context) Cookie

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

Cookie get first cookie value by name

func (*Context) CookieAll

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

CookieAll get first value of all cookies

func (*Context) Copy

func (c *Context) Copy() iface.IContext

Copy copy context

func (*Context) Debug

func (c *Context) Debug(format string, v ...interface{})

func (*Context) ElapseMs

func (c *Context) ElapseMs() int

ElapseMs get elapsed ms since request start

func (*Context) End

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

send response

func (*Context) Error

func (c *Context) Error(format string, v ...interface{})

func (*Context) Fatal

func (c *Context) Fatal(format string, v ...interface{})

func (*Context) FinishGoLog

func (c *Context) FinishGoLog()

finish coroutine log

func (*Context) Header

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

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

func (*Context) HeaderAll

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

HeaderAll get first value of all headers

func (*Context) HttpRW

func (c *Context) HttpRW(debug, enableAccessLog bool, r *http.Request, w http.ResponseWriter)

func (*Context) Info

func (c *Context) Info(format string, v ...interface{})

func (*Context) Input

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

SetInput

func (*Context) LogId

func (c *Context) LogId() string

LogId get log id of current context

func (*Context) Method

func (c *Context) Method() string

Method get request method

func (*Context) Next

func (c *Context) Next()

Next start running plugin chain

func (*Context) Notice

func (c *Context) Notice(format string, v ...interface{})

func (*Context) Output

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

Output

func (*Context) Param

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

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

func (*Context) ParamAll

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

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

func (*Context) ParamArray

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

ParamArray get array value from GET/POST

func (*Context) ParamMap

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

ParamMap get map value from GET/POST

func (*Context) Path

func (c *Context) Path() string

Path get request path

func (*Context) Post

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

Post get first post value by name

func (*Context) PostAll

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

PostAll get first value of all posts

func (*Context) PostArray

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

PostArray get array value from POST

func (*Context) PostMap

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

PostMap get map value from POST

func (*Context) Process

func (c *Context) Process(plugins []iface.IPlugin)

start plugin chain process

func (*Context) Query

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

Query get first url query value by name

func (*Context) QueryAll

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

QueryAll get first value of all url queries

func (*Context) QueryArray

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

QueryArray get array value from GET

func (*Context) QueryMap

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

QueryMap get map value from GET

func (*Context) SetAccessLogFormat added in v0.1.9

func (c *Context) SetAccessLogFormat(v iface.IAccessLogFormat)

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) SetEnableAccessLog added in v0.1.114

func (c *Context) SetEnableAccessLog(v bool)

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

func (c *Context) Size() int

Size get response size

func (*Context) Start

func (c *Context) Start(plugins []iface.IPlugin)

func (*Context) Status

func (c *Context) Status() int

Status get response status

func (*Context) UserData

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

UserData get user data from current context

func (*Context) ValidateParam

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

validate get/post param, return string validator

func (*Context) ValidatePost

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

validate post param, return string validator

func (*Context) ValidateQuery

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

validate query param, return string validator

func (*Context) Warn

func (c *Context) Warn(format string, v ...interface{})

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

func (c *Controller) Data(data []byte, dftContentType ...string)

Data output data response

func (*Controller) Error added in v0.1.1

func (c *Controller) Error(status int, message string)

Error

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{}, debug bool)

HandlePanic process unhandled action panic

func (*Controller) Json

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

Json output json response

func (*Controller) JsonV2 added in v0.1.132

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

JsonV2 output json response

func (*Controller) Jsonp

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

Jsonp output jsonp response

func (*Controller) ProtoBuf

func (c *Controller) ProtoBuf(data interface{}, statuses ...int)

ProtoBuf output proto buf response

func (*Controller) Redirect

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

Redirect output redirect response

func (*Controller) Render

func (c *Controller) Render(r render.Render, statuses ...int)

Render Custom renderer

func (*Controller) Response added in v0.1.136

func (c *Controller) Response(v interface{}, err error)

Response response values action returned

func (*Controller) SetActionDesc added in v0.1.122

func (c *Controller) SetActionDesc(message string)

SetActionDesc Deprecated: Delete the next version directly

func (*Controller) View

func (c *Controller) View(view string, data interface{}, contentTypes ...string)

View output rendered view

func (*Controller) Xml

func (c *Controller) Xml(data interface{}, statuses ...int)

Xml output xml response

type File

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

func NewFile

func NewFile(config map[string]interface{}) *File

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

func (*File) SetExcludeExtensions

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

type Gzip

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

func NewGzip

func NewGzip() *Gzip

Gzip gzip compression plugin

func (*Gzip) HandleRequest

func (g *Gzip) HandleRequest(ctx iface.IContext)

type Handler

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

type I18n

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

func NewI18n

func NewI18n(config map[string]interface{}) *I18n

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

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

type Object

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

Object base class of context based object

func (*Object) Context

func (o *Object) Context() iface.IContext

GetContext get context of this object

func (*Object) GetObj

func (o *Object) GetObj(obj iface.IObject) iface.IObject

GetObject create new object

func (*Object) GetObjBox added in v0.1.116

func (o *Object) GetObjBox(className string, params ...interface{}) iface.IObject

GetObjPool Get Object from box,Have the function of the pool params: Parameter passed into Prepare

func (*Object) GetObjBoxCtx added in v0.1.116

func (o *Object) GetObjBoxCtx(ctx iface.IContext, className string, params ...interface{}) iface.IObject

GetObjBoxCtx Get Object from box and new Context,Have the function of the pool params: Parameter passed into Prepare

func (*Object) GetObjCtx

func (o *Object) GetObjCtx(ctx iface.IContext, obj iface.IObject) iface.IObject

GetObject create new object and new Context

func (*Object) GetObjPool

func (o *Object) GetObjPool(className string, funcName iface.IObjPoolFunc, params ...interface{}) iface.IObject

GetObjPool Get Object from pool Recommended: Use GetObjBox instead.

func (*Object) GetObjPoolCtx

func (o *Object) GetObjPoolCtx(ctx iface.IContext, className string, funcName iface.IObjPoolFunc, params ...interface{}) iface.IObject

GetObjPoolCtx Get Object from pool and new Context Recommended: Use GetObjBoxCtx instead.

func (*Object) GetObjSingle

func (o *Object) GetObjSingle(name string, funcName iface.IObjSingleFunc, params ...interface{}) iface.IObject

GetObject Get single object

func (*Object) GetObjSingleCtx

func (o *Object) GetObjSingleCtx(ctx iface.IContext, name string, funcName iface.IObjSingleFunc, params ...interface{}) iface.IObject

GetObject Get single object and new Context

func (*Object) SetContext

func (o *Object) SetContext(ctx iface.IContext) iface.IObject

SetContext set context of this object

type Parser added in v0.1.130

type Parser struct {
}

func NewParser added in v0.1.130

func NewParser() *Parser

func (*Parser) ActionInfo added in v0.1.130

func (p *Parser) ActionInfo(pkgRealPath, pkgPath string) map[string][]*ActionInfo

func (*Parser) Dir added in v0.1.130

func (p *Parser) Dir(path string, filterFunc ...func(os.FileInfo) bool) map[string]*ast.Package

func (*Parser) GetActionInfo added in v0.1.130

func (p *Parser) GetActionInfo(pkgPath, controllerName, actionName string) *ActionInfo

func (*Parser) InitActionInfo added in v0.1.130

func (p *Parser) InitActionInfo(pkgRealPath, pkgPath string)

func (*Parser) ParseCallExpr added in v0.1.130

func (p *Parser) ParseCallExpr(expr ast.Expr, pkgName string, minLenArg int) *ActionInfoParam

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

func (r *Response) Size() int

func (*Response) Status

func (r *Response) Status() int

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
}

func NewRouter

func NewRouter(config map[string]interface{}) *Router

Router the router component, configuration: router:

httpStatus:true // Whether to override the HTTP status code
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) CmdHandlers

func (r *Router) CmdHandlers() map[string]*Handler

func (*Router) CreateController

func (r *Router) CreateController(path string, ctx iface.IContext) (reflect.Value, reflect.Value, []string)

CreateController Create the controller and parameters

func (*Router) ErrorController added in v0.1.1

func (r *Router) ErrorController(ctx iface.IContext, statuses ...int) iface.IController

func (*Router) Handler

func (r *Router) Handler(path string) *Handler

func (*Router) InitHandlers

func (r *Router) InitHandlers()

InitHandlers Initialization route

func (*Router) Resolve

func (r *Router) Resolve(path, method string) (handler *Handler, params []string)

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

func (*Router) SetErrorController added in v0.1.1

func (r *Router) SetErrorController(v string)

func (*Router) SetHandlers

func (r *Router) SetHandlers(cmdType string, list map[string]interface{})

SetHandlers Set route

func (*Router) SetHttpStatus added in v0.1.1

func (r *Router) SetHttpStatus(v bool)

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
}

func NewServer

func NewServer(config map[string]interface{}) *Server

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
debug:true
disableCheckListen: true

func (*Server) AddPlugin

func (s *Server) AddPlugin(v iface.IPlugin)

AddPlugins add plugin

func (*Server) GetStats

func (s *Server) GetStats() *ServerStats

GetStats get server stats

func (*Server) HandleRequest

func (s *Server) HandleRequest(ctx iface.IContext)

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) SetAccessLogFormat added in v0.1.9

func (s *Server) SetAccessLogFormat(v iface.IAccessLogFormat)

SetAccessLogFormat set accessLogFormat

func (*Server) SetCrtFile

func (s *Server) SetCrtFile(certFile string)

SetCrtFile set certificate file for https

func (*Server) SetDebug

func (s *Server) SetDebug(v bool)

SetDebug set debug

func (*Server) SetDebugAddr

func (s *Server) SetDebugAddr(addr string)

SetDebugAddr set debug and pprof addr.

func (*Server) SetDisableCheckListen added in v0.1.127

func (s *Server) SetDisableCheckListen(v bool)

SetDisableCheckListen Disable check listen port

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 by 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 ServerConfig

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

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
}

func NewStatus

func NewStatus(config map[string]interface{}) *Status

Status the status component, configuration: status:

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

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

func (*Status) Text

func (s *Status) Text(status int, lang string, dft ...string) string

GetText get status text

type StopBefore

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

func NewStopBefore

func NewStopBefore() *StopBefore

func (*StopBefore) Add

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

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

func (*StopBefore) Exec

func (s *StopBefore) Exec()

执行

type View

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

func NewView

func NewView(config map[string]interface{}) *View

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

Directories

Path Synopsis
client
db
es
orm
test
mock/adapter
Package mock_adapter is a generated GoMock package.
Package mock_adapter is a generated GoMock package.
mock/config
Package mock_config is a generated GoMock package.
Package mock_config is a generated GoMock package.
mock/iface
Package mock_iface is a generated GoMock package.
Package mock_iface is a generated GoMock package.
mock/logs
Package mock_logs is a generated GoMock package.
Package mock_logs is a generated GoMock package.
mock/render
Package mock_render is a generated GoMock package.
Package mock_render is a generated GoMock package.

Jump to

Keyboard shortcuts

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