webx

package module
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Dec 28, 2015 License: MIT Imports: 46 Imported by: 0

README

webx

webx是一个强大的Go语言web框架。

Go Walker Bitdeli Badge

技术支持

QQ群:369240307

更新日志

  • v1.0.0 :
    1. 新增模板扩展
    2. 将扩展包统一放到lib文件夹
    3. 框架启用新名字webx
  • v0.5.0 :
    1. Server支持平滑关闭;
    2. 静态文件和模板文件仅在使用时才缓存(优点:加快服务生效时间和节约内存),支持根据配置自动改变监控目录;
    3. 支持合并静态资源,支持同步更新合并的静态资源;
    4. 改进路由注册方式(现在变得更加智能);
    5. Server支持限制最大连接数
    6. 新增对action新返回类型:webx.JSON/webx.JSONP/webx.XML/webx.FILE等的支持
    7. app支持绑定子域名
    8. 改进https服务
    9. 其它细微调整
  • v0.4.0 :
    1. AddTmplVar改为Assign;
    2. AddTmplVars改为MultiAssign;
    3. 日志中增加IP、页面字节大小以及耗时记录(便于查找恶意访问来源);
    4. 修复bug
  • v0.3.0 : 增加对称加密、XSRF通用接口,更换hook引擎为更加优雅的events引擎
  • v0.2.1 : 自动Binding新增对jquery对象,map和array的支持。
  • v0.2 : 新增 validation 子包,从 https://github.com/astaxie/beego/tree/master/validation 拷贝过来。
  • v0.1.2 : 采用 github.com/coscms/webx/lib/httpsession 作为session组件,API保持兼容;Action现在必须从*Action继承,这个改变与以前的版本不兼容,必须更改代码;新增两个模板函数{{session "key"}} 和 {{cookie "key"}};Action新增函数MapForm
  • v0.1.1 : App新增AutoAction方法;Action新增Assign方法;Render方法的模版渲染方法中可以通过T混合传入函数和变量,更新了快速入门
  • v0.1.0 : 初始版本

特性

  • 在一个可执行程序中多Server(http,tls,scgi,fcgi),多App的支持
  • 简单好用的路由映射方式
  • 静态文件及版本支持,并支持自动加载,默认开启
  • 改进的模版支持,并支持自动加载,动态新增模板函数
  • session支持
  • validation支持

安装

在安装之前确认你已经安装了Go语言. Go语言安装请访问 install instructions.

安装 webx:

go get github.com/coscms/webx

Examples

请访问 examples folder

案例

文档

快速入门

源码文档请访问 GoWalker

License

BSD License http://creativecommons.org/licenses/BSD/

Documentation

Overview

Package webx is a simple and powerful web framework for Go.

Installation

Make sure you have installed Go 1.1+ and then:

go get github.com/coscms/webx

More usage, please visit https://github.com/coscms/webx/

Package web is a lightweight web framework for Go. It's ideal for writing simple, performant backend web services.

Index

Constants

View Source
const (
	Debug = iota + 1
	Product
	XSRF_TAG string = "_xsrf"
)
View Source
const (
	ForeBlack  = iota + 30 //30         40         黑色
	ForeRed                //31         41         紅色
	ForeGreen              //32         42         綠色
	ForeYellow             //33         43         黃色
	ForeBlue               //34         44         藍色
	ForePurple             //35         45         紫紅色
	ForeCyan               //36         46         青藍色
	ForeWhite              //37         47         白色
)
View Source
const (
	LevelTrace = iota + 1
	LevelDebug
	LevelInfo
	LevelWarn
	LevelError
	LevelCritical
)
View Source
const (
	Version = "1.0.0"
)

Variables

View Source
var (
	DefaultFuncs template.FuncMap = template.FuncMap{
		"Now":         Now,
		"Eq":          Eq,
		"FormatDate":  FormatDate,
		"Add":         Add,
		"Subtract":    Subtract,
		"IsNil":       IsNil,
		"Url":         Url,
		"UrlFor":      UrlFor,
		"Html":        Html,
		"Js":          Js,
		"Css":         Css,
		"XsrfField":   XsrfName,
		"HtmlAttr":    HtmlAttr,
		"ToHtmlAttrs": ToHtmlAttrs,
		"BuildUrl":    BuildUrl,
	}
)

*

  • 默认模板函数
  • 除了这里定义的之外,还可以使用当前Action(即在方法中使用Render的Action)中定义的可导出的属性和方法(使用".属性"或".方法"来访问)
  • 另外还支持函数:
  • include —— Include(tmplName string) interface{}
  • session —— GetSession(key string) interface{}
  • cookie —— Cookie(key string) string
  • XsrfFormHtml —— XsrfFormHtml() template.HTML
  • XsrfValue —— XsrfValue() string
  • XsrfName —— XsrfName() string
  • StaticUrl —— StaticUrl(url string) string
  • 支持变量:
  • webxVer —— string
View Source
var (
	DefaultHtmlFilter = func(v string) (r string) {
		return v
	}
)
View Source
var ExtensionValidator = make(map[string]func(*App, http.ResponseWriter, *http.Request) bool)

Functions

func Abort

func Abort(code int, content ...string) error

func Add

func Add(left interface{}, right interface{}) interface{}

func AddAction

func AddAction(c ...interface{})

func AddApp

func AddApp(a *App)

func AddConfig

