栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Go语言

Golang Gin embed static 静态文件嵌入

Go语言 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Golang Gin embed static 静态文件嵌入

Golang Gin embed 静态文件嵌入
  • 需求
  • 改进思路
    • a). Gin文档 静态资源嵌入 方案
    • b). Gin 自带方法
      • 代码
      • 效果
    • c). 改进
      • 1. 自带http库做法
      • 2. 查看gin staticfs源码
      • 3. 最终解决方案

需求

用Gin开发Web服务时, 编译生成的应用可能如下, 需提供static目录和web-app.exe给用户
如果将static文件夹到生成的exe中,分发单个EXE文件给用户使用,更加方便

# 改进前
├── static
│   └── js/jquery.min.js
│   ├── favicon.ico
│   ├── index.html
├── web-app.exe
# 改进后
├── web-app.exe (static内嵌进exe里)
改进思路 a). Gin文档 静态资源嵌入 方案

参考: https://learnku.com/docs/gin-gonic/1.7/examples-bind-single-binary-with-template/11403
需要使用额外工具go-assets,操作有点复杂,因此不考虑

b). Gin 自带方法 代码
package main
import (
	"embed"
	"net/http"
	"github.com/gin-gonic/gin"
)
//go:embed static
	r.Any("/static/*filepath", func(c *gin.Context) {
		staticServer := http.FileServer(http.FS(fs))
		staticServer.ServeHTTP(c.Writer, c.Request)
	})
	r.Run("localhost:80")
}

查看效果达到预期

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/904158.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号