-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.go
100 lines (85 loc) · 2.28 KB
/
app.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
package mxgo
import (
"net/http"
"fmt"
"time"
"path"
"github.com/menghx/mxgo/config"
"github.com/menghx/mxgo/httplib"
)
const (
MxGoVersion = "0.0.1"
MxGoServerName = "MxGo"
MxGoImportPath = "github.com/menghx/mxgo"
)
type MxGoApp struct{
AppName string
AppHome string
addr string
port int
enableSSL bool
StaticUri string
Cfg *config.Config
Rm *RouterManager
Fm *FilterManager
cotter *Cotter
}
func NewMxGoApp() *MxGoApp {
mxGo := &MxGoApp{}
mxGo.cotter = NewCotter()
mxGo.AppHome = mxGo.cotter.appHome
mxGo.cotter.watchApp()
mxGo.Cfg = config.NewConfig(path.Join(mxGo.AppHome,"conf","app.conf"))
mxGo.AppName = mxGo.Cfg.String("name")
mxGo.StaticUri = mxGo.Cfg.String("static.uri")
mxGo.addr = mxGo.Cfg.String("addr")
mxGo.port = mxGo.Cfg.Int("port")
mxGo.Fm = NewFilterManager()
mxGo.Rm = NewRouterManager()
mxGo.initRouter()
return mxGo
}
func (mxGO *MxGoApp)initRouter(){
mxGO.Rm.Router("*:/error/*",&ErrorController{},"Handle")//erorr
mxGO.Rm.Router("*:"+mxGO.StaticUri,&StaticController{},"Handle")//erorr
mxGO.Rm.Router("GET:/favicon.ico",&StaticController{},"Handle")//static
}
func (mxGo *MxGoApp)EnableAdmin(enable bool){
if enable {
mxGo.Rm.Router("*:/admin/*",&AdminController{},"Handle")//erorr
}
}
func (mxGo *MxGoApp) Run() {
server := &http.Server{
Addr:fmt.Sprintf("%s:%d", mxGo.addr, mxGo.port),
Handler:mxGo,
}
var err error
go func() {
time.Sleep(100 * time.Millisecond)
mxLog.Info("Start server success listening ", server.Addr)
}()
if mxGo.enableSSL {
certFile := mxGo.Cfg.String("ssl.cert_file") //parser from config
keyFile := mxGo.Cfg.String("ssl.key_file") //parser from config
err = server.ListenAndServeTLS(certFile, keyFile)
}else {
err = server.ListenAndServe()
}
if err != nil {
mxLog.Error("start server failed ", server.Addr)
}
}
func (mxGo *MxGoApp) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
rw.Header().Add("Server", MxGoServerName)
var request = httplib.NewRequest(req)
var response = httplib.NewResponse(rw)
mxLog.Debug("ServeHTTP:",request.URL)
if SecurityVerify(request, response){
mxGo.execAction(request, response)
}
}
func (mxGo *MxGoApp) execAction(request *httplib.Request, response *httplib.Response) {
action := mxGo.Rm.FindAction(request,response)
action.Execute(mxGo)
}