func AddConfig(name string, value interface{})

func AddEvent

func AddEvent(eventName string, handler func(interface{}, func(bool)))

添加事件

func AddFilter

func AddFilter(filter Filter)

func AddRouter

func AddRouter(url string, c interface{})

func Assign

func Assign(name string, varOrFun interface{})

func AutoAction

func AutoAction(c ...interface{})

func AvgTime

func AvgTime(items []time.Duration) time.Duration

func BuildUrl

func BuildUrl(route, appName, servName string, size int) string

func Close

func Close()

Close stops the main server.

func CloseZWriter

func CloseZWriter(zwriter io.Writer)

CloseZWriter closes the io.Writer after compressing static file.

func Css

func Css(raw string) template.CSS

func DelEvent

func DelEvent(eventName string)

删除事件

func Download

func Download(w http.ResponseWriter, fpath string) error

func Eq

func Eq(left interface{}, right interface{}) bool

func Error

func Error(w http.ResponseWriter, status int, content string) error

func Event

func Event(eventName string, session interface{}, next func(bool))

顺序执行事件

func FixDirSeparator

func FixDirSeparator(dir string) string

func Forbidden

func Forbidden(content ...string) error

func FormatDate

func FormatDate(t time.Time, format string) string

func FriendlyBytes

func FriendlyBytes(bytes uint64) string

format bytes number friendly

func FriendlyTime

func FriendlyTime(d time.Duration) string

short string format

func GetAcceptEncodingZip

func GetAcceptEncodingZip(r *http.Request) string

GetAcceptEncodingZip returns accept encoding format in http header. zip is first, then deflate if both accepted. If no accepted, return empty string.

func GoEvent

func GoEvent(eventName string, session interface{}, next func(bool))

并发执行事件

func Html

func Html(raw string) template.HTML

func HtmlAttr

func HtmlAttr(raw string) template.HTMLAttr

func InternalServerError

func InternalServerError(content ...string) error

func IsNil

func IsNil(a interface{}) bool

func JoinPath

func JoinPath(paths ...string) string

func Js

func Js(raw string) template.JS

func MultiAssign

func MultiAssign(t *T)

func NewCookie

func NewCookie(name string, value string, args ...interface{}) *http.Cookie

NewCookie is a helper method that returns a new http.Cookie object. Duration is specified in seconds. If the duration is zero, the cookie is permanent. This can be used in conjunction with ctx.SetCookie.

func NotFound

func NotFound(content ...string) error

func NotSupported

func NotSupported(content ...string) error

func Now

func Now() time.Time

func PKCS5Padding

func PKCS5Padding(ciphertext []byte, blockSize int) []byte

func PKCS5UnPadding

func PKCS5UnPadding(origData []byte) []byte

func PageSize

func PageSize(total, limit int) int

func PrintGCSummary

func PrintGCSummary(w io.Writer)

print gc information to io.Writer

func Process

func Process(w http.ResponseWriter, req *http.Request)

Process invokes the main server's routing system.

func Run

func Run(addr string)

Run starts the web application and serves HTTP requests for the main server.

func RunFcgi

func RunFcgi(addr string)

RunFcgi starts the web application and serves FastCGI requests for the main server.

func RunScgi

func RunScgi(addr string)

RunScgi starts the web application and serves SCGI requests for the main server.

func RunTLS

func RunTLS(addr string, config *tls.Config)

RunTLS starts the web application and serves HTTPS requests for the main server.

func SetLogger

func SetLogger(logger *log.Logger)

SetLogger sets the logger for the main server.

func SetStaticDir

func SetStaticDir(dir string)

func SetTemplateDir

func SetTemplateDir(dir string)

func SimpleParse

func SimpleParse(data string) map[string]string

func SimpleTLSConfig

func SimpleTLSConfig(certFile, keyFile string) (*tls.Config, error)

func Slug

func Slug(s string, sep string) string

Slug is a helper function that returns the URL slug for string s. It's used to return clean, URL-friendly strings that can be used in routing.

func SplitJson

func SplitJson(s string) ([]string, error)

user[name][test]

func StartCPUProfile

func StartCPUProfile()

start cpu profile monitor

func StopCPUProfile

func StopCPUProfile()

stop cpu profile monitor

func Subtract

func Subtract(left interface{}, right interface{}) interface{}

func Ternary

func Ternary(express bool, trueVal interface{}, falseVal interface{}) interface{}

the func is the same as condition ? true : false

func ToHtmlAttrs

func ToHtmlAttrs(raw map[string]interface{}) (r map[template.HTMLAttr]interface{})

func UnTitle

func UnTitle(s string) string

func Unauthorized

func Unauthorized(content ...string) error

func Url

func Url(args ...string) string

Usage:Url("/user/login","appName","servName") or Url("/user/login","appName") or Url("/user/login") or UrlFor()

func UrlFor

func UrlFor(args ...string) string

Usage:UrlFor("main:root:/user/login") or UrlFor("root:/user/login") or UrlFor("/user/login") or UrlFor() 这里的main代表Server名称;root代表App名称;后面的内容为Action中方法函数所对应的网址

func Urlencode

func Urlencode(data map[string]string) string

Urlencode is a helper method that converts a map into URL-encoded form data. It is a useful when constructing HTTP POST requests.

func XsrfName

func XsrfName() string

func ZeroPadding

func ZeroPadding(ciphertext []byte, blockSize int) []byte

