gochart/server.go

65 lines
1.3 KiB
Go
Raw Normal View History

2014-12-26 17:42:51 +08:00
package main
import (
2014-12-26 20:25:03 +08:00
//"fmt"
"net/http"
"text/template"
2017-03-16 16:27:33 +08:00
"strconv"
"log"
)
2014-12-26 20:25:03 +08:00
var (
ChartHandlers = make(map[string]ChartIf)
ChartFiles []string
Index int
)
2014-12-26 17:37:11 +08:00
func handler(w http.ResponseWriter, r *http.Request) {
2017-03-16 16:27:33 +08:00
values := r.URL.Query()
i := values.Get("index")
if len(i) > 0 {
Index, _ = strconv.Atoi(i)
} else {
Index++
}
Index = Index % len(ChartFiles)
log.Printf("Index=%v rendering %v", Index, ChartFiles[Index])
tt, err := Parse(ChartFiles[Index])
if err != nil {
w.Write([]byte(err.Error()))
return
2014-12-26 17:37:11 +08:00
}
2014-12-26 17:42:51 +08:00
if t, err := template.New("foo").Parse(tt.tmpl); err != nil {
w.Write([]byte(err.Error()))
} else {
if err = t.ExecuteTemplate(w, "T", tt.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) {})
2014-12-26 20:25:03 +08:00
var err error
ChartFiles, err = LookupChartFiles(".")
if err != nil {
return err
}
// Register chart handlders
2014-12-26 20:25:03 +08:00
ChartHandlers["spline"] = new(SplineChart)
ChartHandlers["column"] = new(SplineChart)
ChartHandlers["area"] = new(SplineChart)
ChartHandlers["bar"] = new(SplineChart)
ChartHandlers["line"] = new(SplineChart)
ChartHandlers["pie"] = new(PieChart)
return http.ListenAndServe(addr, nil)
}