米露小窝
放弃个性,就和死了没什么区别
米露小窝

Golang 使用 Gin + embed + vue3 打包项目

前言

在本萌新一次编写 Gin + vue3 项目的过程中需要将 vue3 打包到应用程序里面,然后就在找解决方案

尝试解决

问了 GPT 说需要定义静态路由,一写上去一个 panic 甩我脸上,来都来不及躲

https://upy.milu.ink/2025/01/20250117141501949-1024x148.png!/format/webp/lossless/true

然后又 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

以上是借鉴完全抄袭这篇文章的代码的,希望大家可以去原帖支持一下

参考文章

go embed 实现gin + vue静态资源嵌入

赞赏
Golang 使用 Gin + embed + vue3 打包项目》依据“CC BY-NC-SA 4.0”许可证进行授权。转载的时候请附上米露的链接,最好请勿用于商业目的 qaq
没有标签
首页      生活      Golang 使用 Gin + embed + vue3 打包项目

MxmiluBOB

文章作者

发表回复

textsms
account_circle
email

  • Someone

    好欸,是大佬,我们有救了

    3 周前 回复
  • Caius

    不愧是大佬

    3 周前 回复
  • liuzhen932

    Golang 下还有一些其他不错的嵌入包,比如 rakyll/statik(evmos 等在用)

    3 周前 回复

米露小窝

Golang 使用 Gin + embed + vue3 打包项目
前言 在本萌新一次编写 Gin + vue3 项目的过程中需要将 vue3 打包到应用程序里面,然后就在找解决方案 尝试解决 问了 GPT 说需要定义静态路由,一写上去一个 panic 甩我脸上,来…
扫描二维码继续阅读
2025-01-17