func ZeroUnPadding

func ZeroUnPadding(origData []byte) []byte

Types

type AbortError

type AbortError struct {
	Code    int
	Content string
}

func (*AbortError) Error

func (a *AbortError) Error() string

type Action

type Action struct {
	Request *http.Request
	App     *App
	Option  *ActionOption
	http.ResponseWriter
	C reflect.Value

	T T

	RequestBody   []byte
	StatusCode    int
	ResponseSize  int64
	JsonpCallback string
	ExtensionName string

	Exit bool
	// contains filtered or unexported fields
}

An Action object or it's substruct is created for every incoming HTTP request. It provides information about the request, including the http.Request object, the GET and POST params, and acts as a Writer for the response.

func (*Action) Abort

func (c *Action) Abort(status int, body string) error

Abort is a helper method that sends an HTTP header and an optional body. It is useful for returning 4xx or 5xx errors. Once it has been called, any return value from the handler will not be written to the response.

func (*Action) Arg

func (c *Action) Arg(k int) string

func (*Action) Args

func (c *Action) Args() []string

func (*Action) Assign

func (c *Action) Assign(name string, varOrFunc interface{})

add a name value for template

func (*Action) BasePath

func (c *Action) BasePath() string

func (*Action) Body

func (c *Action) Body() []byte

Body returns the raw request body data as bytes.

func (*Action) BuildUrl

func (c *Action) BuildUrl(m string, obj interface{}) (jurl string)

{{"action"|.BuildUrl "list?name=webx"}}

func (*Action) Cookie

func (c *Action) Cookie(key string) string

Cookie returns request cookie item string by a given key. if non-existed, return empty string.

func (*Action) CookieAuthKey

func (c *Action) CookieAuthKey() string

func (*Action) Debug

func (c *Action) Debug(params ...interface{})

func (*Action) Debugf

func (c *Action) Debugf(format string, params ...interface{})

func (*Action) DelSession

func (c *Action) DelSession(keys ...string)

func (*Action) DisableHttpCache

func (c *Action) DisableHttpCache()

func (*Action) Domain

func (c *Action) Domain() string

Domain returns host name. Alias of Host method.

func (*Action) Error

func (c *Action) Error(params ...interface{})

func (*Action) Errorf

func (c *Action) Errorf(format string, params ...interface{})

func (*Action) Fatal

func (c *Action) Fatal(params ...interface{})

func (*Action) Fatalf

func (c *Action) Fatalf(format string, params ...interface{})

func (*Action) Flush

func (c *Action) Flush()

func (*Action) GetBool

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

func (*Action) GetConfig

func (c *Action) GetConfig(name string) interface{}

func (*Action) GetConfigString

func (c *Action) GetConfigString(name string) string

func (*Action) GetCookie

func (c *Action) GetCookie(cookieName string) (*http.Cookie, error)

func (*Action) GetFile

func (c *Action) GetFile(key string) (multipart.File, *multipart.FileHeader, error)

func (*Action) GetFloat

func (c *Action) GetFloat(key string) (float64, error)

func (*Action) GetForm

func (c *Action) GetForm() url.Values

func (*Action) GetFuncs

func (c *Action) GetFuncs() template.FuncMap

func (*Action) GetInt

func (c *Action) GetInt(key string) (int64, error)

func (*Action) GetLogger

func (c *Action) GetLogger() *log.Logger

func (*Action) GetSecureCookie

func (c *Action) GetSecureCookie(name string) (string, bool)

func (*Action) GetSession

func (c *Action) GetSession(key string) interface{}

func (*Action) GetSlice

func (c *Action) GetSlice(key string) []string

func (*Action) GetString

func (c *Action) GetString(key string) string

func (*Action) Go

func (c *Action) Go(m string, anotherc ...interface{}) error

func (*Action) Header

func (c *Action) Header(key string) string

Header returns request header item string by a given string.

func (*Action) Host

func (c *Action) Host() string

Host returns host name. if no host info in request, return localhost.

func (*Action) HttpCache

func (c *Action) HttpCache(content []byte) bool

func (*Action) IP

func (c *Action) IP() string

ClientIP implements a best effort algorithm to return the real client IP, it parses X-Real-IP and X-Forwarded-For in order to work properly with reverse-proxies such us: nginx or haproxy.

func (*Action) Include

func (c *Action) Include(tmplName string, args ...interface{}) interface{}

Include method provide to template for {{include "webx"}}

func (*Action) Info

func (c *Action) Info(params ...interface{})

func (*Action) Infof

func (c *Action) Infof(format string, params ...interface{})

func (*Action) Is

func (c *Action) Is(method string) bool

Is returns boolean of this request is on given method, such as Is("POST").

func (*Action) IsAjax

func (c *Action) IsAjax() bool

IsAjax returns boolean of this request is generated by ajax.

func (*Action) IsSecure

func (c *Action) IsSecure() bool

IsSecure returns boolean of this request is in https.

func (*Action) IsUpload

func (c *Action) IsUpload() bool

IsSecure returns boolean of whether file uploads in this request or not..

func (*Action) IsWebsocket

func (c *Action) IsWebsocket() bool

IsSecure returns boolean of this request is in webSocket.

func (*Action) MapForm

func (c *Action) MapForm(st interface{}, names ...string) error

ParseStruct mapping forms' name and values to struct's field For example:

