-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
99 lines (80 loc) · 1.78 KB
/
main.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
package main
import (
"log"
"net/http"
"reflect"
"strings"
)
func Redirect(path string, w http.ResponseWriter, req *http.Request) {
inter := router.GetPage(path)
if inter == nil {
log.Panicln("can't find the page interface")
}
http.Redirect(w, req, inter.GetPath(), http.StatusFound)
}
func RouterHandler(w http.ResponseWriter, req *http.Request) {
url := req.URL.Path
if url == "/" {
// if the url is root, redirect to the index page
Redirect("welcome", w, req)
return
}
s := strings.Split(url, "/")
// get the page interface
inter := router.GetPage(s[1])
if inter != nil {
l := len(s)
// Render page pattern
if l == 2 {
inter.Render(w, req)
return
}
// method function pattern
if l == 3 {
methodName := s[2]
method := reflect.ValueOf(inter).MethodByName(methodName)
in := make([]reflect.Value, 2)
in[0] = reflect.ValueOf(w)
in[1] = reflect.ValueOf(req)
method.Call(in)
return
}
}
// something wrong
Redirect("error", w, req)
}
func InitSetting() {
setting = Setting{
Host: "",
Port: "6767",
DBHost: "",
DBName: "bean_test",
DBUser: "root",
DBPwd: "tlj789520",
}
}
func InitRouter() {
router = Router{}
router.Init()
}
func InitStaticFileServer() {
http.Handle("/css/", http.FileServer(http.Dir(".")))
http.Handle("/img/", http.FileServer(http.Dir(".")))
http.Handle("/js/", http.FileServer(http.Dir(".")))
}
func InitRouterHandler() {
http.HandleFunc("/", RouterHandler)
}
func InitEnv() {
InitSetting()
InitStaticFileServer()
InitRouter()
InitRouterHandler()
}
func main() {
InitEnv()
err := http.ListenAndServe(setting.GetListenAndServe(), nil)
if err != nil {
log.Fatal("start server failed: ", err)
}
}