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 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!