<form>
	<input name="user.id"/>
	<input name="user.name"/>
	<input name="user.age"/>
</form>

type User struct {
	Id int64
	Name string
	Age string
}

var user User
err := action.MapForm(&user)

func (*Action) Method

func (c *Action) Method() string

func (*Action) MultiAssign

func (c *Action) MultiAssign(t *T)

add names and values for template

func (*Action) NamedRender

func (c *Action) NamedRender(name, content string, params ...*T) error

render the template with vars map, you can have zero or one map

func (*Action) Namespace

func (c *Action) Namespace() string

func (*Action) NewCookie

func (c *Action) NewCookie(name string, value string, args ...interface{}) *http.Cookie

func (*Action) NotFound

func (c *Action) NotFound(message string) error

NotFound writes a 404 HTTP response

func (*Action) NotModified

func (c *Action) NotModified()

Notmodified writes a 304 HTTP response

func (*Action) Panic

func (c *Action) Panic(params ...interface{})

func (*Action) Panicf

func (c *Action) Panicf(format string, params ...interface{})

func (*Action) Port

func (c *Action) Port() int

Port returns request client port. when error or empty, return 80.

func (*Action) Protocol

func (c *Action) Protocol() string

Protocol returns request protocol name, such as HTTP/1.1 .

func (*Action) Proxy

func (c *Action) Proxy() []string

Proxy returns proxy client ips slice.

func (*Action) Query

func (c *Action) Query(key string) string

Query returns input data item string by a given string.

func (*Action) Redirect

func (c *Action) Redirect(url string, status ...int) error

Redirect is a helper method for 3xx redirects.

func (*Action) Refer

func (c *Action) Refer() string

Refer returns http referer header.

func (*Action) Render

func (c *Action) Render(tmpl string, params ...*T) (err error)

render the template with vars map, you can have zero or one map

func (*Action) RenderString

func (c *Action) RenderString(content string, params ...*T) error

func (*Action) SaveToFile

func (c *Action) SaveToFile(fromfile, tofile string) error

func (*Action) Scheme

func (c *Action) Scheme() string

Scheme returns request scheme as "http" or "https".

func (*Action) Self

func (c *Action) Self() interface{}

func (*Action) ServeFile

func (c *Action) ServeFile(fpath string)

func (*Action) ServeJson

func (c *Action) ServeJson(obj interface{})

func (*Action) ServeJsonp

func (c *Action) ServeJsonp(obj interface{}, callback string)

func (*Action) ServeXml

func (c *Action) ServeXml(obj interface{})

func (*Action) Session

func (c *Action) Session() *httpsession.Session

func (*Action) SetArg

func (c *Action) SetArg(k int, v string) bool

func (*Action) SetBody

func (c *Action) SetBody(content []byte) error

Body sets response body content. if EnableGzip, compress content string. it sends out response body directly.

func (*Action) SetConfig

func (c *Action) SetConfig(name string, value interface{})

func (*Action) SetConfigString

func (c *Action) SetConfigString(name string, value string)

func (*Action) SetContentType

func (c *Action) SetContentType(val string) string

ContentType sets the Content-Type header for an HTTP response. For example, c.ContentType("json") sets the content-type to "application/json" If the supplied value contains a slash (/) it is set as the Content-Type verbatim. The return value is the content type as it was set, or an empty string if none was found.

func (*Action) SetCookie

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

SetCookie adds a cookie header to the response.

func (*Action) SetHeader

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

SetHeader sets a response header. the current value of that header will be overwritten .

func (*Action) SetSecureCookie

func (c *Action) SetSecureCookie(name string, val string, args ...interface{})

func (*Action) SetSession

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

func (*Action) Site

func (c *Action) Site() string

Site returns base site url as scheme://domain type.

func (*Action) SubDomains

func (c *Action) SubDomains() string

SubDomains returns sub domain string. if aa.bb.domain.com, returns aa.bb .

func (*Action) Uri

func (c *Action) Uri() string

Uri returns full request url with query string, fragment.

func (*Action) Url

func (c *Action) Url() string

Url returns request url path (without query string, fragment).

func (*Action) UserAgent

func (c *Action) UserAgent() string

UserAgent returns request client user agent string.

func (*Action) Warn

func (c *Action) Warn(params ...interface{})

func (*Action) Warnf

func (c *Action) Warnf(format string, params ...interface{})

func (*Action) Write

func (c *Action) Write(content string, values ...interface{}) error

func (*Action) WriteBytes

func (c *Action) WriteBytes(bytes []byte) error

WriteString writes string data into the response object.

func (*Action) XsrfFormHtml

func (c *Action) XsrfFormHtml() template.HTML

func (*Action) XsrfValue

func (c *Action) XsrfValue() string

type ActionInformation

type ActionInformation struct {
	*Action
	ContentString *string
	ContentByte   *[]byte
}

type ActionOption

type ActionOption struct {
	AutoMapForm bool
	CheckXsrf   bool
}

type AesCrypto

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

func (*AesCrypto) Decode

func (c *AesCrypto) Decode(cryptedData, authKey string) string

func (*AesCrypto) Encode

func (c *AesCrypto) Encode(rawData, authKey string) string

type App

