feat: assets程序内嵌全局资源访问

This commit is contained in:
TsMask
2023-10-26 20:23:46 +08:00
parent 2e160ef4d3
commit 1a35240d42
4 changed files with 35 additions and 12 deletions

View File

@@ -1,6 +1,7 @@
package src
import (
"embed"
"fmt"
"ems.agt/src/framework/config"
@@ -17,6 +18,9 @@ import (
"github.com/gin-gonic/gin"
)
//go:embed assets/*
var assetsDir embed.FS
// 路由函数句柄,交给由 http.ListenAndServe(addr, router)
func AppEngine() *gin.Engine {
app := initAppEngine()
@@ -27,12 +31,11 @@ func AppEngine() *gin.Engine {
// 初始模块路由
initModulesRoute(app)
// 设置程序内全局资源访问
config.SetAssetsDirFS(assetsDir)
// 读取服务配置
app.ForwardedByClientIP = config.Get("server.proxy").(bool)
addr := fmt.Sprintf(":%d", config.Get("server.port").(int))
// 启动服务
fmt.Printf("\nopen http://localhost%s \n\n", addr)
return app
}
@@ -45,13 +48,7 @@ func AppEngine() *gin.Engine {
// }
// }
func RunServer() error {
app := initAppEngine()
// 初始全局默认
initDefeat(app)
// 初始模块路由
initModulesRoute(app)
app := AppEngine()
// 读取服务配置
app.ForwardedByClientIP = config.Get("server.proxy").(bool)

Binary file not shown.

View File

@@ -147,6 +147,16 @@ func Get(key string) any {
return viper.Get(key)
}
// GetAssetsDirFS 访问程序内全局资源访问
func GetAssetsDirFS() embed.FS {
return viper.Get("AssetsDir").(embed.FS)
}
// SetAssetsDirFS 设置程序内全局资源访问
func SetAssetsDirFS(assetsDir embed.FS) {
viper.Set("AssetsDir", assetsDir)
}
// IsAdmin 用户是否为管理员
func IsAdmin(userID string) bool {
if userID == "" {

View File

@@ -455,7 +455,23 @@ func (s *SysUserController) Export(c *gin.Context) {
func (s *SysUserController) Template(c *gin.Context) {
fileName := fmt.Sprintf("user_import_template_%d.xlsx", time.Now().UnixMilli())
asserPath := "assets/template/excel/user_import_template.xlsx"
c.FileAttachment(asserPath, fileName)
// 从 embed.FS 中读取默认配置文件内容
assetsDir := config.GetAssetsDirFS()
// 读取内嵌文件
fileData, err := assetsDir.ReadFile(asserPath)
if err != nil {
c.String(500, "Failed to read file")
return
}
// 设置响应头
c.Header("Content-Disposition", fmt.Sprintf("attachment; filename=%s", fileName))
c.Header("Content-Type", "application/octet-stream")
// 返回响应体
c.Data(200, "application/octet-stream", fileData)
}
// 用户信息列表导入