前言
在本萌新一次编写 Gin + vue3 项目的过程中需要将 vue3 打包到应用程序里面,然后就在找解决方案
尝试解决
问了 GPT 说需要定义静态路由,一写上去一个 panic 甩我脸上,来都来不及躲
然后又 Google 了一顿发现很多解决方案是将静态资源不放在 / 下,显得十分非主流
所以就在一直改和一直 Google 和 GPT
直到看到了这篇文章,尝试了一下终于成功了呜呜!
解决方案
解决方案就是使用中间件进行过滤
所以下面贴出代码来记录一下是怎么解决的
package middleware
import (
"embed"
"io/fs"
"net/http"
"os"
"path"
"strings"
"github.com/gin-gonic/gin"
)
const INDEX = "index.html"
type ServeFileSystem interface {
http.FileSystem
Exists(prefix string, path string) bool
}
type localFileSystem struct {
http.FileSystem
root string
indexes bool
}
func LocalFile(root string, indexes bool) *localFileSystem {
return &localFileSystem{
FileSystem: gin.Dir(root, indexes),
root: root,
indexes: indexes,
}
}
func (l *localFileSystem) Exists(prefix string, filepath string) bool {
if p := strings.TrimPrefix(filepath, prefix); len(p) < len(filepath) {
name := path.Join(l.root, p)
stats, err := os.Stat(name)
if err != nil {
return false
}
if stats.IsDir() {
if !l.indexes {
index := path.Join(name, INDEX)
_, err := os.Stat(index)
if err != nil {
return false
}
}
}
return true
}
return false
}
func ServeRoot(urlPrefix, root string) gin.HandlerFunc {
return Serve(urlPrefix, LocalFile(root, false))
}
// Static returns a middleware handler that serves static files in the given directory.
func Serve(urlPrefix string, fs ServeFileSystem) gin.HandlerFunc {
fileserver := http.FileServer(fs)
if urlPrefix != "" {
fileserver = http.StripPrefix(urlPrefix, fileserver)
}
return func(c *gin.Context) {
if fs.Exists(urlPrefix, c.Request.URL.Path) {
fileserver.ServeHTTP(c.Writer, c.Request)
c.Abort()
}
}
}
type embedFileSystem struct {
http.FileSystem
}
func (e embedFileSystem) Exists(prefix string, path string) bool {
_, err := e.Open(path)
if err != nil {
return false
}
return true
}
func EmbedFolder(fsEmbed embed.FS, targetPath string) ServeFileSystem {
fsys, err := fs.Sub(fsEmbed, targetPath)
if err != nil {
panic(err)
}
return embedFileSystem{
FileSystem: http.FS(fsys),
}
}
Go使用例
r.Use(middleware.Serve("/", middleware.EmbedFolder(content, "public/dist")))
r.NoRoute(func(c *gin.Context) {
data, err := content.ReadFile("public/dist/index.html")
if err != nil {
c.AbortWithError(http.StatusInternalServerError, err)
return
}
c.Data(http.StatusOK, "text/html; charset=utf-8", data)
})
Go以上是借鉴完全抄袭这篇文章的代码的,希望大家可以去原帖支持一下
发表回复