在我们用golang进行web开发过程中,有是需要将前段编译好的项目打包到golang的二进制中,方便发布;
话不多说上菜:
1.在项目的最外层建立一个web目录:

其中backend和installer 都是前段编译好的代码
2.在目录中建立一个fs.go的文件内容如下:

//go:embed backend
var BackendFs embed.FS

//go:embed installer/*
var InstallerFs embed.FS

其中backendFs 和 installFs 都是接收前段代码的fs

  1. 在路由中应用, 以Echo路由为例:
securityIn =: "" //这个是访问地址,可用是动态的
securityInAb := strings.TrimLeft(strings.TrimRight(securityIn, "/"), "/")
	securityInFs := "/*"
	if securityInAb != "" {
		securityInFs = fmt.Sprintf("/%s%s", securityInAb, securityInFs)
	}
	// 路由
	// 分两种,1.固定,2.动态(动态就要动态取的去掉前缀,这也是为什么要用http.stripPrefix的原因)
e.Any(securityInFs, func(c echo.Context) error {
		fsys, err := fs.Sub(web.BackendFs, "backend")
		if err != nil {
			panic(err)
		}

		var ser http.Handler
		if securityInAb == "" {
			ser = http.FileServer(http.FS(fsys))
		} else {
		// 去掉前缀,就是fs不会取找前缀的文件
			ser = http.StripPrefix(fmt.Sprintf("/%s/", securityInAb), http.FileServer(http.FS(fsys)))
		}
		ser.ServeHTTP(c.Response().Writer, c.Request())
		return nil
	})
  1. 访问 xxx.com/ 或者动态的xxx.com/xxx

这样通过go build只会生成一个可执行文件,运行后直接访问路由就可以了,没有前段代码