首页 > 解决方案 > 如何在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

标签: cssgo

解决方案


首先,您需要在 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")

推荐阅读