2024年C C++最新go embed 实现gin + vue静态资源嵌入_gin embed vue,2024年最新阿里后台开发

img
img

网上学习资料一大堆,但如果学到的知识不成体系,遇到问题时只是浅尝辄止,不再深入研究,那么很难做到真正的技术提升。

需要这份系统化的资料的朋友,可以添加戳这里获取

一个人可以走的很快,但一群人才能走的更远!不论你是正从事IT行业的老鸟或是对IT行业感兴趣的新人,都欢迎加入我们的的圈子(技术交流、学习资源、职场吐槽、大厂内推、面试辅导),让我们一起学习成长!

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

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

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

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 {


![img](https://img-blog.csdnimg.cn/img_convert/6088f7c1872224465268844c6080c252.png)
![img](https://img-blog.csdnimg.cn/img_convert/78d88eb01c365ce32104701e3a9ff91c.png)

**既有适合小白学习的零基础资料,也有适合3年以上经验的小伙伴深入学习提升的进阶课程,涵盖了95%以上C C++开发知识点,真正体系化!**

**由于文件比较多,这里只是将部分目录截图出来,全套包含大厂面经、学习笔记、源码讲义、实战项目、大纲路线、讲解视频,并且后续会持续更新**

**[如果你需要这些资料,可以戳这里获取](https://bbs.csdn.net/topics/618668825)**

-1715550451137)]

**既有适合小白学习的零基础资料,也有适合3年以上经验的小伙伴深入学习提升的进阶课程,涵盖了95%以上C C++开发知识点,真正体系化!**

**由于文件比较多,这里只是将部分目录截图出来,全套包含大厂面经、学习笔记、源码讲义、实战项目、大纲路线、讲解视频,并且后续会持续更新**

**[如果你需要这些资料,可以戳这里获取](https://bbs.csdn.net/topics/618668825)**

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值