1
0
mirror of https://github.com/astaxie/beego.git synced 2024-11-05 05:30:54 +00:00
Beego/app.go

124 lines
2.6 KiB
Go
Raw Normal View History

2013-09-09 16:00:11 +00:00
package beego
import (
"fmt"
"net"
"net/http"
"net/http/fcgi"
"time"
2013-12-03 13:37:39 +00:00
"github.com/astaxie/beego/context"
2013-09-09 16:00:11 +00:00
)
type FilterFunc func(*context.Context)
type App struct {
Handlers *ControllerRegistor
}
// New returns a new PatternServeMux.
func NewApp() *App {
cr := NewControllerRegistor()
app := &App{Handlers: cr}
return app
}
func (app *App) Run() {
addr := HttpAddr
if HttpPort != 0 {
addr = fmt.Sprintf("%s:%d", HttpAddr, HttpPort)
}
2013-12-05 03:27:29 +00:00
BeeLogger.Info("Running on %s", addr)
2013-09-09 16:00:11 +00:00
var (
err error
l net.Listener
)
2013-09-09 16:00:11 +00:00
if UseFcgi {
if HttpPort == 0 {
l, err = net.Listen("unix", addr)
} else {
l, err = net.Listen("tcp", addr)
}
if err != nil {
2013-09-09 16:17:49 +00:00
BeeLogger.Critical("Listen: ", err)
2013-09-09 16:00:11 +00:00
}
err = fcgi.Serve(l, app.Handlers)
} else {
if EnableHotUpdate {
server := &http.Server{
Handler: app.Handlers,
ReadTimeout: time.Duration(HttpServerTimeOut) * time.Second,
WriteTimeout: time.Duration(HttpServerTimeOut) * time.Second,
}
laddr, err := net.ResolveTCPAddr("tcp", addr)
if nil != err {
2013-09-09 16:17:49 +00:00
BeeLogger.Critical("ResolveTCPAddr:", err)
2013-09-09 16:00:11 +00:00
}
l, err = GetInitListner(laddr)
theStoppable = newStoppable(l)
err = server.Serve(theStoppable)
theStoppable.wg.Wait()
CloseSelf()
} else {
s := &http.Server{
Addr: addr,
Handler: app.Handlers,
ReadTimeout: time.Duration(HttpServerTimeOut) * time.Second,
WriteTimeout: time.Duration(HttpServerTimeOut) * time.Second,
}
if HttpTLS {
err = s.ListenAndServeTLS(HttpCertFile, HttpKeyFile)
} else {
err = s.ListenAndServe()
}
}
}
2013-09-09 16:00:11 +00:00
if err != nil {
2013-09-09 16:17:49 +00:00
BeeLogger.Critical("ListenAndServe: ", err)
time.Sleep(100 * time.Microsecond)
2013-09-09 16:00:11 +00:00
}
}
func (app *App) Router(path string, c ControllerInterface, mappingMethods ...string) *App {
app.Handlers.Add(path, c, mappingMethods...)
return app
}
func (app *App) AutoRouter(c ControllerInterface) *App {
app.Handlers.AddAuto(c)
return app
}
func (app *App) UrlFor(endpoint string, values ...string) string {
return app.Handlers.UrlFor(endpoint, values...)
}
2013-09-09 16:00:11 +00:00
func (app *App) Filter(pattern, action string, filter FilterFunc) *App {
app.Handlers.AddFilter(pattern, action, filter)
return app
}
func (app *App) InsertFilter(pattern string, pos int, filter FilterFunc) *App {
app.Handlers.InsertFilter(pattern, pos, filter)
return app
}
2013-09-09 16:00:11 +00:00
func (app *App) SetViewsPath(path string) *App {
ViewsPath = path
return app
}
func (app *App) SetStaticPath(url string, path string) *App {
StaticDir[url] = path
return app
}
func (app *App) DelStaticPath(url string) *App {
delete(StaticDir, url)
return app
}