Repository navigation
Expand file tree
/
Copy pathmain.go
More file actions
100 lines (91 loc) · 2.24 KB
/
Copy pathmain.go
File metadata and controls
100 lines (91 loc) · 2.24 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 (
"DomainManager/config"
"DomainManager/database"
"DomainManager/router"
"DomainManager/services"
"embed"
"io"
"io/fs"
"log"
"mime"
"net/http"
"path/filepath"
"strings"
"github.com/gin-gonic/gin"
)
//go:embed web/dist/*
var frontendFS embed.FS
func main() {
config.Load()
database.Init()
// Load runtime settings (WHOIS/ICP/OauthGo etc.) from the database; env only
// provides initial defaults on first startup.
database.LoadSettingsIntoConfig()
// Start the background job runner (定时推送系统信息等).
services.StartScheduler()
r := router.Setup()
sub, err := fs.Sub(frontendFS, "web/dist")
if err != nil {
log.Fatalf("failed to load embedded frontend: %v", err)
}
serveFile := func(c *gin.Context, name string) {
f, err := sub.Open(name)
if err != nil {
c.Status(http.StatusNotFound)
return
}
defer func(f fs.File) {
err := f.Close()
if err != nil {
log.Printf("failed to close file: %v", err)
}
}(f)
data, err := io.ReadAll(f)
if err != nil {
c.Status(http.StatusInternalServerError)
return
}
ext := filepath.Ext(name)
contentType := mime.TypeByExtension(ext)
if contentType == "" {
contentType = map[string]string{
".html": "text/html; charset=utf-8",
".js": "text/javascript; charset=utf-8",
".css": "text/css; charset=utf-8",
".svg": "image/svg+xml",
".json": "application/json",
".map": "application/json",
".png": "image/png",
".ico": "image/x-icon",
".woff": "font/woff",
".woff2": "font/woff2",
".ttf": "font/ttf",
}[ext]
}
if contentType == "" {
contentType = "application/octet-stream"
}
c.Data(http.StatusOK, contentType, data)
}
r.NoRoute(func(c *gin.Context) {
path := c.Request.URL.Path
if strings.HasPrefix(path, "/api") {
c.JSON(http.StatusNotFound, gin.H{"error": "not found"})
return
}
clean := strings.TrimPrefix(path, "/")
if clean == "" {
clean = "index.html"
}
if _, err := fs.Stat(sub, clean); err == nil {
serveFile(c, clean)
return
}
serveFile(c, "index.html")
})
log.Printf("Server starting on port %s", config.AppConfig.Port)
if err := r.Run(":" + config.AppConfig.Port); err != nil {
log.Fatalf("failed to start server: %v", err)
}
}