-
Notifications
You must be signed in to change notification settings - Fork 51
/
Copy pathdockercopilot.go
176 lines (162 loc) · 4.62 KB
/
dockercopilot.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
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
package main
import (
"embed"
"flag"
"fmt"
loader "github.com/nathan-osman/pongo2-embed-loader"
"github.com/onlyLTY/dockerCopilot/internal/config"
"github.com/onlyLTY/dockerCopilot/internal/handler"
"github.com/onlyLTY/dockerCopilot/internal/svc"
"github.com/onlyLTY/dockerCopilot/internal/utiles"
"github.com/robfig/cron/v3"
"github.com/zeromicro/go-zero/core/conf"
"github.com/zeromicro/go-zero/core/logx"
"github.com/zeromicro/go-zero/rest"
"github.com/zeromicro/go-zero/rest/httpx"
"github.com/zeromicro/x/errors"
xhttp "github.com/zeromicro/x/http"
"go/types"
"net/http"
"os"
"strings"
)
var configFile = flag.String("f", "etc/dockerCopilot.yaml", "the config file")
type UnauthorizedResponse struct {
Code int `json:"code"`
Msg string `json:"msg"`
Data map[string]interface{} `json:"data"`
}
//go:embed templates/*
var content embed.FS
func main() {
logDir := "./logs"
ErrSetupLog := SetupLog(logDir)
if ErrSetupLog != nil {
logx.Errorf("failed to setup log: %v", ErrSetupLog)
os.Exit(1)
}
flag.Parse()
var c config.Config
err := conf.Load(*configFile, &c, conf.UseEnv())
if err != nil {
logx.Errorf("无法加载配置文件出错: %v", err)
logx.Errorf("请确认secretKey设置正确,要求非纯数字且大于八位")
os.Exit(1)
}
server := rest.MustNewServer(c.RestConf, rest.WithCors("*"), rest.WithUnauthorizedCallback(
func(w http.ResponseWriter, r *http.Request, err error) {
response := UnauthorizedResponse{
Code: http.StatusUnauthorized, // 401
Msg: "未授权",
Data: map[string]interface{}{},
}
httpx.WriteJson(w, http.StatusUnauthorized, response)
}))
defer server.Stop()
ctx := svc.NewServiceContext(c, &loader.Loader{Content: content})
list, err := utiles.GetImagesList(ctx)
if err != nil {
logx.Errorf("panic获取镜像列表出错: %v", err)
panic(err)
}
go ctx.HubImageInfo.CheckUpdate(list)
corndanmu := cron.New(cron.WithParser(cron.NewParser(
cron.Minute | cron.Hour | cron.Dom | cron.Month | cron.Dow,
)))
_, err = corndanmu.AddFunc("30 * * * *", func() {
list, err := utiles.GetImagesList(ctx)
if err != nil {
logx.Errorf("panic获取镜像列表出错: %v", err)
panic(err)
}
ctx.HubImageInfo.CheckUpdate(list)
})
if err != nil {
logx.Errorf("panic添加定时任务出错: %v", err)
panic(err)
}
corndanmu.Start()
defer corndanmu.Stop()
httpx.SetErrorHandler(func(err error) (int, any) {
switch e := err.(type) {
case *errors.CodeMsg:
return http.StatusOK, xhttp.BaseResponse[types.Nil]{
Code: e.Code,
Msg: e.Msg,
}
default:
return http.StatusOK, xhttp.BaseResponse[types.Nil]{
Code: 50000,
Msg: err.Error(),
}
}
})
handler.RegisterHandlers(server, ctx)
RegisterHandlers(server)
fmt.Printf("Starting server at %s:%d...\n", c.Host, c.Port)
logx.Info("程序版本" + config.Version)
server.Start()
}
func RegisterHandlers(engine *rest.Server) {
//这里注册
dirlevel := []string{":1", ":2", ":3", ":4", ":5", ":6", ":7", ":8"}
patern := "/static/"
dirpath := "./static/"
for i := 1; i < len(dirlevel); i++ {
path := patern + strings.Join(dirlevel[:i], "/")
//最后生成 /asset
engine.AddRoute(
rest.Route{
Method: http.MethodGet,
Path: path,
Handler: http.StripPrefix(patern, http.FileServer(http.Dir(dirpath))).ServeHTTP,
})
//logx.Infof("register dir %s %s", path, dirpath)
}
engine.AddRoute(
rest.Route{
Method: http.MethodGet,
Path: "/manager/",
Handler: func(w http.ResponseWriter, r *http.Request) {
http.ServeFile(w, r, "./templates/index.html")
},
},
)
managerPatern := "/manager/"
managerDirpath := "./templates/"
for i := 1; i < len(dirlevel); i++ {
path := managerPatern + strings.Join(dirlevel[:i], "/")
//最后生成 /asset
engine.AddRoute(
rest.Route{
Method: http.MethodGet,
Path: path,
Handler: http.StripPrefix(managerPatern, http.FileServer(http.Dir(managerDirpath))).ServeHTTP,
})
//logx.Infof("register dir %s %s", path, dirpath)
}
}
// 检查并创建日志目录
func ensureLogDirectory(logDir string) error {
if _, err := os.Stat(logDir); os.IsNotExist(err) {
return os.MkdirAll(logDir, 0755) // 创建目录并设置权限
}
return nil
}
// SetupLog 初始化日志设置
func SetupLog(logDir string) error {
// 检查日志目录是否存在
if err := ensureLogDirectory(logDir); err != nil {
return fmt.Errorf("failed to create log directory: %v", err)
}
logConf := logx.LogConf{
Path: logDir,
Level: "info",
KeepDays: 7,
Compress: true,
Mode: "file",
}
logx.MustSetup(logConf)
logx.AddWriter(logx.NewWriter(os.Stdout))
return nil
}