Golang Gin embed static靜態(tài)文件嵌入問題
需求
用Gin開發(fā)Web服務(wù)時, 編譯生成的應(yīng)用可能如下, 需提供static目錄和web-app.exe給用戶
如果將static文件夾到生成的exe中,分發(fā)單個EXE文件給用戶使用,更加方便
# 改進前 ├── static │ └── js/jquery.min.js │ ├── favicon.ico │ ├── index.html ├── web-app.exe # 改進后 ├── web-app.exe (static內(nèi)嵌進exe里)
改進思路
a). Gin文檔 靜態(tài)資源嵌入 方案
參考: https://learnku.com/docs/gin-gonic/1.7/examples-bind-single-binary-with-template/11403
需要使用額外工具go-assets,操作有點復(fù)雜,因此不考慮
b). Gin 自帶方法
代碼:
package main
import (
"embed"
"net/http"
"github.com/gin-gonic/gin"
)
//go:embed static/*
var fs embed.FS
func main() {
r := gin.Default()
r.StaticFS("/static", http.FS(fs))
}
效果:
以favicon.ico為例, 需要訪問
http://localhost/static/static/favicon.ico
中間多了兩個static, 而index.html中可能資源位置是
<link rel="icon" href="/static/favicon.ico" rel="external nofollow" >

c). 改進
1. 自帶http庫做法
http.StripPrefix("/static", http.FileServer(http.FS(fs)))
2. 查看gin staticfs源碼
看下大致調(diào)用函數(shù)名,可以看到大概是這樣調(diào)用
http.FileServer(fs).ServeHTTP(c.Writer, c.Request)
func (group *RouterGroup) createStaticHandler(relativePath string, fs http.FileSystem) HandlerFunc {
absolutePath := group.calculateAbsolutePath(relativePath)
fileServer := http.StripPrefix(absolutePath, http.FileServer(fs))
return func(c *Context) {
........ 讀取fs中文件,判斷是否存在有權(quán)限等錯誤,省略
fileServer.ServeHTTP(c.Writer, c.Request)
}
}
3. 最終解決方案
package main
import (
"embed"
"net/http"
"github.com/gin-gonic/gin"
)
//go:embed static/*
var fs embed.FS
func main() {
r := gin.Default()
/*
查看staticfs方案中g(shù)in啟動日志可以看到,staticfs實際注冊了GET、HEAD
[GIN-debug] GET /static/*filepath --> github.com/gin-gonic/gin.(*RouterGroup).createStaticHandler.func1 (3 handlers)
[GIN-debug] HEAD /static/*filepath --> github.com/gin-gonic/gin.(*RouterGroup).createStaticHandler.func1 (3 handlers)
因此直接用r.Any
*/
r.Any("/static/*filepath", func(c *gin.Context) {
staticServer := http.FileServer(http.FS(fs))
staticServer.ServeHTTP(c.Writer, c.Request)
})
r.Run("localhost:80")
}
查看效果達(dá)到預(yù)期

總結(jié)
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
Go 如何基于IP限制HTTP訪問頻率的方法實現(xiàn)
這篇文章主要介紹了Go 如何基于IP限制HTTP訪問頻率的方法實現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2019-11-11
golang?slice中常見性能優(yōu)化手段總結(jié)
這篇文章主要為大家詳細(xì)一些Golang開發(fā)中常用的slice關(guān)聯(lián)的性能優(yōu)化手段,文中的示例代碼講解詳細(xì),感興趣的小伙伴可以跟隨小編一起學(xué)習(xí)一下2024-10-10
詳解Golang如何優(yōu)雅接入多個遠(yuǎn)程配置中心
這篇文章主要為大家為大家介紹了Golang如何優(yōu)雅接入多個遠(yuǎn)程配置中心詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2023-05-05