type App struct {
	BasePath string
	Name     string
	Domain   string
	Route    *route.Route

	Server          *Server
	AppConfig       *AppConfig
	Config          *CONF
	Actions         map[string]interface{}
	ReflectedType   map[string]reflect.Type
	Controllers     map[reflect.Type]*sync.Pool
	Urls            map[reflect.Type]map[string]*TagMapper
	FuncMaps        template.FuncMap
	Logger          *log.Logger
	VarMaps         T
	SessionManager  *httpsession.Manager //Session manager
	RootTemplate    *template.Template
	ErrorTemplate   *template.Template
	StaticVerMgr    *StaticVerMgr
	TemplateEx      *tplex.TemplateEx
	ContentEncoding string
	RequestTime     time.Time

	RouteValidator  func(*App, string) (string, error)
	ActionValidator func(*App, reflect.Type, reflect.Value) bool
	Cryptor
	XsrfManager
	// contains filtered or unexported fields
}

func NewApp

func NewApp(path string, name string) *App

func RootApp

func RootApp() *App

func (*App) Action

func (app *App) Action(name string) interface{}

func (*App) AddAction

func (app *App) AddAction(cs ...interface{})

func (*App) AddFilter

func (app *App) AddFilter(filter Filter)

func (*App) AddRouter

func (app *App) AddRouter(url string, c interface{})

func (*App) Assign

func (app *App) Assign(name string, varOrFun interface{})

func (*App) AutoAction

func (app *App) AutoAction(cs ...interface{})

func (*App) Close

func (a *App) Close()

func (*App) Debug

func (app *App) Debug(params ...interface{})

func (*App) Debugf

func (app *App) Debugf(format string, params ...interface{})

func (*App) DelDomain

func (a *App) DelDomain()

func (*App) ElapsedTime

func (a *App) ElapsedTime() float64

func (*App) ElapsedTimeString

func (a *App) ElapsedTimeString() string

func (*App) Error

func (app *App) Error(params ...interface{})

func (*App) Errorf

func (app *App) Errorf(format string, params ...interface{})

func (*App) Fatal

func (app *App) Fatal(params ...interface{})

func (*App) Fatalf

func (app *App) Fatalf(format string, params ...interface{})

func (*App) GetConfig

func (app *App) GetConfig(name string) interface{}

func (*App) GetConfigString

func (app *App) GetConfigString(name string) string

func (*App) Info

func (app *App) Info(params ...interface{})

func (*App) Infof

func (app *App) Infof(format string, params ...interface{})

func (*App) InitHeadContent

func (a *App) InitHeadContent(w http.ResponseWriter, contentLength int64)

Init content-length header.

func (*App) IsRootApp

func (a *App) IsRootApp() bool

func (*App) MultiAssign

func (app *App) MultiAssign(t *T)

func (*App) Nodes

func (app *App) Nodes() (r map[string]map[string][]string)

example:

{
	"AdminAction":{
		"Index":["GET","POST"],
		"Add":	["GET","POST"],
		"Edit":	["GET","POST"]
	}
}

func (*App) Panic

func (app *App) Panic(params ...interface{})

func (*App) Panicf

func (app *App) Panicf(format string, params ...interface{})

func (*App) Redirect

func (app *App) Redirect(w http.ResponseWriter, requestPath, url string, status ...int) error

func (*App) SafelyCall

func (a *App) SafelyCall(fn reflect.Value, args []reflect.Value) (resp []reflect.Value, err error)

safelyCall invokes `function` in recover block

func (*App) SetConfig

func (app *App) SetConfig(name string, val interface{})

func (*App) SetConfigString

func (app *App) SetConfigString(name string, val string)

func (*App) SetDomain

func (a *App) SetDomain(domain string)

func (*App) SetStaticDir

func (a *App) SetStaticDir(dir string)

func (*App) SetTemplateDir

func (a *App) SetTemplateDir(path string)

func (*App) StaticUrl

func (a *App) StaticUrl(url string) string

func (*App) StructMap

func (a *App) StructMap(m interface{}, r *http.Request) error

StructMap function mapping params to controller's properties

func (*App) TryServingFile

func (a *App) TryServingFile(name string, req *http.Request, w http.ResponseWriter) (bool, int64)

tryServingFile attempts to serve a static file, and returns whether or not the operation is successful.

func (*App) VisitedLog

func (a *App) VisitedLog(req *http.Request, statusCode int, requestPath string, responseSize int64)

func (*App) Warn

func (app *App) Warn(params ...interface{})

func (*App) Warnf

func (app *App) Warnf(format string, params ...interface{})

type AppConfig

type AppConfig struct {
	Mode              int
	StaticDir         string
	TemplateDir       string
	TemplateTheme     string
	TemplateStyle     string
	SessionOn         bool
	MaxUploadSize     int64
	CookieSecret      string
	CookieLimitIP     bool
	CookieLimitUA     bool
	CookiePrefix      string
	CookieDomain      string
	StaticFileVersion bool
	CacheTemplates    bool
	ReloadTemplates   bool
	CheckXsrf         bool
	SessionTimeout    time.Duration
	FormMapToStruct   bool
	EnableHttpCache   bool
	AuthBasedOnCookie bool
	StaticFileParser  map[string]func(string, *http.Request, http.ResponseWriter) (bool, int64)
}

func NewAppConfig

func NewAppConfig() *AppConfig

type AutoResponse

type AutoResponse struct {
}

func (*AutoResponse) Do

func (s *AutoResponse) Do(c *Action, ret []reflect.Value) error

type CONF

