Repository navigation
Expand file tree
/
Copy pathmain.go
More file actions
100 lines (95 loc) · 2.29 KB
/
Copy pathmain.go
File metadata and controls
100 lines (95 loc) · 2.29 KB
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 main
import (
"context"
"embed"
"encoding/json"
"flag"
"fmt"
"io/fs"
"net/http"
"os"
"os/signal"
"path/filepath"
"syscall"
"time"
"zcode2api/internal/server"
"zcode2api/internal/server/update"
)
//go:embed src/web/*
var assets embed.FS
// version is set by release builds.
var version = "dev"
func dataDirectory(root string) string {
if data := os.Getenv("ZCODE2API_DATA_DIR"); data != "" {
return data
}
return filepath.Join(root, "data")
}
func main() {
root := flag.String("root", ".", "配置文件所在目录")
health := flag.String("healthcheck", "", "检查指定健康地址后退出")
showVersion := flag.Bool("version", false, "显示程序版本后退出")
applyUpdate := flag.String("apply-update", "", "应用已下载的网关更新")
dockerUpdater := flag.Bool("docker-updater", false, "在宿主机执行 WebUI 提交的 Compose 更新")
flag.Parse()
if *showVersion {
fmt.Println("zcode2api " + version)
return
}
if *applyUpdate != "" {
if err := update.Apply(*applyUpdate); err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
return
}
if *dockerUpdater {
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
defer stop()
if err := update.RunDockerUpdater(ctx, *root); err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
return
}
if *health != "" {
if *health == "auto" {
b, e := os.ReadFile(filepath.Join(dataDirectory(*root), "ports.json"))
var info struct {
Port int `json:"gateway_port"`
}
if e != nil || json.Unmarshal(b, &info) != nil || info.Port <= 0 {
os.Exit(1)
}
*health = fmt.Sprintf("http://127.0.0.1:%d/healthz", info.Port)
}
c := http.Client{Timeout: 4 * time.Second}
r, e := c.Get(*health)
if e != nil {
os.Exit(1)
}
r.Body.Close()
if r.StatusCode != 200 {
os.Exit(1)
}
return
}
abs, e := filepath.Abs(*root)
if e != nil {
fmt.Fprintln(os.Stderr, e)
os.Exit(1)
}
web, _ := fs.Sub(assets, "src/web")
app, e := server.New(abs, dataDirectory(abs), web, version)
if e != nil {
fmt.Fprintln(os.Stderr, "启动失败:", e)
os.Exit(1)
}
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
defer stop()
defer app.Close()
if e = app.Run(ctx); e != nil {
fmt.Fprintln(os.Stderr, e)
os.Exit(1)
}
}