Golang动态打印html行

I would like to print out rows from a mysql db as html. This is what I want to achieve:

<html>
<head>
...
</head>
<body>
<a href = "url1">name1</a>
<a href = "url2">name2</a>
...
</body>
</html>

My go code:

for rows.Next() {
    var name string
    var url string

    err = rows.Scan(&name, &url)
    if err != nil {
        log.Fatal(err)
    }
}

I thought that I could put the items into a slice and write them out with a for loop in a template, but instead of this is it possible to write out each line with the for loop in the go code?

It is possible but not a good idea. The template package is useful for escaping things which might have touched user input, and not hard to use. Just make a slice of things, and range over them in the template.

This is safer than trying to build html in code because the context package knows about escaping urls or js for example, as opposed to html, and takes the location of variables into account.

https://play.golang.org/p/JEIjPT5ayP

package main

import (
    "log"
    "os"
    "text/template"
)

var t = `
<html>
<head>
...
</head>
<body>
{{range . }}
  <a href = "{{.URL}}">{{.Name}}</a>
{{end}}
</body>
</html> 
`

type Location struct {
    Name string
    URL  string
}

func main() {

    // Insert read data code here
    data := []Location{{Name: "example", URL: "https://example.com"}}

    tmpl, err := template.New("foo").Parse(t)
    if err != nil {
        log.Fatal(err)
    }

    err = tmpl.Execute(os.Stdout, data)
    if err != nil {
        log.Fatal(err)
    }
}