type CONF struct {
	Bool      map[string]bool
	Interface map[string]interface{}
	String    map[string]string
	Int       map[string]int64
	Float     map[string]float64
	Byte      map[string][]byte
	Conf      map[string]*CONF
}

func NewCONF

func NewCONF() *CONF

func (*CONF) DelBool

func (a *CONF) DelBool(k string)

func (*CONF) DelByte

func (a *CONF) DelByte(k string)

func (*CONF) DelConf

func (a *CONF) DelConf(k string)

func (*CONF) DelFloat

func (a *CONF) DelFloat(k string)

func (*CONF) DelInt

func (a *CONF) DelInt(k string)

func (*CONF) DelInterface

func (a *CONF) DelInterface(k string)

func (*CONF) DelString

func (a *CONF) DelString(k string)

func (*CONF) GetBool

func (a *CONF) GetBool(k string) bool

func (*CONF) GetByte

func (a *CONF) GetByte(k string) []byte

func (*CONF) GetConf

func (a *CONF) GetConf(k string) *CONF

func (*CONF) GetFloat

func (a *CONF) GetFloat(k string) float64

func (*CONF) GetInt

func (a *CONF) GetInt(k string) int64

func (*CONF) GetInterface

func (a *CONF) GetInterface(k string) interface{}

func (*CONF) GetString

func (a *CONF) GetString(k string) string

func (*CONF) Init

func (a *CONF) Init()

func (*CONF) InitBool

func (a *CONF) InitBool()

func (*CONF) InitByte

func (a *CONF) InitByte()

func (*CONF) InitConf

func (a *CONF) InitConf()

func (*CONF) InitFloat

func (a *CONF) InitFloat()

func (*CONF) InitInt

func (a *CONF) InitInt()

func (*CONF) InitInterface

func (a *CONF) InitInterface()

func (*CONF) InitString

func (a *CONF) InitString()

func (*CONF) SetBool

func (a *CONF) SetBool(k string, v bool)

func (*CONF) SetByte

func (a *CONF) SetByte(k string, v []byte)

func (*CONF) SetConf

func (a *CONF) SetConf(k string, v *CONF)

func (*CONF) SetFloat

func (a *CONF) SetFloat(k string, v float64)

func (*CONF) SetInt

func (a *CONF) SetInt(k string, v int64)

func (*CONF) SetInterface

func (a *CONF) SetInterface(k string, v interface{})

func (*CONF) SetString

func (a *CONF) SetString(k string, v string)

type Cryptor

type Cryptor interface {
	Encode(rawData, authKey string) string
	Decode(cryptedData, authKey string) string
}
var DefaultCryptor Cryptor = &AesCrypto{key: make(map[string][]byte, 0)}

type EventsInstance

type EventsInstance struct {
	// contains filtered or unexported fields
}
var Events *EventsInstance = NewEvents()

func NewEvents

func NewEvents() *EventsInstance

func (*EventsInstance) Delete

func (e *EventsInstance) Delete(eventName string)

func (*EventsInstance) Execute

func (e *EventsInstance) Execute(eventName string, session interface{}, next func(bool))

*

  • 顺序执行事件

func (*EventsInstance) GoExecute

func (e *EventsInstance) GoExecute(eventName string, session interface{}, next func(bool))

并发执行事件 [Examle 1:] Events.GoExecute("AfterHandler", session, func(_ bool) {//此匿名函数在本事件的最后执行

	session.Response.Send()
	session.Response.Close()
})

[Examle 2:] Events.Execute("AfterResponse", session, func(_ bool) {})

func (*EventsInstance) Register

func (e *EventsInstance) Register(eventName string, handler func(interface{}, func(bool)))

注册事件 [Examle:]

Events.Register("AfterResponse", func(session interface{}, next func(bool)) {
	log.Println("Got AfterResponse event!")
	isSuccess := true
	next(isSuccess) //这里的next函数无论什么情况下必须执行。
})

采用不同的方式执行事件时,此处的next函数的作用也是不同的: 1、在并发执行事件的时候,next函数的作用是通知程序我已经执行完了(不理会这一步是否执行成功); 2、在顺序执行事件的时候,next函数的作用是通知程序是否继续执行下一步,next(true)是继续执行下一步,next(false)是终止执行下一步

type FILE

type FILE struct {
	Data string
}

type Filter

type Filter interface {
	Do(http.ResponseWriter, *http.Request) bool
}

type FromConversion

type FromConversion interface {
	FromString(content string) error
}

a struct implements this interface can be convert from request param to a struct

type JSON

type JSON struct {
	Data interface{}
}

type JSONP

type JSONP struct {
	Data     interface{}
	Callback string
}

type JSONResponse

type JSONResponse struct {
	Status  int
	Message interface{}
	Data    interface{}
}

func (*JSONResponse) Do

func (j *JSONResponse) Do(c *Action, ret []reflect.Value) error

type JUMP

type JUMP struct {
	Url  string
	Code int
}

type LoginFilter

type LoginFilter struct {
	App           *App
	SessionName   string
	AnonymousUrls []*regexp.Regexp
	AskLoginUrls  []*regexp.Regexp
	Redirect      string
}

func NewLoginFilter

func NewLoginFilter(app *App, name string, redirect string) *LoginFilter

func (*LoginFilter) AddAnonymousUrls

func (s *LoginFilter) AddAnonymousUrls(urls ...string)

