duanhui4160 2018-12-13 07:58
浏览 58
已采纳

如何使template.Execute()写入文件而不是response.Writer?

I have a below code to parse the template file and write the parsed html to ResponseWriter:-

package main

import (
    "net/http"
    "html/template"
)

func handler(w http.ResponseWriter, r *http.Request) {
    t, _ := template.ParseFiles("view.html")
    t.Execute(w, "Hello World!")
}

func main() {
    server := http.Server{
        Addr: "127.0.0.1:8080",
    }
    http.HandleFunc("/view", handler)
    server.ListenAndServe()
}  

and the template file "template.html" is as:

<html>
<head>
    <title>First Program</title>
</head>
<body>
    {{ . }}
</body>
</html>  

Now, Instead of writing parsed/executed file to ResponseWriter, I would like to write those contents to html file say "parsed.html". How can I achieve it. I'm new to Go, so having hard time getting the idea. Thank you.

  • 写回答

1条回答 默认 最新

  • douxing1353 2018-12-13 08:21
    关注

    Here's one way to do it:

    t, err := template.ParseFiles("view.html")
    if err != nil {
        // handle error
    }
    
    // Create the file
    f, err := os.Create("parsed.html")
    if err != nil {
        // handle error
    }
    
    // Execute the template to the file.
    err = t.Execute(f, "Hello World!")
    if err != nil {
        // handle error
    }
    
    // Close the file when done.
    f.Close()
    

    Run it on the playground

    Key Point: An *os.File and an http.ResponseWriter both satisfy the io.Writer interface used in the first argument to Execute.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥30 eclipse开启服务后,网页无法打开
  • ¥30 雷达辐射源信号参考模型
  • ¥15 html+css+js如何实现这样子的效果?
  • ¥15 STM32单片机自主设计
  • ¥15 如何在node.js中或者java中给wav格式的音频编码成sil格式呢
  • ¥15 不小心不正规的开发公司导致不给我们y码,
  • ¥15 我的代码无法在vc++中运行呀,错误很多
  • ¥50 求一个win系统下运行的可自动抓取arm64架构deb安装包和其依赖包的软件。
  • ¥60 fail to initialize keyboard hotkeys through kernel.0000000000
  • ¥30 ppOCRLabel导出识别结果失败