gin使用embed打包html

2023-07-10 16:26:55 浏览数 (1)

embed

使用类似的注释打包html文件

//go:embed pages/dist/*

打包的代码如下

代码语言:javascript复制
package main

import (
	"embed"
	"io/fs"
	"net/http"

	"github.com/gin-gonic/gin"
)

//go:embed pages/dist/*
var embedFs embed.FS

func main() {
	e := gin.Default()
	fpages, _ := fs.Sub(embedFs, "pages")
	fdist, _ := fs.Sub(fpages, "dist")
	fjs, _ := fs.Sub(fdist, "js")
	fcss, _ := fs.Sub(fdist, "css")
	e.StaticFS("/js", http.FS(fjs))
	e.StaticFS("/css", http.FS(fcss))
	e.GET("/", func(c *gin.Context) {
		c.FileFromFS("/", http.FS(fdist))
	})
	e.Run()
}

浏览器在请求服务端页面时,根据url匹配文件

io.fs.open(“/”)

返回"/“路径下所有的文件,不会递归遍历,所有c.FileFromFS(”/", http.FS(fdist))返回更目录中的所有文件


下面代码中的js和css文件在单独的目录里面,使用"/"无法访问

代码语言:javascript复制
<!doctype html>
<html lang="">

<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width,initial-scale=1">
    <link rel="icon" href="/favicon.ico">
    <title>pages</title>
    <script defer="defer" src="/js/chunk-vendors.87e17c26.js"></script>
    <script defer="defer" src="/js/app.cf230781.js"></script>
    <link href="/css/app.2cf79ad6.css" rel="stylesheet">
</head>

<body><noscript><strong>We're sorry but pages doesn't work properly without JavaScript enabled. Please enable it to
            continue.</strong></noscript>
    <div id="app"></div>
</body>

</html>

添加静态文件服务器

e.StaticFS(“/js”, http.FS(fjs)) e.StaticFS(“/css”, http.FS(fcss))

或者修改html相对路径,保证文件能在"/"路径中所有搜索到或者在静态文件服务器中找到。

0 人点赞