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/go-xweb/xweb
More usage, please visit https://github.com/go-xweb/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 Js(raw string) template.JS
- 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 SplitJson(s string) ([]string, error)
- 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) Debug(params ...interface{})
- func (c *Action) Debugf(format string, params ...interface{})
- func (c *Action) DelSession(key string)
- func (c *Action) DisableHttpCache()
- func (c *Action) Domain() string
- func (c *Action) Error(params ...interface{})
- func (c *Action) Errorf(format string, params ...interface{})
- func (c *Action) Fatal(params ...interface{})
- func (c *Action) Fatalf(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(params ...interface{})
- func (c *Action) Infof(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) Panic(params ...interface{})
- func (c *Action) Panicf(format string, params ...interface{})
- 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) ServeFile(fpath 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) SetConfig(name string, value interface{})
- 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) Uri() string
- func (c *Action) Url() string
- func (c *Action) UserAgent() string
- func (c *Action) Warn(params ...interface{})
- func (c *Action) Warnf(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) Action(name string) interface{}
- 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) Debug(params ...interface{})
- func (app *App) Debugf(format string, params ...interface{})
- func (app *App) Error(params ...interface{})
- func (app *App) Errorf(format string, params ...interface{})
- func (app *App) Fatal(params ...interface{})
- func (app *App) Fatalf(format string, params ...interface{})
- func (app *App) GetConfig(name string) interface{}
- func (app *App) Info(params ...interface{})
- func (app *App) Infof(format string, params ...interface{})
- func (a *App) InitHeadContent(w http.ResponseWriter, contentLength int64)
- func (app *App) Nodes() (r map[string]map[string][]string)
- func (app *App) Panic(params ...interface{})
- func (app *App) Panicf(format string, params ...interface{})
- 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 (a *App) TryServingFile(name string, req *http.Request, w http.ResponseWriter) bool
- func (app *App) Warn(params ...interface{})
- func (app *App) Warnf(format string, params ...interface{})
- type AppConfig
- type Filter
- type FromConversion
- type Hook
- type HookEngine
- type LoginFilter
- type Mapper
- type MemFile
- type MemFileInfo
- 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) GetConfig(name string) interface{}
- func (s *Server) InitSession()
- 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) SetConfig(name string, value interface{})
- func (s *Server) SetLogger(logger *log.Logger)
- func (s *Server) SetStaticDir(path string)
- func (s *Server) SetTemplateDir(path string)
- type ServerConfig
- type StaticVerMgr
- func (self *StaticVerMgr) CacheAll(staticPath string) error
- func (self *StaticVerMgr) CacheDelete(url string)
- func (self *StaticVerMgr) CacheItem(url string)
- func (self *StaticVerMgr) GetVersion(url string) string
- func (self *StaticVerMgr) Init(app *App, staticPath string) error
- func (self *StaticVerMgr) Moniter(staticPath string) error
- 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
Constants ¶
const ( Debug = iota + 1 Product )
const (
Version = "0.2.1"
)
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 RoutesEq map[string]map[string]Route Server *Server AppConfig *AppConfig Config map[string]interface{} Actions map[string]interface{} ActionsPath map[reflect.Type]string ActionsNamePath map[string]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) Nodes ¶
example:
{ "AdminAction":{ "Index":["GET","POST"], "Add": ["GET","POST"], "Edit": ["GET","POST"] } }
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 FromConversion ¶
a struct implements this interface can be convert from request param to a struct
type HookEngine ¶
type HookEngine struct { Hooks map[string]Hook Index map[string]uint // contains filtered or unexported fields }
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 LoginFilter ¶
type LoginFilter struct { App *App SessionName string AnonymousUrls []*regexp.Regexp AskLoginUrls []*regexp.Regexp Redirect string OriUrlName 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 AppsNamePath map[string]string Name string SessionManager *httpsession.Manager 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) InitSession ¶
func (s *Server) InitSession()
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 SessionTimeout time.Duration }
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) CacheDelete ¶
func (self *StaticVerMgr) CacheDelete(url string)
func (*StaticVerMgr) CacheItem ¶
func (self *StaticVerMgr) CacheItem(url string)
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 Preprocessor func([]byte) []byte // 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