css - 如何在golang中将CSS文件与html页面链接
问题描述
将图像和 CSS 文件链接到使用 golang 用作 API 的 html 文件的适当方法是什么
我尝试了以下代码,但 CSS 和图像没有呈现,我使用 julienschmidt 库来路由 API
var tpl *template.Template
func init() {
tpl = template.Must(template.ParseGlob("*.html"))
}
func main(){
router := httprouter.New()
router.GET("/", indexPage)
}
func indexPage(w http.ResponseWriter, r *http.Request, _ httprouter.Params){
tpl.ExecuteTemplate(w, "index.html", nil)
}
在 index.html 我使用链接来使用外部 CSS 文件
<link rel="stylesheet" type="text/css" href="public/css/main.css" />
文件结构是
/go
/src
/github.com
/My_account
/WebServerProject
-main.go
-index.html
/public
/css
-main.css
/images
解决方案
首先,您需要在 Web 服务器上提供静态文件,您还可以将代码分段到目录中的模板中,然后提供该目录。
r := gin.Default()
files, err := filepath.Glob("./app/templates/*.tmpl")
if err == nil && files != nil {
r.LoadHTMLGlob("./app/templates/*.tmpl")
}
v1 := r.Group("/v1")
v1.Static("/static", "./_assets/static")
推荐阅读
- mysql - 试图在我的选择语句中不获取重复的列
- android - 如何使未选择的片段看起来比当前选择的片段小一点
- python-3.x - AWS - 从 Lambda 获取存储网关的激活密钥
- c# - 将嵌套 XML 绑定到 DataGridView
- typescript - 为什么来自 tensorflowjs 的 model.predict() 总是返回相同的预测?
- sql - 如何按集群汇总金额并查找附加值
- c# - ANTLR4 commonTokenStream.GetTokens() 没有得到所有令牌
- php - 如何合并唯一的这两个数组?
- aws-lambda - Terraform:为什么这种链接资源的尝试不起作用?
- java - 对多个 aar 使用相同的 .jar。在同一个项目中