go-examples/tpl-ex3/main.go

60 lines
1.0 KiB
Go
Raw Normal View History

2017-07-26 18:34:08 +00:00
package main
import (
"html/template"
"io"
"log"
"net/http"
"os"
2017-07-27 16:31:24 +00:00
"meutel.net/meutel/go-examples/tpl-ex3/records"
)
2017-07-26 18:34:08 +00:00
type TplData struct {
Columns []string
2017-07-27 16:31:24 +00:00
Rows []records.FinancialData
2017-07-26 18:34:08 +00:00
}
2017-07-27 16:31:24 +00:00
func printHTML(tpl *template.Template, cols []string, rows []records.FinancialData, out io.Writer) {
2017-07-26 18:34:08 +00:00
tplData := TplData{
2017-07-27 16:31:24 +00:00
cols,
rows,
2017-07-26 18:34:08 +00:00
}
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
2017-07-27 16:31:24 +00:00
cols, rows := records.ReadCsv(csv)
2017-07-26 18:34:08 +00:00
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) {
2017-07-27 16:31:24 +00:00
printHTML(tpl, cols, rows, res)
2017-07-26 18:34:08 +00:00
})
http.ListenAndServe(":9000", nil)
}