embed
Package html files using comments like
//go:embed pages/dist/*
The packaged code is as follows
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()
}
When the browser requests the server page, it matches the file based on the URL.
io.fs.open(“/”)
Returns all files under the "/" path without recursive traversal. All c.FileFromFS("/", http.FS(fdist)) returns all files in the directory.
The js and css files in the code below are in separate directories and cannot be accessed using "/"
<!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>
Add static file server
e.StaticFS(“/js”, http.FS(fjs))
e.StaticFS(“/css”, http.FS(fcss))
Or modify the html relative path to ensure that the file can be searched in the "/" path or found in the static file server.