在 Golang 中加载图像和 css

Load image and css in Golang

我在项目根目录mainserver.js中设置了一个路由

http.HandleFunc("/",route.IndexHandler)

IndexHandler 在包 route 中的实现方式如下:

func IndexHandler(w http.ResponseWriter, r *http.Request) {
    data:=struct{
        Name string
    }{
        "My name",
    }
    util.RenderTemplate(w, "index", data)
}

RenderTemplate 函数在包 util 中的实现方式如下:

func RenderTemplate(w http.ResponseWriter, tmpl string, data interface{}) {
    cwd, _ := os.Getwd()
    t, err := template.ParseFiles(filepath.Join(cwd, "./view/" + tmpl + ".html"))
    if err != nil {
        http.Error(w, err.Error(), http.StatusInternalServerError)
        return
    }
    err = t.Execute(w, data)
    if err != nil {
        http.Error(w, err.Error(), http.StatusInternalServerError)
    }
}

项目中的目录结构如下:

/
/public/css
/public/images
/public/js
/route
/view

index.html 视图位于文件夹 view 中,路由器位于文件夹 route

index.html 中,我包含了如下资源:

<link rel="stylesheet" type="text/css" href="../public/css/style.css">

<img src="../public/images/img_landing_page_mac.png">

当请求适当的路径时,index.html 仍然呈现,但不加载图像和样式表。我怎样才能将它们包含在 Golang html 模板引擎中?

您需要明确要求您的服务器提供静态文件。

http.FileServer

在你的情况下注册另一个处理程序。

http.Handle("/public/", http.StripPrefix("/public/", http.FileServer(http.Dir("public"))))

如Aruna所说,注册一个静态文件服务器句柄

http.Handle("/public/", http.StripPrefix("/public/", http.FileServer(http.Dir("public"))))

要使用 HTML 中的文件,只需

<img src="/public/images/img_landing_page_mac.png">