gin使用embed打包html
导读:embed使用类似的注释打包html文件 //go:embed pages/dist/* 打包的代码如下package main import ( "embed" "io/fs" "net/http" "github.com/...
embed
使用类似的注释打包html文件
//go:embed pages/dist/*
打包的代码如下
package main
import (
"embed"
"io/fs"
"net/http"
"github.com/gin-gonic/gin"
)
//go:embed pages/dist/*
var embedFs embed.FS
func main() {
e := gin.Default()
fpages, _ := fs.Sub(embedFs, "pages")
fdist, _ := fs.Sub(fpages, "dist")
fjs, _ := fs.Sub(fdist, "js")
fcss, _ := fs.Sub(fdist, "css")
e.StaticFS("/js", http.FS(fjs))
e.StaticFS("/css", http.FS(fcss))
e.GET("/", func(c *gin.Context) {
c.FileFromFS("/", http.FS(fdist))
}
)
e.Run()
}
浏览器在请求服务端页面时,根据url匹配文件
io.fs.open(“/”)
返回"/“路径下所有的文件,不会递归遍历,所有c.FileFromFS(”/", http.FS(fdist))返回更目录中的所有文件
下面代码中的js和css文件在单独的目录里面,使用"/"无法访问
!doctype html>
html lang="">
head>
meta charset="utf-8">
meta http-equiv="X-UA-Compatible" content="IE=edge">
meta name="viewport" content="width=device-width,initial-scale=1">
link rel="icon" href="/favicon.ico">
title>
pages/title>
script defer="defer" src="/js/chunk-vendors.87e17c26.js">
/script>
script defer="defer" src="/js/app.cf230781.js">
/script>
link href="/css/app.2cf79ad6.css" rel="stylesheet">
/head>
body>
noscript>
strong>
We're sorry but pages doesn't work properly without JavaScript enabled. Please enable it to
continue./strong>
/noscript>
div id="app">
/div>
/body>
/html>
添加静态文件服务器
e.StaticFS(“/js”, http.FS(fjs)) e.StaticFS(“/css”, http.FS(fcss))
或者修改html相对路径,保证文件能在"/"路径中所有搜索到或者在静态文件服务器中找到。
声明:本文内容由网友自发贡献,本站不承担相应法律责任。对本内容有异议或投诉,请联系2913721942#qq.com核实处理,我们将尽快回复您,谢谢合作!
若转载请注明出处: gin使用embed打包html
本文地址: https://pptw.com/jishu/506325.html