I have inserted dummy data into the database.
The sample print function prints 13 and its square as per the code in the console. But I need to pass the entire data to the HTML template(index) where I can see a table of all the numbers passed with their respective square number.
How to pass this data in index HTML?
Number x Number = SquareNumber 1 x 1 = 1 2 x 2 = 4 3 x 3 = 9
... and so on.
func main() {
db, err := sql.Open("mysql", "root:@/godb")
if err != nil {
panic(err.Error())
}
defer db.Close()
stmtIns, err := db.Prepare("INSERT INTO squarenum VALUES(?, ?, ? )") // ? =
placeholder
if err != nil {
panic(err.Error()) }
defer stmtIns.Close()
stmtOut, err := db.Prepare("SELECT squareNum FROM squareNum WHERE number =
?")
if err != nil {
panic(err.Error())
}
defer stmtOut.Close()
for i := 1; i < 50; i++ {
_, err = stmtIns.Exec(0,i, (i * i))
if err != nil {
panic(err.Error())
}
}
err = stmtOut.QueryRow(13).Scan(&squareNum) // WHERE number = 13
if err != nil {
panic(err.Error()) // proper error handling instead of panic in your app
}
tRes:=pageData{}
tRes.SquareNum=squareNum
fmt.Printf("The square number of 13 is: %d
", squareNum)
// Query another number.. 1 maybe?
err = stmtOut.QueryRow(1).Scan(&squareNum) // WHERE number = 1
if err != nil {
panic(err.Error()) // proper error handling instead of panic in your app
}
fmt.Printf("The square number of 1 is: %d
", squareNum)
http.HandleFunc("/",idx)
http.ListenAndServe(":8888", nil)
}
func idx(w http.ResponseWriter, r *http.Request) {
pd := pageData{
SquareNum: squareNum,
}
err := tpl.ExecuteTemplate(w, "index.html", pd)
if err != nil {
log.Println("LOGGED", err)
http.Error(w, "Internal server error", http.StatusInternalServerError)
return
}
}
package main
import (
"html/template"
"os"
)
// here is your template
const tplString = `
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>{{.Title}}</title>
</head>
<body>
{{range .Dummies}}
<div>Square of {{.Number}} is {{.Square}}</div>
{{end}}
</body>
</html>
`
var (
tpl *template.Template
err error
)
// the dummydata you talked about
type DummyData struct {
Number int
Square int
}
//some PageData just with dummies and a title
type PageData struct {
Title string
Dummies []*DummyData
}
//here you would be using your sql queries
func createSomeDummies(amount int) []*DummyData {
dummies := make([]*DummyData, amount)
for i := 0; i < amount; i++ {
dd := new(DummyData)
dd.Number = i
dd.Square = i * i
dummies[i] = dd
}
return dummies
}
func main() {
pd := new(PageData)
pd.Title = "Hello Dummies"
pd.Dummies = createSomeDummies(10)
tpl = template.New("index")
tpl, err = tpl.Parse(tplString)
if err != nil {
panic(err)
}
err = tpl.Execute(os.Stdout, pd)
if err != nil {
panic(err)
}
}
This Snippet creates a PageData struct to hold the array of dummydata entries and a Title for the webpage.
type PageData struct {
Title string
Dummies []*DummyData
}
It then uses a function to create 10 dummydata structs. This array is then assigned to the Dummmies field of the PageData.
pd.Dummies = createSomeDummies(10)
This function is a placeholder for your sql query function you just have to loop over your sql rows instead of manually creating them like i do.
func createSomeDummies(amount int) []*DummyData {
dummies := make([]*DummyData, amount)
for i := 0; i < amount; i++ {
dd := new(DummyData)
dd.Number = i
dd.Square = i * i
dummies[i] = dd
}
return dummies
}
The Template itself inserts the title like so: <title>{{.Title}}</title>
The Dummies themselves are inserted by a range template directive that works like a for iterator. The one thing to be careful about is that inside this loop all data points to the DummyData item and not the PageData
{{range .Dummies}}
<div>Square of {{.Number}} is {{.Square}}</div>
{{end}}
Then the template is parsed. Errors will halt execution and print the error message.
tpl = template.New("index")
tpl, err = tpl.Parse(tplString)
if err != nil {
panic(err)
}
And finally the template will be rendered to Stdout. For use in a http Handler you would have to use the http.ResponseWriter instead. Once again errors halt execution and print the error message.
err = tpl.Execute(os.Stdout, pd)
if err != nil {
panic(err)
}
Working Example here: Go Playground