Documentation ¶
Overview ¶
Package xweb is a simple and powerful web framework for Go.
Installation ¶
Make sure you have installed Go 1.1+ and then:
go get github.com/lunny/xweb
More usage, please visit https://github.com/lunny/xweb/
*********************** [钩子引擎 (version 0.3)] @author:S.W.H @E-mail:swh@admpub.com @update:2014-01-18 ***********************
Package web is a lightweight web framework for Go. It's ideal for writing simple, performant backend web services.
Index ¶
- Constants
- Variables
- func Abort(code int, content ...string) error
- func Add(left interface{}, right interface{}) interface{}
- func AddAction(c ...interface{})
- func AddApp(a *App)
- func AddConfig(name string, value interface{})
- func AddFilter(filter Filter)
- func AddHook(name string, fns ...interface{})
- func AddRouter(url string, c interface{})
- func AddTmplVar(name string, varOrFun interface{})
- func AddTmplVars(t *T)
- func AutoAction(c ...interface{})
- func AvgTime(items []time.Duration) time.Duration
- func Close()
- func CloseZWriter(zwriter io.Writer)
- func Download(w http.ResponseWriter, fpath string) error
- func Eq(left interface{}, right interface{}) bool
- func Error(w http.ResponseWriter, status int, content string) error
- func Forbidden(content ...string) error
- func FormatDate(t time.Time, format string) string
- func FriendlyBytes(bytes uint64) string
- func FriendlyTime(d time.Duration) string
- func GetAcceptEncodingZip(r *http.Request) string
- func Html(raw string) template.HTML
- func InternalServerError(content ...string) error
- func IsNil(a interface{}) bool
- func JoinPath(paths ...string) string
- func NewCookie(name string, value string, age int64) *http.Cookie
- func NotFound(content ...string) error
- func NotSupported(content ...string) error
- func Now() time.Time
- func PageSize(total, limit int) int
- func PrintGCSummary(w io.Writer)
- func Process(c http.ResponseWriter, req *http.Request)
- func Run(addr string)
- func RunFcgi(addr string)
- func RunScgi(addr string)
- func RunTLS(addr string, config *tls.Config)
- func SetLogger(logger *log.Logger)
- func SetStaticDir(dir string)
- func SetTemplateDir(dir string)
- func SimpleParse(data string) map[string]string
- func SimpleTLSConfig(certFile, keyFile string) (*tls.Config, error)
- func Slug(s string, sep string) string
- func StartCPUProfile()
- func StopCPUProfile()
- func Subtract(left interface{}, right interface{}) interface{}
- func Ternary(express bool, trueVal interface{}, falseVal interface{}) interface{}
- func UnTitle(s string) string
- func Unauthorized(content ...string) error
- func UrlFor(args ...string) string
- func Urlencode(data map[string]string) string
- func XsrfName() string
- type AbortError
- type Action
- func (c *Action) Abort(status int, body string) error
- func (c *Action) AddTmplVar(name string, varOrFunc interface{})
- func (c *Action) AddTmplVars(t *T)
- func (c *Action) BasePath() string
- func (c *Action) Body() []byte
- func (c *Action) Cookie(key string) string
- func (c *Action) Critical(format string, params ...interface{})
- func (c *Action) Debug(format string, params ...interface{})
- func (c *Action) DelSession(key string)
- func (c *Action) DisableHttpCache()
- func (c *Action) Domain() string
- func (c *Action) Error(format string, params ...interface{})
- func (c *Action) Flush()
- func (c *Action) GetBool(key string) (bool, error)
- func (c *Action) GetConfig(name string) interface{}
- func (c *Action) GetCookie(cookieName string) (*http.Cookie, error)
- func (c *Action) GetFile(key string) (multipart.File, *multipart.FileHeader, error)
- func (c *Action) GetFloat(key string) (float64, error)
- func (c *Action) GetForm() url.Values
- func (c *Action) GetFuncs() template.FuncMap
- func (c *Action) GetInt(key string) (int64, error)
- func (c *Action) GetLogger() *log.Logger
- func (c *Action) GetSecureCookie(name string) (string, bool)
- func (c *Action) GetSession(key string) interface{}
- func (c *Action) GetSlice(key string) []string
- func (c *Action) GetString(key string) string
- func (c *Action) Go(m string, anotherc ...interface{}) error
- func (c *Action) Header(key string) string
- func (c *Action) Host() string
- func (c *Action) HttpCache(content []byte) bool
- func (c *Action) IP() string
- func (c *Action) Include(tmplName string) interface{}
- func (c *Action) Info(format string, params ...interface{})
- func (c *Action) Is(method string) bool
- func (c *Action) IsAjax() bool
- func (c *Action) IsSecure() bool
- func (c *Action) IsUpload() bool
- func (c *Action) IsWebsocket() bool
- func (c *Action) MapForm(st interface{}, names ...string) error
- func (c *Action) Method() string
- func (c *Action) NamedRender(name, content string, params ...*T) error
- func (c *Action) Namespace() string
- func (c *Action) NotFound(message string) error
- func (c *Action) NotModified()
- func (c *Action) Port() int
- func (c *Action) Protocol() string
- func (c *Action) Proxy() []string
- func (c *Action) Query(key string) string
- func (c *Action) Redirect(url string, status ...int) error
- func (c *Action) Refer() string
- func (c *Action) Render(tmpl string, params ...*T) error
- func (c *Action) RenderString(content string, params ...*T) error
- func (c *Action) SaveToFile(fromfile, tofile string) error
- func (c *Action) Scheme() string
- func (c *Action) ServeJson(obj interface{})
- func (c *Action) ServeXml(obj interface{})
- func (c *Action) Session() *httpsession.Session
- func (c *Action) SetBody(content []byte) error
- func (c *Action) SetContentType(val string) string
- func (c *Action) SetCookie(cookie *http.Cookie)
- func (c *Action) SetHeader(key string, value string)
- func (c *Action) SetSecureCookie(name string, val string, age int64)
- func (c *Action) SetSession(key string, value interface{})
- func (c *Action) Site() string
- func (c *Action) SubDomains() string
- func (c *Action) Trace(format string, params ...interface{})
- func (c *Action) Uri() string
- func (c *Action) Url() string
- func (c *Action) UserAgent() string
- func (c *Action) Warn(format string, params ...interface{})
- func (c *Action) Write(content string, values ...interface{}) error
- func (c *Action) WriteBytes(bytes []byte) error
- func (c *Action) XsrfFormHtml() template.HTML
- func (c *Action) XsrfValue() string
- type ActionOption
- type App
- func (app *App) AddAction(cs ...interface{})
- func (app *App) AddFilter(filter Filter)
- func (app *App) AddRouter(url string, c interface{})
- func (app *App) AddTmplVar(name string, varOrFun interface{})
- func (app *App) AddTmplVars(t *T)
- func (app *App) AutoAction(cs ...interface{})
- func (app *App) Critical(format string, params ...interface{})
- func (app *App) Debug(format string, params ...interface{})
- func (app *App) Error(format string, params ...interface{})
- func (app *App) GetConfig(name string) interface{}
- func (app *App) Info(format string, params ...interface{})
- func (a *App) InitHeadContent(w http.ResponseWriter, contentLength int64)
- func (app *App) Nodes() (r map[string][]string)
- func (app *App) Redirect(w http.ResponseWriter, requestPath, url string, status ...int) error
- func (a *App) SafelyCall(vc reflect.Value, method string, args []reflect.Value) (resp []reflect.Value, err error)
- func (app *App) SetConfig(name string, val interface{})
- func (a *App) SetStaticDir(dir string)
- func (a *App) SetTemplateDir(path string)
- func (a *App) StaticUrl(url string) string
- func (a *App) StructMap(vc reflect.Value, r *http.Request) error
- func (app *App) Trace(format string, params ...interface{})
- func (a *App) TryServingFile(name string, req *http.Request, w http.ResponseWriter) bool
- func (app *App) Warn(format string, params ...interface{})
- type AppConfig
- type AutoResponse
- type Filter
- type FromConversion
- type Hook
- type HookEngine
- type JSONResponse
- type LoginFilter
- type Mapper
- type MemFile
- type MemFileInfo
- type Response
- type Route
- type Server
- func (s *Server) AddAction(cs ...interface{})
- func (s *Server) AddApp(a *App)
- func (s *Server) AddConfig(name string, value interface{})
- func (s *Server) AddFilter(filter Filter)
- func (s *Server) AddRouter(url string, c interface{})
- func (s *Server) AddTmplVar(name string, varOrFun interface{})
- func (s *Server) AddTmplVars(t *T)
- func (s *Server) App(name string) *App
- func (s *Server) AutoAction(c ...interface{})
- func (s *Server) Close()
- func (s *Server) Critical(format string, params ...interface{})
- func (s *Server) Debug(format string, params ...interface{})
- func (s *Server) Error(format string, params ...interface{})
- func (s *Server) Info(format string, params ...interface{})
- func (s *Server) Process(w http.ResponseWriter, req *http.Request)
- func (s *Server) Run(addr string)
- func (s *Server) RunFcgi(addr string)
- func (s *Server) RunScgi(addr string)
- func (s *Server) RunTLS(addr string, config *tls.Config) error
- func (s *Server) ServeHTTP(c http.ResponseWriter, req *http.Request)
- func (s *Server) SetLogger(logger *log.Logger)
- func (s *Server) SetStaticDir(path string)
- func (s *Server) SetTemplateDir(path string)
- func (s *Server) Trace(format string, params ...interface{})
- func (s *Server) Warn(format string, params ...interface{})
- type ServerConfig
- type StaticVerMgr
- type T
- type TemplateMgr
- func (self *TemplateMgr) CacheAll(rootDir string) error
- func (self *TemplateMgr) CacheDelete(tmpl string)
- func (self *TemplateMgr) CacheTemplate(tmpl string, content []byte)
- func (self *TemplateMgr) GetTemplate(tmpl string) ([]byte, error)
- func (self *TemplateMgr) Init(app *App, rootDir string, reload bool) error
- func (self *TemplateMgr) Moniter(rootDir string) error
- type ToConversion
- type XMLResponse
Constants ¶
const ( Debug = iota + 1 Product )
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 白色 )
const ( LevelTrace = iota + 1 LevelDebug LevelInfo LevelWarn LevelError LevelCritical )
const (
Version = "0.2"
)
const (
XSRF_TAG string = "_xsrf"
)
Variables ¶
var ServerNumber uint = 0
Functions ¶
func AddTmplVar ¶
func AddTmplVar(name string, varOrFun interface{})
func AddTmplVars ¶
func AddTmplVars(t *T)
func AutoAction ¶
func AutoAction(c ...interface{})
func CloseZWriter ¶
CloseZWriter closes the io.Writer after compressing static file.
func GetAcceptEncodingZip ¶
GetAcceptEncodingZip returns accept encoding format in http header. zip is first, then deflate if both accepted. If no accepted, return empty string.
func InternalServerError ¶
func NewCookie ¶
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 NotSupported ¶
func Process ¶
func Process(c 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 SetStaticDir ¶
func SetStaticDir(dir string)
func SetTemplateDir ¶
func SetTemplateDir(dir string)
func SimpleParse ¶
func Slug ¶
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 Ternary ¶
func Ternary(express bool, trueVal interface{}, falseVal interface{}) interface{}
the func is the same as condition ? true : false
func Unauthorized ¶
func UrlFor ¶
Usage:UrlFor("main:root:/user/login") or UrlFor("root:/user/login") or UrlFor("/user/login") or UrlFor()
Types ¶
type AbortError ¶
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 RootTemplate *template.Template RequestBody []byte StatusCode int // 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 ¶
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) AddTmplVar ¶
add a name value for template
func (*Action) Cookie ¶
Cookie returns request cookie item string by a given key. if non-existed, return empty string.
func (*Action) DelSession ¶
func (*Action) DisableHttpCache ¶
func (c *Action) DisableHttpCache()
func (*Action) GetSession ¶
func (*Action) IP ¶
IP returns request client ip. if in proxy, return first proxy id. if error, return 127.0.0.1.
func (*Action) IsWebsocket ¶
IsSecure returns boolean of this request is in webSocket.
func (*Action) MapForm ¶
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) NamedRender ¶
render the template with vars map, you can have zero or one map
func (*Action) SaveToFile ¶
func (*Action) Session ¶
func (c *Action) Session() *httpsession.Session
func (*Action) SetBody ¶
Body sets response body content. if EnableGzip, compress content string. it sends out response body directly.
func (*Action) SetContentType ¶
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) SetHeader ¶
SetHeader sets a response header. the current value of that header will be overwritten .
func (*Action) SetSecureCookie ¶
func (*Action) SetSession ¶
func (*Action) SubDomains ¶
SubDomains returns sub domain string. if aa.bb.domain.com, returns aa.bb .
func (*Action) WriteBytes ¶
WriteString writes string data into the response object.
func (*Action) XsrfFormHtml ¶
type ActionOption ¶
type App ¶
type App struct { BasePath string Name string //[SWH|+] Routes []Route Server *Server AppConfig *AppConfig Config map[string]interface{} Actions map[reflect.Type]string FuncMaps template.FuncMap Logger *log.Logger VarMaps T SessionManager *httpsession.Manager //Session manager RootTemplate *template.Template ErrorTemplate *template.Template StaticVerMgr *StaticVerMgr TemplateMgr *TemplateMgr ContentEncoding string // contains filtered or unexported fields }
func (*App) AddTmplVar ¶
func (*App) AddTmplVars ¶
func (*App) AutoAction ¶
func (app *App) AutoAction(cs ...interface{})
func (*App) InitHeadContent ¶
func (a *App) InitHeadContent(w http.ResponseWriter, contentLength int64)
Init content-length header.
func (*App) SafelyCall ¶
func (a *App) SafelyCall(vc reflect.Value, method string, args []reflect.Value) (resp []reflect.Value, err error)
safelyCall invokes `function` in recover block
func (*App) SetStaticDir ¶
func (*App) SetTemplateDir ¶
func (*App) TryServingFile ¶
tryServingFile attempts to serve a static file, and returns whether or not the operation is successful.
type AppConfig ¶
type AppConfig struct { Mode int StaticDir string TemplateDir string SessionOn bool MaxUploadSize int64 CookieSecret string StaticFileVersion bool CacheTemplates bool ReloadTemplates bool CheckXrsf bool SessionTimeout int64 FormMapToStruct bool //[SWH|+] EnableHttpCache bool //[SWH|+] //[SWH|+] On/Off Log EnableTraceLog bool EnableDebugLog bool EnableInfoLog bool EnableWarnLog bool EnableErrorLog bool EnableCriticalLog bool }
type AutoResponse ¶
type AutoResponse struct { }
type FromConversion ¶
a struct implements this interface can be convert from request param to a struct
type HookEngine ¶
var ( ErrParamsNotAdapted = errors.New("The number of params is not adapted.") XHook *HookEngine = NewHookEngine(10) )
func NewHookEngine ¶
func NewHookEngine(size int) *HookEngine
func (*HookEngine) Bind ¶
func (f *HookEngine) Bind(name string, fns ...interface{}) (err error)
type JSONResponse ¶
type JSONResponse struct { }
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 ¶
func (s *LoginFilter) Do(w http.ResponseWriter, req *http.Request) bool
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 ¶
OpenMemZipFile returns MemFile object with a compressed static file. it's used for serve static file if gzip enable.
func (*MemFile) Readdir ¶
read os.FileInfo of files in directory of memfile. it returns empty slice.
type MemFileInfo ¶
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) 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 Server ¶
type Server struct { Config *ServerConfig Apps map[string]*App AppName map[string]string //[SWH|+] Name string //[SWH|+] RootApp *App Logger *log.Logger Env map[string]interface{} // contains filtered or unexported fields }
Server represents a xweb server.
func MainServer ¶
func MainServer() *Server
func (*Server) AddTmplVar ¶
func (*Server) AddTmplVars ¶
func (*Server) AutoAction ¶
func (s *Server) AutoAction(c ...interface{})
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) ServeHTTP ¶
func (s *Server) ServeHTTP(c http.ResponseWriter, req *http.Request)
ServeHTTP is the interface method for Go's http server package
func (*Server) SetStaticDir ¶
func (*Server) SetTemplateDir ¶
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 }
ServerConfig is configuration for server objects.
var ( Config *ServerConfig = &ServerConfig{ RecoverPanic: true, EnableGzip: true, StaticExtensionsToGzip: []string{".css", ".js"}, } Servers map[string]*Server = make(map[string]*Server) //[SWH|+] )
Config is the configuration of the main server.
type StaticVerMgr ¶
type StaticVerMgr struct { Caches map[string]string Path string Ignores map[string]bool // contains filtered or unexported fields }
func (*StaticVerMgr) CacheAll ¶
func (self *StaticVerMgr) CacheAll(staticPath string) error
func (*StaticVerMgr) GetVersion ¶
func (self *StaticVerMgr) GetVersion(url string) string
func (*StaticVerMgr) Moniter ¶
func (self *StaticVerMgr) Moniter(staticPath string) error
type TemplateMgr ¶
type TemplateMgr struct { Caches map[string][]byte RootDir string Ignores map[string]bool IsReload bool // contains filtered or unexported fields }
func (*TemplateMgr) CacheAll ¶
func (self *TemplateMgr) CacheAll(rootDir string) error
func (*TemplateMgr) CacheDelete ¶
func (self *TemplateMgr) CacheDelete(tmpl string)
func (*TemplateMgr) CacheTemplate ¶
func (self *TemplateMgr) CacheTemplate(tmpl string, content []byte)
func (*TemplateMgr) GetTemplate ¶
func (self *TemplateMgr) GetTemplate(tmpl string) ([]byte, error)
func (*TemplateMgr) Init ¶
func (self *TemplateMgr) Init(app *App, rootDir string, reload bool) error
func (*TemplateMgr) Moniter ¶
func (self *TemplateMgr) Moniter(rootDir string) error
type ToConversion ¶
type ToConversion interface {
ToString() string
}
a struct implements this interface can be convert from struct to template variable Not Implemented
type XMLResponse ¶
type XMLResponse struct { }