func (*LoginFilter) AddAskLoginUrls

func (s *LoginFilter) AddAskLoginUrls(urls ...string)

func (*LoginFilter) Do

type Mapper

type Mapper struct{}

type MemFile

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

MemFile contains MemFileInfo and bytes offset when reading. it implements io.Reader,io.ReadCloser and io.Seeker.

func OpenMemZipFile

func OpenMemZipFile(path string, zip string) (*MemFile, error)

OpenMemZipFile returns MemFile object with a compressed static file. it's used for serve static file if gzip enable.

func (*MemFile) Close

func (f *MemFile) Close() error

Close memfile.

func (*MemFile) Read

func (f *MemFile) Read(p []byte) (n int, err error)

Read bytes from the compressed file bytes.

func (*MemFile) Readdir

func (f *MemFile) Readdir(count int) ([]os.FileInfo, error)

read os.FileInfo of files in directory of memfile. it returns empty slice.

func (*MemFile) Seek

func (f *MemFile) Seek(offset int64, whence int) (ret int64, err error)

Read bytes from the compressed file bytes by seeker.

func (*MemFile) Stat

func (f *MemFile) Stat() (os.FileInfo, error)

Get os.FileInfo of memfile.

type MemFileInfo

type MemFileInfo struct {
	os.FileInfo
	// contains filtered or unexported fields
}

MemFileInfo contains a compressed file bytes and file information. it implements os.FileInfo interface.

func (*MemFileInfo) IsDir

func (fi *MemFileInfo) IsDir() bool

IsDir returns the compressing file is a directory or not.

func (*MemFileInfo) ModTime

func (fi *MemFileInfo) ModTime() time.Time

ModTime returns the last modified time of raw file.

func (*MemFileInfo) Mode

func (fi *MemFileInfo) Mode() os.FileMode

Mode returns file mode.

func (*MemFileInfo) Name

func (fi *MemFileInfo) Name() string

Name returns the compressed filename.

func (*MemFileInfo) Size

func (fi *MemFileInfo) Size() int64

Size returns the raw file content size, not compressed size.

func (*MemFileInfo) Sys

func (fi *MemFileInfo) Sys() interface{}

return nil. implement the os.FileInfo interface method.

type Reflected

type Reflected struct {
	NameV           reflect.Value
	StructV         reflect.Value
	HasFieldAction  bool
	HasMethodInit   bool
	HasMethodBefore bool
	HasMethodAfter  bool
	FieldAction     reflect.Value
	MethodInit      reflect.Value
	MethodBefore    reflect.Value
	MethodAfter     reflect.Value
	MethodByPath    map[string]reflect.Value
}

type Response

type Response interface {
	Do(ret []reflect.Value)
}

type SHOW

type SHOW struct {
	Tmpl string
	*T
}

type Server

type Server struct {
	Config         *ServerConfig
	Apps           map[string]*App   //r["root"]
	App2Domain     map[string]string //r["root"]="www.coscms.com"
	Domain2App     map[string]string //r["www.coscms.com"]="root"
	AppsNamePath   map[string]string //r["root"]="/"
	Name           string
	SessionManager *httpsession.Manager
	RootApp        *App
	Logger         *log.Logger
	Env            map[string]interface{}
	Mux            *http.ServeMux
	// contains filtered or unexported fields
}

Server represents a webx server.

func MainServer

func MainServer() *Server

func NewServer

func NewServer(name string, args ...*ServerConfig) *Server

func Serv

func Serv(name string) *Server

func (*Server) AddAction

func (s *Server) AddAction(cs ...interface{})

func (*Server) AddApp

func (s *Server) AddApp(a *App)

func (*Server) AddConfig

func (s *Server) AddConfig(name string, value interface{})

func (*Server) AddFilter

func (s *Server) AddFilter(filter Filter)

func (*Server) AddRouter

func (s *Server) AddRouter(url string, c interface{})

func (*Server) App

func (s *Server) App(name string) *App

func (*Server) Assign

func (s *Server) Assign(name string, varOrFun interface{})

func (*Server) AutoAction

func (s *Server) AutoAction(c ...interface{})

func (*Server) Close

func (s *Server) Close()

Close stops server s.

func (*Server) GetConfig

func (s *Server) GetConfig(name string) interface{}

func (*Server) InitSession

func (s *Server) InitSession()

func (*Server) IsRunning

func (s *Server) IsRunning() bool

func (*Server) MultiAssign

func (s *Server) MultiAssign(t *T)

func (*Server) Process

func (s *Server) Process(w http.ResponseWriter, req *http.Request)

Process invokes the routing system for server s non-root app's route will override root app's if there is same path

func (*Server) Run

func (s *Server) Run(addr string) error

Run starts the web application and serves HTTP requests for s

func (*Server) RunFcgi

func (s *Server) RunFcgi(addr string)

RunFcgi starts the web application and serves FastCGI requests for s.

func (*Server) RunScgi

func (s *Server) RunScgi(addr string)

RunScgi starts the web application and serves SCGI requests for s.

func (*Server) RunTLS

func (s *Server) RunTLS(addr string, config *tls.Config) error

RunTLS starts the web application and serves HTTPS requests for s.

func (*Server) ServeHTTP

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

ServeHTTP is the interface method for Go's http server package

func (*Server) SetConfig

func (s *Server) SetConfig(name string, value interface{})

func (*Server) SetLogger

