1
0
mirror of https://github.com/astaxie/beego.git synced 2024-11-23 05:40:55 +00:00

Merge pull request #1478 from fuxiaohei/develop

clean compliated codes, refactor if sections in app.go
This commit is contained in:
astaxie 2015-12-17 14:44:14 +08:00
commit 46aa340b1d
2 changed files with 222 additions and 227 deletions

236
admin.go
View File

@ -81,91 +81,93 @@ func qpsIndex(rw http.ResponseWriter, r *http.Request) {
func listConf(rw http.ResponseWriter, r *http.Request) { func listConf(rw http.ResponseWriter, r *http.Request) {
r.ParseForm() r.ParseForm()
command := r.Form.Get("command") command := r.Form.Get("command")
if command != "" { if command == "" {
data := make(map[interface{}]interface{}) rw.Write([]byte("command not support"))
switch command { return
case "conf": }
tmpl := template.Must(template.New("dashboard").Parse(dashboardTpl))
tmpl = template.Must(tmpl.Parse(configTpl))
tmpl = template.Must(tmpl.Parse(defaultScriptsTpl))
data["Content"] = BConfig data := make(map[interface{}]interface{})
switch command {
case "conf":
tmpl := template.Must(template.New("dashboard").Parse(dashboardTpl))
tmpl = template.Must(tmpl.Parse(configTpl))
tmpl = template.Must(tmpl.Parse(defaultScriptsTpl))
tmpl.Execute(rw, data) data["Content"] = BConfig
case "router": tmpl.Execute(rw, data)
content := make(map[string]interface{})
var fields = []string{ case "router":
fmt.Sprintf("Router Pattern"), var (
fmt.Sprintf("Methods"), content = map[string]interface{}{
fmt.Sprintf("Controller"), "Fields": []string{
"Router Pattern",
"Methods",
"Controller",
},
} }
content["Fields"] = fields methods = []string{}
methodsData = make(map[string]interface{})
)
for method, t := range BeeApp.Handlers.routers {
methods := []string{} resultList := new([][]string)
methodsData := make(map[string]interface{})
for method, t := range BeeApp.Handlers.routers {
resultList := new([][]string) printTree(resultList, t)
printTree(resultList, t) methods = append(methods, method)
methodsData[method] = resultList
}
methods = append(methods, method) content["Data"] = methodsData
methodsData[method] = resultList content["Methods"] = methods
data["Content"] = content
data["Title"] = "Routers"
execTpl(rw, data, routerAndFilterTpl, defaultScriptsTpl)
case "filter":
var (
content = map[string]interface{}{
"Fields": []string{
"Router Pattern",
"Filter Function",
},
} }
filterTypes = []string{}
filterTypeData = make(map[string]interface{})
)
content["Data"] = methodsData if BeeApp.Handlers.enableFilter {
content["Methods"] = methods var filterType string
data["Content"] = content for k, fr := range map[int]string{
data["Title"] = "Routers" BeforeStatic: "Before Static",
execTpl(rw, data, routerAndFilterTpl, defaultScriptsTpl) BeforeRouter: "Before Router",
case "filter": BeforeExec: "Before Exec",
content := make(map[string]interface{}) AfterExec: "After Exec",
FinishRouter: "Finish Router"} {
var fields = []string{ if bf, ok := BeeApp.Handlers.filters[k]; ok {
fmt.Sprintf("Router Pattern"), filterType = fr
fmt.Sprintf("Filter Function"), filterTypes = append(filterTypes, filterType)
} resultList := new([][]string)
content["Fields"] = fields for _, f := range bf {
var result = []string{
filterTypes := []string{} fmt.Sprintf("%s", f.pattern),
filterTypeData := make(map[string]interface{}) fmt.Sprintf("%s", utils.GetFuncName(f.filterFunc)),
if BeeApp.Handlers.enableFilter {
var filterType string
for k, fr := range map[int]string{
BeforeStatic: "Before Static",
BeforeRouter: "Before Router",
BeforeExec: "Before Exec",
AfterExec: "After Exec",
FinishRouter: "Finish Router"} {
if bf, ok := BeeApp.Handlers.filters[k]; ok {
filterType = fr
filterTypes = append(filterTypes, filterType)
resultList := new([][]string)
for _, f := range bf {
var result = []string{
fmt.Sprintf("%s", f.pattern),
fmt.Sprintf("%s", utils.GetFuncName(f.filterFunc)),
}
*resultList = append(*resultList, result)
} }
filterTypeData[filterType] = resultList *resultList = append(*resultList, result)
} }
filterTypeData[filterType] = resultList
} }
} }
content["Data"] = filterTypeData
content["Methods"] = filterTypes
data["Content"] = content
data["Title"] = "Filters"
execTpl(rw, data, routerAndFilterTpl, defaultScriptsTpl)
default:
rw.Write([]byte("command not support"))
} }
} else {
content["Data"] = filterTypeData
content["Methods"] = filterTypes
data["Content"] = content
data["Title"] = "Filters"
execTpl(rw, data, routerAndFilterTpl, defaultScriptsTpl)
default:
rw.Write([]byte("command not support"))
} }
} }
@ -180,23 +182,23 @@ func printTree(resultList *[][]string, t *Tree) {
if v, ok := l.runObject.(*controllerInfo); ok { if v, ok := l.runObject.(*controllerInfo); ok {
if v.routerType == routerTypeBeego { if v.routerType == routerTypeBeego {
var result = []string{ var result = []string{
fmt.Sprintf("%s", v.pattern), v.pattern,
fmt.Sprintf("%s", v.methods), fmt.Sprintf("%s", v.methods),
fmt.Sprintf("%s", v.controllerType), fmt.Sprintf("%s", v.controllerType),
} }
*resultList = append(*resultList, result) *resultList = append(*resultList, result)
} else if v.routerType == routerTypeRESTFul { } else if v.routerType == routerTypeRESTFul {
var result = []string{ var result = []string{
fmt.Sprintf("%s", v.pattern), v.pattern,
fmt.Sprintf("%s", v.methods), fmt.Sprintf("%s", v.methods),
fmt.Sprintf(""), "",
} }
*resultList = append(*resultList, result) *resultList = append(*resultList, result)
} else if v.routerType == routerTypeHandler { } else if v.routerType == routerTypeHandler {
var result = []string{ var result = []string{
fmt.Sprintf("%s", v.pattern), v.pattern,
fmt.Sprintf(""), "",
fmt.Sprintf(""), "",
} }
*resultList = append(*resultList, result) *resultList = append(*resultList, result)
} }
@ -209,49 +211,49 @@ func printTree(resultList *[][]string, t *Tree) {
func profIndex(rw http.ResponseWriter, r *http.Request) { func profIndex(rw http.ResponseWriter, r *http.Request) {
r.ParseForm() r.ParseForm()
command := r.Form.Get("command") command := r.Form.Get("command")
format := r.Form.Get("format") if command == "" {
data := make(map[interface{}]interface{}) return
}
var result bytes.Buffer var (
if command != "" { format = r.Form.Get("format")
toolbox.ProcessInput(command, &result) data = make(map[interface{}]interface{})
data["Content"] = result.String() result bytes.Buffer
)
toolbox.ProcessInput(command, &result)
data["Content"] = result.String()
if format == "json" && command == "gc summary" { if format == "json" && command == "gc summary" {
dataJSON, err := json.Marshal(data) dataJSON, err := json.Marshal(data)
if err != nil { if err != nil {
http.Error(rw, err.Error(), http.StatusInternalServerError) http.Error(rw, err.Error(), http.StatusInternalServerError)
return
}
rw.Header().Set("Content-Type", "application/json")
rw.Write(dataJSON)
return return
} }
data["Title"] = command rw.Header().Set("Content-Type", "application/json")
defaultTpl := defaultScriptsTpl rw.Write(dataJSON)
if command == "gc summary" { return
defaultTpl = gcAjaxTpl
}
execTpl(rw, data, profillingTpl, defaultTpl)
} }
data["Title"] = command
defaultTpl := defaultScriptsTpl
if command == "gc summary" {
defaultTpl = gcAjaxTpl
}
execTpl(rw, data, profillingTpl, defaultTpl)
} }
// Healthcheck is a http.Handler calling health checking and showing the result. // Healthcheck is a http.Handler calling health checking and showing the result.
// it's in "/healthcheck" pattern in admin module. // it's in "/healthcheck" pattern in admin module.
func healthcheck(rw http.ResponseWriter, req *http.Request) { func healthcheck(rw http.ResponseWriter, req *http.Request) {
data := make(map[interface{}]interface{}) var (
data = make(map[interface{}]interface{})
var result = []string{} result = []string{}
fields := []string{ resultList = new([][]string)
fmt.Sprintf("Name"), content = map[string]interface{}{
fmt.Sprintf("Message"), "Fields": []string{"Name", "Message", "Status"},
fmt.Sprintf("Status"), }
} )
resultList := new([][]string)
content := make(map[string]interface{})
for name, h := range toolbox.AdminCheckList { for name, h := range toolbox.AdminCheckList {
if err := h.Check(); err != nil { if err := h.Check(); err != nil {
@ -271,8 +273,6 @@ func healthcheck(rw http.ResponseWriter, req *http.Request) {
} }
*resultList = append(*resultList, result) *resultList = append(*resultList, result)
} }
content["Fields"] = fields
content["Data"] = resultList content["Data"] = resultList
data["Content"] = content data["Content"] = content
data["Title"] = "Health Check" data["Title"] = "Health Check"
@ -288,10 +288,8 @@ func taskStatus(rw http.ResponseWriter, req *http.Request) {
req.ParseForm() req.ParseForm()
taskname := req.Form.Get("taskname") taskname := req.Form.Get("taskname")
if taskname != "" { if taskname != "" {
if t, ok := toolbox.AdminTaskList[taskname]; ok { if t, ok := toolbox.AdminTaskList[taskname]; ok {
err := t.Run() if err := t.Run(); err != nil {
if err != nil {
data["Message"] = []string{"error", fmt.Sprintf("%s", err)} data["Message"] = []string{"error", fmt.Sprintf("%s", err)}
} }
data["Message"] = []string{"success", fmt.Sprintf("%s run success,Now the Status is <br>%s", taskname, t.GetStatus())} data["Message"] = []string{"success", fmt.Sprintf("%s run success,Now the Status is <br>%s", taskname, t.GetStatus())}
@ -305,18 +303,18 @@ func taskStatus(rw http.ResponseWriter, req *http.Request) {
resultList := new([][]string) resultList := new([][]string)
var result = []string{} var result = []string{}
var fields = []string{ var fields = []string{
fmt.Sprintf("Task Name"), "Task Name",
fmt.Sprintf("Task Spec"), "Task Spec",
fmt.Sprintf("Task Status"), "Task Status",
fmt.Sprintf("Last Time"), "Last Time",
fmt.Sprintf(""), "",
} }
for tname, tk := range toolbox.AdminTaskList { for tname, tk := range toolbox.AdminTaskList {
result = []string{ result = []string{
fmt.Sprintf("%s", tname), tname,
fmt.Sprintf("%s", tk.GetSpec()), fmt.Sprintf("%s", tk.GetSpec()),
fmt.Sprintf("%s", tk.GetStatus()), fmt.Sprintf("%s", tk.GetStatus()),
fmt.Sprintf("%s", tk.GetPrev().String()), tk.GetPrev().String(),
} }
*resultList = append(*resultList, result) *resultList = append(*resultList, result)
} }

213
app.go
View File

@ -59,128 +59,125 @@ func (app *App) Run() {
} }
var ( var (
err error err error
l net.Listener l net.Listener
endRunning = make(chan bool, 1)
) )
endRunning := make(chan bool, 1)
// run cgi server
if BConfig.Listen.EnableFcgi { if BConfig.Listen.EnableFcgi {
if BConfig.Listen.EnableStdIo { if BConfig.Listen.EnableStdIo {
err = fcgi.Serve(nil, app.Handlers) // standard I/O if err = fcgi.Serve(nil, app.Handlers); err == nil { // standard I/O
if err == nil {
BeeLogger.Info("Use FCGI via standard I/O") BeeLogger.Info("Use FCGI via standard I/O")
} else { } else {
BeeLogger.Info("Cannot use FCGI via standard I/O", err) BeeLogger.Critical("Cannot use FCGI via standard I/O", err)
} }
return
}
if BConfig.Listen.HTTPPort == 0 {
// remove the Socket file before start
if utils.FileExists(addr) {
os.Remove(addr)
}
l, err = net.Listen("unix", addr)
} else { } else {
if BConfig.Listen.HTTPPort == 0 { l, err = net.Listen("tcp", addr)
// remove the Socket file before start }
if utils.FileExists(addr) { if err != nil {
os.Remove(addr) BeeLogger.Critical("Listen: ", err)
}
if err = fcgi.Serve(l, app.Handlers); err != nil {
BeeLogger.Critical("fcgi.Serve: ", err)
}
return
}
app.Server.Handler = app.Handlers
app.Server.ReadTimeout = time.Duration(BConfig.Listen.ServerTimeOut) * time.Second
app.Server.WriteTimeout = time.Duration(BConfig.Listen.ServerTimeOut) * time.Second
// run graceful mode
if BConfig.Listen.Graceful {
httpsAddr := BConfig.Listen.HTTPSAddr
app.Server.Addr = httpsAddr
if BConfig.Listen.HTTPSEnable {
go func() {
time.Sleep(20 * time.Microsecond)
if BConfig.Listen.HTTPSPort != 0 {
httpsAddr = fmt.Sprintf("%s:%d", BConfig.Listen.HTTPSAddr, BConfig.Listen.HTTPSPort)
app.Server.Addr = httpsAddr
} }
l, err = net.Listen("unix", addr) server := grace.NewServer(httpsAddr, app.Handlers)
} else { server.Server.ReadTimeout = app.Server.ReadTimeout
l, err = net.Listen("tcp", addr) server.Server.WriteTimeout = app.Server.WriteTimeout
} if err := server.ListenAndServeTLS(BConfig.Listen.HTTPSCertFile, BConfig.Listen.HTTPSKeyFile); err != nil {
if err != nil { BeeLogger.Critical("ListenAndServeTLS: ", err, fmt.Sprintf("%d", os.Getpid()))
BeeLogger.Critical("Listen: ", err) time.Sleep(100 * time.Microsecond)
} endRunning <- true
err = fcgi.Serve(l, app.Handlers) }
}()
} }
} else { if BConfig.Listen.HTTPEnable {
if BConfig.Listen.Graceful { go func() {
httpsAddr := BConfig.Listen.HTTPSAddr server := grace.NewServer(addr, app.Handlers)
app.Server.Addr = httpsAddr server.Server.ReadTimeout = app.Server.ReadTimeout
app.Server.Handler = app.Handlers server.Server.WriteTimeout = app.Server.WriteTimeout
app.Server.ReadTimeout = time.Duration(BConfig.Listen.ServerTimeOut) * time.Second if BConfig.Listen.ListenTCP4 {
app.Server.WriteTimeout = time.Duration(BConfig.Listen.ServerTimeOut) * time.Second server.Network = "tcp4"
if BConfig.Listen.HTTPSEnable { }
go func() { if err := server.ListenAndServe(); err != nil {
time.Sleep(20 * time.Microsecond) BeeLogger.Critical("ListenAndServe: ", err, fmt.Sprintf("%d", os.Getpid()))
if BConfig.Listen.HTTPSPort != 0 { time.Sleep(100 * time.Microsecond)
httpsAddr = fmt.Sprintf("%s:%d", BConfig.Listen.HTTPSAddr, BConfig.Listen.HTTPSPort) endRunning <- true
app.Server.Addr = httpsAddr }
} }()
server := grace.NewServer(httpsAddr, app.Handlers) }
server.Server.ReadTimeout = app.Server.ReadTimeout <-endRunning
server.Server.WriteTimeout = app.Server.WriteTimeout return
err := server.ListenAndServeTLS(BConfig.Listen.HTTPSCertFile, BConfig.Listen.HTTPSKeyFile) }
if err != nil {
BeeLogger.Critical("ListenAndServeTLS: ", err, fmt.Sprintf("%d", os.Getpid())) // run normal mode
time.Sleep(100 * time.Microsecond) app.Server.Addr = addr
endRunning <- true if BConfig.Listen.HTTPSEnable {
} go func() {
}() time.Sleep(20 * time.Microsecond)
if BConfig.Listen.HTTPSPort != 0 {
app.Server.Addr = fmt.Sprintf("%s:%d", BConfig.Listen.HTTPSAddr, BConfig.Listen.HTTPSPort)
} }
if BConfig.Listen.HTTPEnable { BeeLogger.Info("https server Running on %s", app.Server.Addr)
go func() { if err := app.Server.ListenAndServeTLS(BConfig.Listen.HTTPSCertFile, BConfig.Listen.HTTPSKeyFile); err != nil {
server := grace.NewServer(addr, app.Handlers) BeeLogger.Critical("ListenAndServeTLS: ", err)
server.Server.ReadTimeout = app.Server.ReadTimeout time.Sleep(100 * time.Microsecond)
server.Server.WriteTimeout = app.Server.WriteTimeout endRunning <- true
if BConfig.Listen.ListenTCP4 {
server.Network = "tcp4"
}
err := server.ListenAndServe()
if err != nil {
BeeLogger.Critical("ListenAndServe: ", err, fmt.Sprintf("%d", os.Getpid()))
time.Sleep(100 * time.Microsecond)
endRunning <- true
}
}()
} }
} else { }()
}
if BConfig.Listen.HTTPEnable {
go func() {
app.Server.Addr = addr app.Server.Addr = addr
app.Server.Handler = app.Handlers BeeLogger.Info("http server Running on %s", app.Server.Addr)
app.Server.ReadTimeout = time.Duration(BConfig.Listen.ServerTimeOut) * time.Second if BConfig.Listen.ListenTCP4 {
app.Server.WriteTimeout = time.Duration(BConfig.Listen.ServerTimeOut) * time.Second ln, err := net.Listen("tcp4", app.Server.Addr)
if err != nil {
if BConfig.Listen.HTTPSEnable { BeeLogger.Critical("ListenAndServe: ", err)
go func() { time.Sleep(100 * time.Microsecond)
time.Sleep(20 * time.Microsecond) endRunning <- true
if BConfig.Listen.HTTPSPort != 0 { return
app.Server.Addr = fmt.Sprintf("%s:%d", BConfig.Listen.HTTPSAddr, BConfig.Listen.HTTPSPort) }
} if err = app.Server.Serve(ln); err != nil {
BeeLogger.Info("https server Running on %s", app.Server.Addr) BeeLogger.Critical("ListenAndServe: ", err)
err := app.Server.ListenAndServeTLS(BConfig.Listen.HTTPSCertFile, BConfig.Listen.HTTPSKeyFile) time.Sleep(100 * time.Microsecond)
if err != nil { endRunning <- true
BeeLogger.Critical("ListenAndServeTLS: ", err) return
time.Sleep(100 * time.Microsecond) }
endRunning <- true } else {
} if err := app.Server.ListenAndServe(); err != nil {
}() BeeLogger.Critical("ListenAndServe: ", err)
time.Sleep(100 * time.Microsecond)
endRunning <- true
}
} }
}()
if BConfig.Listen.HTTPEnable {
go func() {
app.Server.Addr = addr
BeeLogger.Info("http server Running on %s", app.Server.Addr)
if BConfig.Listen.ListenTCP4 {
ln, err := net.Listen("tcp4", app.Server.Addr)
if err != nil {
BeeLogger.Critical("ListenAndServe: ", err)
time.Sleep(100 * time.Microsecond)
endRunning <- true
return
}
err = app.Server.Serve(ln)
if err != nil {
BeeLogger.Critical("ListenAndServe: ", err)
time.Sleep(100 * time.Microsecond)
endRunning <- true
return
}
} else {
err := app.Server.ListenAndServe()
if err != nil {
BeeLogger.Critical("ListenAndServe: ", err)
time.Sleep(100 * time.Microsecond)
endRunning <- true
}
}
}()
}
}
} }
<-endRunning <-endRunning
} }