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

news/2024/7/7 20:09:00

前言

golang1.16出来以后,早就有打算把ckman项目的前端代码打包更换成embed。在此之前,使用的是pkger进行的打包。
但是今天打包时却报了个错:
在这里插入图片描述
而且通过各种手段尝试均无果之后,果断把决定立即将其更换为embed进行资源嵌入管理。
但是在折腾的时候,其实也是遇到了不少的坑,在这里总结一下。
关于embed,具体的功能这里就不多做介绍了,网上有一堆资料,但是这些资料并不能解决我的问题,我翻阅了无数的网页,也没有找到一个能确切解决我的问题的方案。因此决定自己记录一下。

embed资源嵌入

ckman项目的后端框架是gin,前端代码是vue,我们可以从这里下载到其前端代码的静态资源。目录大概长这个样子:
在这里插入图片描述

第一版代码(完全不能用)

第一版代码如下:

package main

import (
	"embed"
	"fmt"
	"net/http"

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

//go:embed static/dist
var f embed.FS

func main() {
	r := gin.Default()
	r.NoRoute(func(c *gin.Context) {
		data, err := f.ReadFile("static/dist/index.html")
		if err != nil {
			c.AbortWithError(http.StatusInternalServerError, err)
			return
		}
		c.Data(http.StatusOK, "text/html; charset=utf-8", data)
	})

	err := r.Run("0.0.0.0:5999")
	if err != nil {
		fmt.Println(err)
	}
}

通过后台日志,可以看到资源是可以加载出来的:
在这里插入图片描述
但是前端完全没有任何显示:
在这里插入图片描述
因此,这一版代码是完全不能工作的。

第二版代码(静态资源可以加载)

上一版代码不能工作,肯定是资源加载不全导致的,因此,在第二版代码里,我做了下改动:

package main

import (
	"embed"
	"fmt"
	"net/http"

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

//go:embed static/dist
var f embed.FS

func main() {
	r := gin.Default()
	st, _ := fs.Sub(f, "static/dist")
	r.StaticFS("/", http.FS(st))
	r.NoRoute(func(c *gin.Context) {
		data, err := f.ReadFile("static/dist/index.html")
		if err != nil {
			c.AbortWithError(http.StatusInternalServerError, err)
			return
		}
		c.Data(http.StatusOK, "text/html; charset=utf-8", data)
	})
	
	err := r.Run("0.0.0.0:5999")
	if err != nil {
		fmt.Println(err)
	}
}

与上一版代码相比,只增加了两行内容:

st, _ := fs.Sub(f, "static/dist")
r.StaticFS("/", http.FS(st))

此时首页正常加载出来了。
在这里插入图片描述

但是,当我讲这段代码放到项目里使用时,却根本无法工作!
原因就是路由冲突了。
因为gin框架采用了wildchard的方式对路由进行处理,我们在上面的代码中:

r.StaticFS("/", http.FS(st))

其实在gin处理时,已经匹配了/*filepath,因此,当我们还有其他路由需要处理时,就无法工作了,也就出现了路由冲突。
我们将上面代码改一下,模拟路由冲突的场景:

package main

import (
	"embed"
	"fmt"
	"net/http"

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

//go:embed static/dist
var f embed.FS

func main() {
	r := gin.Default()
	st, _ := fs.Sub(f, "static/dist")
	r.StaticFS("/", http.FS(st))
	r.NoRoute(func(c *gin.Context) {
		data, err := f.ReadFile("static/dist/index.html")
		if err != nil {
			c.AbortWithError(http.StatusInternalServerError, err)
			return
		}
		c.Data(http.StatusOK, "text/html; charset=utf-8", data)
	})
    r.GET("/api/hello", func(c *gin.Context) {
		c.JSON(200, gin.H{
			"msg": "hello world",
		})
	})
	
	err := r.Run("0.0.0.0:5999")
	if err != nil {
		fmt.Println(err)
	}
}

我们在这里增加了一个/api/hello的路由,当访问这个路由时,返回{"msg":"hello world"}
当再次运行时,发现直接panic了:
在这里插入图片描述
报错内容为: conflicts with existing wildcard '/*filepath' in existing prefix '/*filepath'
接下来,我们就来解决这个问题。

第三版代码(解决路由冲突问题)

解决路由冲突的方法有很多,但目前为止,都没有一个比较优雅的解决方案。比如重定向,代价就是要修改前端代码,这么做会显得比较非主流,而且修改前端代码,对我挑战有点大,因此没有用这种方案。
第二种方案是使用中间件。但目前为止没有一款比较好的中间件可以完美支持embed的资源嵌入。因此需要自己实现。
实现代码如下:

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),
	}
}

这样我们在路由中加入该中间件:


func main() {
	r := gin.Default()
	r.Use(Serve("/", EmbedFolder(f, "static/dist")))
	r.NoRoute(func(c *gin.Context) {
		data, err := f.ReadFile("static/dist/index.html")
		if err != nil {
			c.AbortWithError(http.StatusInternalServerError, err)
			return
		}
		c.Data(http.StatusOK, "text/html; charset=utf-8", data)
	})
	r.GET("/api/hello", func(c *gin.Context) {
		c.JSON(200, gin.H{
			"msg": "hello world",
		})
	})

	err := r.Run("0.0.0.0:5999")
	if err != nil {
		fmt.Println(err)
	}
}

此时,既能访问静态资源:
在这里插入图片描述
也能访问其他的路由接口:
在这里插入图片描述

注意事项

我们在调试时需要注意每次运行记得清理浏览器缓存,否则有可能会影响到当前的运行结果。

参考文档

  • Golang通过Embed嵌入静态资源

推荐一个零声学院免费教程,个人觉得老师讲得不错,分享给大家:[Linux,Nginx,ZeroMQ,MySQL,Redis,
fastdfs,MongoDB,ZK,流媒体,CDN,P2P,K8S,Docker,
TCP/IP,协程,DPDK等技术内容,点击立即学习: C/C++Linux服务器开发/高级架构师


http://lihuaxi.xjx100.cn/news/1169453.html

相关文章

5种易实现的Linux和 Windows VPS速度提升方法

​  无论是Linux VPS还是Windows VPS&#xff0c;网站速度的提高都是非常重要的。它们在提高网站速度方面都有很多的优化方法。下面我们将介绍 5 种提高网站速度的方法。 1.通过缓存加速 缓存通常是用来加快商业网站加载时间的技术&#xff0c;因此它也可以用在 VPS 上。没有…

如何在华为OD机试中获得满分?Java实现【差值数组不同的字符串】一文详解!

✅创作者&#xff1a;陈书予 &#x1f389;个人主页&#xff1a;陈书予的个人主页 &#x1f341;陈书予的个人社区&#xff0c;欢迎你的加入: 陈书予的社区 &#x1f31f;专栏地址: Java华为OD机试真题&#xff08;2022&2023) 文章目录 1. 题目描述2. 输入描述3. 输出描述…

C++线程

多线程 常见函数 构造函数 函数对应作用thread() noexcept空线程&#xff0c;什么都不做&#xff0c;noexcept作用是标识该函数不会抛出任何异常(简化代码生成过程)template <class Fn, class… Args> explicit thread(Fn&& fn, Args&&… args)创建一…

VB一款实现图像浏览的ActiveX控件

利用GDI实现浏览图片的ActiveX控件&#xff0c;功能:支持读取PNG格式的图片&#xff0c;支持鼠标飞轮对图片进行缩放&#xff0c;镜像&#xff0c;移动等功能&#xff0c;其中用到了功能强大的GDI&#xff0c;GDI&#xff0c;对初及vb编程爱好者运用GDI-API有很大的研究价值&am…

Python实现温度植被干旱指数(TVDI)的计算

前言 温度植被干旱指数&#xff08;Temperature Vegetation Dryness Index&#xff0c;TVDI&#xff09;是一种基于光学与热红外遥感通道数据进行植被覆盖区域表层土壤水分反演的方法。作为同时与归一化植被指数(NDVI)和地表温度(LST)相关的温度植被干旱指数(TVDI)可用于干旱监…

【leetcode刷题】剑指offer基础版(完结)

leetcode刷题笔记—剑指offer 剑指 Offer 05. 替换空格 class Solution { public:string replaceSpace(string s) {int len s.size();string g;for(int i 0; i < len; i){if(s[i] ){g "%20";continue;}g s[i];}return g;} };剑指 Offer 58 - II. 左旋转字…

自动化测试框架类型,你知道几种?此处介绍5种比较常见的

每一个测试人员都应该了解每种框架的优缺点&#xff0c;以帮助你的团队更好地确定最适合的测试的框架&#xff0c;以达到事半功倍。 什么是测试自动化框架? 自动化测试框架就是用于测试自动化的框架。具体来说&#xff0c;它提供了自动化测试用例编写、自动化测试用例执行、自…

设计模式实战 - 工厂模式实现总览页面工作进展指标查询

设计模式实战 - 工厂模式实现总览页面工作进展指标查询 1. 请求入口 ProgressController PostMapping("/progress/indicators") ApiOperation(value "总览工作进展") PreAuthorize("hasAnyAuthority(superAdmin,overViewQuery,incidentQuery,alert…