func (s *Server) SetLogger(logger *log.Logger)

SetLogger sets the logger for server s

func (*Server) SetStaticDir

func (s *Server) SetStaticDir(path string)

func (*Server) SetTemplateDir

func (s *Server) SetTemplateDir(path string)

type ServerConfig

type ServerConfig struct {
	Addr                   string
	Port                   int
	RecoverPanic           bool
	Profiler               bool
	EnableGzip             bool
	StaticExtensionsToGzip []string
	Url                    string
	UrlPrefix              string
	UrlSuffix              string
	StaticHtmlDir          string
	SessionTimeout         time.Duration
	MaxConnections         int
	UseSSL                 bool
	TlsConfig              *tls.Config
	Debug                  bool
	GracefulShutdown       bool
}

ServerConfig is configuration for server objects.

var (
	Config *ServerConfig = &ServerConfig{
		RecoverPanic:           true,
		EnableGzip:             true,
		Profiler:               false,
		StaticExtensionsToGzip: []string{".css", ".js"},
		GracefulShutdown:       true,
	}
	Servers map[string]*Server = make(map[string]*Server) //[SWH|+]

)

Config is the configuration of the main server.

type ServerInformation

type ServerInformation struct {
	*Server
	http.ResponseWriter
	*http.Request
}

type StaticVerMgr

type StaticVerMgr struct {
	Caches   map[string]string
	Combined map[string][]string
	Combines map[string]bool

	Path    string
	Ignores map[string]bool

	TimerCallback func() bool
	// contains filtered or unexported fields
}
var DefaultStaticVerMgr *StaticVerMgr = new(StaticVerMgr)

func (*StaticVerMgr) CacheAll

func (self *StaticVerMgr) CacheAll(staticPath string) error

func (*StaticVerMgr) CacheDelete

func (self *StaticVerMgr) CacheDelete(url string)

func (*StaticVerMgr) CacheItem

func (self *StaticVerMgr) CacheItem(url string)

func (*StaticVerMgr) Close

func (self *StaticVerMgr) Close()

func (*StaticVerMgr) DeleteCombined

func (self *StaticVerMgr) DeleteCombined(url string)

func (*StaticVerMgr) GetVersion

func (self *StaticVerMgr) GetVersion(url string) string

func (*StaticVerMgr) Init

func (self *StaticVerMgr) Init(app *App, staticPath string) error

func (*StaticVerMgr) IsCombined

func (self *StaticVerMgr) IsCombined(combineUrl string) (ok bool)

func (*StaticVerMgr) Moniter

func (self *StaticVerMgr) Moniter(staticPath string) error

func (*StaticVerMgr) RecordCombined

func (self *StaticVerMgr) RecordCombined(fromUrl string, combineUrl string)

func (*StaticVerMgr) RecordCombines

func (self *StaticVerMgr) RecordCombines(combineUrl string)

type T

type T map[string]interface{}

type TagMapper

type TagMapper struct {
	RawUrl string
	Mapper map[string][2]string
	Memo   string
}

func NewTagMapper

func NewTagMapper(rawUrl string) *TagMapper

func (*TagMapper) GenUrl

func (m *TagMapper) GenUrl(vals interface{}) (r string)

func (*TagMapper) Replace

func (m *TagMapper) Replace(r string, v string, mapper [2]string) string

type ToConversion

type ToConversion interface {
	ToString() string
}

a struct implements this interface can be convert from struct to template variable Not Implemented

type XML

type XML struct {
	Data interface{}
}

type XMLResponse

type XMLResponse struct {
	Status  int
	Message interface{}
	Data    interface{}
}

func (*XMLResponse) Do

func (x *XMLResponse) Do(c *Action, ret []reflect.Value) error

type XsrfCookieStorage

type XsrfCookieStorage struct {
	*Action
}

func (*XsrfCookieStorage) Get

func (c *XsrfCookieStorage) Get(key string) string

func (*XsrfCookieStorage) Init

func (c *XsrfCookieStorage) Init(a *Action)

func (*XsrfCookieStorage) Set

func (c *XsrfCookieStorage) Set(key, val string)

func (*XsrfCookieStorage) Valid

func (c *XsrfCookieStorage) Valid(key, val string) bool

type XsrfManager

type XsrfManager interface {
	Init(*Action)
	Get(key string) string
	Set(key, val string)
	Valid(key, val string) bool
}
var DefaultXsrfManager XsrfManager = &XsrfCookieStorage{}

type XsrfSessionStorage

type XsrfSessionStorage struct {
	*Action
}

func (*XsrfSessionStorage) Get

func (c *XsrfSessionStorage) Get(key string) string

func (*XsrfSessionStorage) Init

func (c *XsrfSessionStorage) Init(a *Action)

func (*XsrfSessionStorage) Set

func (c *XsrfSessionStorage) Set(key, val string)

func (*XsrfSessionStorage) Valid

func (c *XsrfSessionStorage) Valid(key, val string) bool

Directories

Path Synopsis
lib
get
httpsession
Package httpsession is a http server session implement for Go.
Package httpsession is a http server session implement for Go.
log
str
tplex
* * 模板扩展 * @author swh <swh@admpub.com>
* * 模板扩展 * @author swh <swh@admpub.com>
uuid
The uuid package generates and inspects UUIDs.
The uuid package generates and inspects UUIDs.

Jump to

Keyboard shortcuts

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