forked from jackluo2012/datacenter
-
Notifications
You must be signed in to change notification settings - Fork 0
/
datacenter.go
67 lines (54 loc) · 1.57 KB
/
datacenter.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
package main
import (
"flag"
"fmt"
"net/http"
"strings"
"datacenter/internal/config"
"datacenter/internal/handler"
"datacenter/internal/middleware"
"datacenter/internal/svc"
"datacenter/shared"
"github.com/tal-tech/go-zero/core/conf"
"github.com/tal-tech/go-zero/rest"
"github.com/tal-tech/go-zero/rest/httpx"
)
var configFile = flag.String("f", "etc/datacenter-api.yaml", "the config file")
func dirhandler(patern, filedir string) http.HandlerFunc {
return func(w http.ResponseWriter, req *http.Request) {
handler := http.StripPrefix(patern, http.FileServer(http.Dir(filedir)))
handler.ServeHTTP(w, req)
}
}
func staticFileHandler(engine *rest.Server) {
//这里注册
dirlevel := []string{":1", ":2", ":3", ":4", ":5", ":6", ":7", ":8"}
patern := "/static/"
dirpath := "./assets/"
for i := 1; i < len(dirlevel); i++ {
path := "/" + strings.Join(dirlevel[:i], "/")
//最后生成 /asset
engine.AddRoute(
rest.Route{
Method: http.MethodGet,
Path: path,
Handler: dirhandler(patern, dirpath),
})
}
}
func main() {
flag.Parse()
var c config.Config
conf.MustLoad(*configFile, &c)
ctx := svc.NewServiceContext(c)
server := rest.MustNewServer(c.RestConf, rest.WithNotAllowedHandler(middleware.NewCorsMiddleware().Handler()))
defer server.Stop()
server.Use(middleware.NewCorsMiddleware().Handle)
//静太文件处理
staticFileHandler(server)
// 设置错误处理函数
httpx.SetErrorHandler(shared.ErrorHandler)
handler.RegisterHandlers(server, ctx)
fmt.Printf("Starting server xxx at %s:%d...\n", c.Host, c.Port)
server.Start()
}