FrontendFileHandler 前端静态文件处理
(dep dependency.Dep)
| 11 | |
| 12 | // FrontendFileHandler 前端静态文件处理 |
| 13 | func FrontendFileHandler(dep dependency.Dep) gin.HandlerFunc { |
| 14 | fs := dep.ServerStaticFS() |
| 15 | l := dep.Logger() |
| 16 | |
| 17 | ignoreFunc := func(c *gin.Context) { |
| 18 | c.Next() |
| 19 | } |
| 20 | |
| 21 | if fs == nil { |
| 22 | return ignoreFunc |
| 23 | } |
| 24 | |
| 25 | // 读取index.html |
| 26 | file, err := fs.Open("/index.html") |
| 27 | if err != nil { |
| 28 | l.Warning("Static file \"index.html\" does not exist, it might affect the display of the homepage.") |
| 29 | return ignoreFunc |
| 30 | } |
| 31 | |
| 32 | fileContentBytes, err := io.ReadAll(file) |
| 33 | if err != nil { |
| 34 | l.Warning("Cannot read static file \"index.html\", it might affect the display of the homepage.") |
| 35 | return ignoreFunc |
| 36 | } |
| 37 | fileContent := string(fileContentBytes) |
| 38 | |
| 39 | fileServer := http.FileServer(fs) |
| 40 | return func(c *gin.Context) { |
| 41 | path := c.Request.URL.Path |
| 42 | |
| 43 | // Skipping routers handled by backend |
| 44 | if strings.HasPrefix(path, "/api") || |
| 45 | strings.HasPrefix(path, "/dav") || |
| 46 | strings.HasPrefix(path, "/f/") || |
| 47 | strings.HasPrefix(path, "/s/") || |
| 48 | path == "/manifest.json" { |
| 49 | c.Next() |
| 50 | return |
| 51 | } |
| 52 | |
| 53 | // 不存在的路径和index.html均返回index.html |
| 54 | if (path == "/index.html") || (path == "/") || !fs.Exists("/", path) { |
| 55 | // 读取、替换站点设置 |
| 56 | settingClient := dep.SettingProvider() |
| 57 | siteBasic := settingClient.SiteBasic(c) |
| 58 | pwaOpts := settingClient.PWA(c) |
| 59 | theme := settingClient.Theme(c) |
| 60 | finalHTML := util.Replace(map[string]string{ |
| 61 | "{siteName}": siteBasic.Name, |
| 62 | "{siteDes}": siteBasic.Description, |
| 63 | "{siteScript}": siteBasic.Script, |
| 64 | "{pwa_small_icon}": pwaOpts.SmallIcon, |
| 65 | "{pwa_medium_icon}": pwaOpts.MediumIcon, |
| 66 | "var(--defaultThemeColor)": theme.DefaultTheme, |
| 67 | }, fileContent) |
| 68 | |
| 69 | c.Header("Content-Type", "text/html") |
| 70 | c.Header("Cache-Control", "public, no-cache") |
no test coverage detected