2024年最全go embed 实现gin + vue静态资源嵌入_gin embed vue(2),掌握这些知识点再也不怕面试通不过

img
img

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

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

如果你需要这些资料,可以戳这里获取

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


此时首页正常加载出来了。  
 ![在这里插入图片描述](https://img-blog.csdnimg.cn/4493fbbc182246b58dd97483d40793d0.png)


但是,当我讲这段代码放到项目里使用时,却根本无法工作!  
 原因就是路由冲突了。  
 因为`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`了:  
 ![在这里插入图片描述](https://img-blog.csdnimg.cn/c0ac8ec154f243c791e7e2c9400dd8a6.png)  
 报错内容为: `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§ < 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)

img
img

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

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

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

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

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

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

  • 26
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值