go-examples/tpl-ex3/main.go
2017-07-27 18:31:24 +02:00

60 lines
1.0 KiB
Go

package main
import (
"html/template"
"io"
"log"
"net/http"
"os"
"meutel.net/meutel/go-examples/tpl-ex3/records"
)
type TplData struct {
Columns []string
Rows []records.FinancialData
}
func printHTML(tpl *template.Template, cols []string, rows []records.FinancialData, out io.Writer) {
tplData := TplData{
cols,
rows,
}
err := tpl.ExecuteTemplate(out, "tpl.html", tplData)
if err != nil {
panic(err)
}
}
func main() {
if len(os.Args) < 2 {
log.Fatalln("Usage go-financial <file>")
}
// read input
csv, err := os.Open(os.Args[1])
if err != nil {
log.Fatalln("Error reading file", err)
}
defer csv.Close()
// parse data
cols, rows := records.ReadCsv(csv)
tpl, err := template.New("").Funcs(template.FuncMap{
"class": func(index int) string {
if index%2 == 0 {
return "even"
}
return "odd"
},
}).ParseFiles("tpl.html", "script.js")
if err != nil {
panic(err)
}
http.HandleFunc("/", func(res http.ResponseWriter, req *http.Request) {
printHTML(tpl, cols, rows, res)
})
http.ListenAndServe(":9000", nil)
}