Websites are under nearly constant attack. Most of these are automated. To prevent a certain kind of attack, a special Go module called "html/template" is available.
With this module, we pass HTML markup to a Parse()
method. Then when we call Execute()
, we insert values into special substitutions. Characters are escaped.
We must use a Writer with the "html/template" package. This program uses the bufio package to create a Writer (with NewWriter
).
template.New
. We provide a name for the template ("example").func
and pass a specially-formatted string
. The substitution comes after the word "Hello" here.package main import ( "bufio" "html/template" "os" ) func main() { // Create a file. f, _ := os.Create("file.txt") // New writer. out := bufio.NewWriter(f) // Create template and parse it. t, _ := template.New("example").Parse("<p>Hello {{.}}</p>") // Insert string into substitution. t.Execute(out, "Friend") // Done. out.Flush() }<p>Hello Friend</p>
To see the result of the program, open the file it wrote to—you will want to adjust the path before you execute the program.
The HTML is fully generated. The string
"Friend" was placed in the HTML where the substitution marker was originally present.
Generating HTML is (for the most part) not an interesting problem. But it is a useful thing to do—HTML is perhaps the most widely used document format in the world.