This question already has an answer here:
I need represent a struct array(load from Mysql) within a template HTML. but the template.Execute() method write response as a string, not represent as a HTML page. can someone help me ?
import (
"fmt"
"log"
"time"
"net/http"
"database/sql"
_ "github.com/go-sql-driver/mysql"
s "strings"
"html/template"
"io/ioutil"
)
var p = fmt.Println
type ListData struct{
Id int
Os sql.NullString
Title string
}
func searchHandler(w http.ResponseWriter, r *http.Request) {
db,er := sql.Open("mysql","root:11b@tcp(localhost:3306)/collection")
cursor := []ListData{}
for rows.Next() {
//load data here....
}
t, pErr := template.ParseFiles("./admin/list.html")
if pErr != nil {
panic(pErr)
}
pErr = t.Execute(w, cursor)
if pErr != nil {
http.Error(w, pErr.Error(), http.StatusInternalServerError)
return
}
}//end of searchHandler
func main(){
p("start servlet.")
//other handlers
http.HandleFunc("/search", searchHandler)
log.Fatal(http.ListenAndServe(":8080", nil))
}
I embed few go code into this HTML files:
........
<thead>
<tr>
<th>id</th>
<th>os</th>
<th>title</th>
</tr>
</thead>
<tbody>
{{range .}}
<tr class="success">
<td>{{.Id}}</td>
<td>{{.Os}}</td>
<td>{{.Title}}</td>
</tr>
{{end}}
</tbody>
.....
Can not load as a HTML page after template.Execute done
</div>
The browser is rendering the page as it was a text. This is because it received no content type from the server. You need to set it in the header.
w.Header().Set("Content-Type", "text/html")