package main import ( "net/http" "path/filepath" "strings" "text/template" ) const html = `{{define "T"}}
By skoo
{{.Canvas}} {{end}} ` type ChartIf interface { Canvas(string, int, int) string JsonCode(*ChartDataType) (string, error) NewChart(string) string } var ChartHandlers = make(map[string]ChartIf) func handler(w http.ResponseWriter, r *http.Request) { urls := strings.Split(r.URL.String(), "/") if 2 > len(urls) { w.Write([]byte("RouteError")) return } file := urls[1] + ".chart" file = filepath.Join(ChartDir, file) datas, err := ParseDataFile(file) if err != nil { w.Write([]byte(err.Error())) return } if len(datas) == 0 { return } c := datas[0] var chart ChartIf var Args = map[string]string{ "Chartjs": Chartjs, } if prop, err := c.Prop(); err != nil { w.Write([]byte(err.Error())) return } else { var ok bool chart, ok = ChartHandlers[prop.Type] if !ok { w.Write([]byte(err.Error())) return } canvas := chart.Canvas("line", prop.Height, prop.Width) Args["Canvas"] = canvas newChart := chart.NewChart("line") Args["NewChart"] = newChart if json, err := chart.JsonCode(c); err != nil { w.Write([]byte(err.Error())) return } else { Args["JsonCode"] = json } } if t, err := template.New("foo").Parse(html); err != nil { w.Write([]byte(err.Error())) } else { if err = t.ExecuteTemplate(w, "T", Args); err != nil { w.Write([]byte(err.Error())) } } } func ListenAndServe(addr string) error { http.HandleFunc("/", handler) http.HandleFunc("/favicon.ico", func(w http.ResponseWriter, r *http.Request) {}) return http.ListenAndServe(addr, nil) }