在Go

时间:2016-09-26 19:54:47

标签: html http go go-templates

尝试使用.html包将值传递到html/template代码时。

但是,我似乎无法设置.css文件中引用的.html内容类型。它以纯文本形式提供给浏览器,因此忽略了格式化。

在静态.html文件中,我可以使用内置http.Fileserver来处理内容类型,但模板不起作用。我无法传递变量。它只显示为{{.}}

有没有办法将内置文件服务器content-type的{​​{1}}方便性与http.Fileserver的模板功能相结合?

这是我的代码,因为它没有使用http.HandleFunc。请注意,我的http.Fileserver文件位于起始目录中,Goindex.html文件位于子目录.css中:

/hello/

这是我的package main import ( "html/template" "io/ioutil" "log" "net/http" ) var Message string = "test page" func servePipe(w http.ResponseWriter, req *http.Request) { dat, err := ioutil.ReadFile("hello/index.html") if err != nil { log.Fatal("couldn't read file:", err) } templ, err := template.New("Test").Parse(string(dat)) if err != nil { log.Fatal("couldn't parse page:", err) } templ.Execute(w, Message) } func main() { http.HandleFunc("/hello/", servePipe) http.ListenAndServe(":8080", nil) } 文件。正在提供html页面没有任何问题。它是未提供的单独.html文件(在.css文件中链接),因此格式化不会发生。

.html

2 个答案:

答案 0 :(得分:4)

Template.Execute()将"传递"调用传递的io.Writer Write()方法的内容,在您的情况下为http.ResponseWriter

如果您在第一次拨打ResponseWriter.Write()之前没有设置内容类型(您的例子中没有),那么net/http包将尝试检测内容类型(基于写入的前512个字节),并将自动为您设置(如果尚未调用WriteHeader(http.StatusOK),则为ResponseWriter.WriteHeader()。)

这在http.ResponseWriter.Write()

中有记录
// Write writes the data to the connection as part of an HTTP reply.
//
// If WriteHeader has not yet been called, Write calls
// WriteHeader(http.StatusOK) before writing the data. If the Header
// does not contain a Content-Type line, Write adds a Content-Type set
// to the result of passing the initial 512 bytes of written data to
// DetectContentType.
//
// ...
Write([]byte) (int, error)

因此,如果您的index.html看起来像这样:

<html>
  <body>
    This is the body!
  </body>
</html>

然后,这将被正确检测为HTML文档,因此将自动设置text/html内容类型。如果您没有这样做,则表示您的index.html无法识别为HTML文档。因此,请确保您的模板文件有效,HTML / CSS /等文档和内容类型将自动正确推断。

另请注意,如果它不适用于某些极端的&#34;在某些情况下,您可以随时&#34;覆盖&#34;它可以在调用Template.Execute()之前手动设置它,如下所示:

w.Header().Set("Content-Type", "text/html")
templ.Execute(w, Message)

附注:请勿在处理程序中阅读和解析模板,有关详细信息,请参阅相关问题:It takes too much time when using "template" package to generate a dynamic web page to client in golang

如果您提供的模板引用了其他模板,则不会神奇地加载和执行它们。在这种情况下,您应该预先加载&#34;预先加载&#34;包含所有模板的模板。 template.ParseFiles()template.ParseGlob()是好的&#34;工具&#34;一次加载多个模板文件。

因此,如果您的index.html引用style.css,则您必须注意提供style.css。如果它不是模板(例如静态文件),您可以使用此处显示的多个选项进行投放:Include js file in Go template

如果它也是模板,那么您还必须加载它并通过调用Template.ExecuteTemplate()来提供它。

一个示例解决方案是使用template.ParseFiles()加载两者,并使用路径指定&#34;指定&#34;您希望提供哪个模板(从客户端/浏览器端)。

E.g。请求路径/hello/index.html可以提供"index.html"模板,请求路径/hello/style.css这将在接收和处理index.html后由浏览器自动完成)可以提供"style.css"模板。它看起来像这样(为简洁起见,省略了错误检查):

parts := strings.Split(req.URL.Path, "/") // Parts of the path
templName := parts[len(parts)-1]          // The last part
templ.ExecuteTemplate(w, templName, someDataForTemplate)

答案 1 :(得分:1)

模板化,即生成作为HTTP响应主体的HTML,与通过HTTP头传输的内容类型完全分离。只需在通过tmpl.Execute(w, ...)生成正文之前将Content-Type设置为适当的

w.Header().Set("Content-Type", "text/css")