golang 将一段文本保存成html文件
时间: 2023-12-20 11:04:41 浏览: 33
可以使用Go语言的标准库和一些HTML模板,将文本保存为HTML文件。
以下是一个将文本保存为HTML文件的示例代码:
```go
package main
import (
"fmt"
"html/template"
"os"
)
func main() {
text := "Hello, World!"
fileName := "output.html"
// Create a new file for writing.
file, err := os.Create(fileName)
if err != nil {
fmt.Println(err)
os.Exit(1)
}
defer file.Close()
// Define the HTML template.
tpl := `<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>{{.Title}}</title>
</head>
<body>
<p>{{.Text}}</p>
</body>
</html>`
// Parse the template.
t, err := template.New("output").Parse(tpl)
if err != nil {
fmt.Println(err)
os.Exit(1)
}
// Define the data to be rendered in the template.
data := struct {
Title string
Text string
}{
Title: "Output HTML",
Text: text,
}
// Render the template into the file.
err = t.Execute(file, data)
if err != nil {
fmt.Println(err)
os.Exit(1)
}
fmt.Printf("Successfully saved text as HTML to %s\n", fileName)
}
```
这个示例代码将一段文本“Hello, World!”保存为一个名为output.html的HTML文件。你可以根据需要自行调整。