rgoplot/server.go

113 lines
2.2 KiB
Go
Raw Normal View History

2013-09-05 00:55:21 +08:00
package main
import (
"net/http"
"path/filepath"
"strings"
2013-09-05 00:55:21 +08:00
"text/template"
)
const html = `{{define "T"}}
<!doctype html>
<html>
2013-09-05 01:10:16 +08:00
<head>
<script>
{{.Chartjs}}
2013-09-05 00:55:21 +08:00
</script>
2013-09-05 01:10:16 +08:00
<meta name = "viewport" content = "initial-scale = 1, user-scalable = no">
<style>
canvas{
2013-09-05 00:55:21 +08:00
}
2013-09-05 01:10:16 +08:00
</style>
</head>
<body>
2013-09-05 15:54:13 +08:00
<div style="padding-top:30px;">
By <a href="http://www.bigendian123.com/skoo.html" target="_blank">skoo</a>
</div>
2013-09-05 00:55:21 +08:00
<div style="padding-top:30px;"></div>
{{.Canvas}}
<script>
{{.JsonCode}}
{{.NewChart}}
</script>
2013-09-05 01:10:16 +08:00
</body>
2013-09-05 00:55:21 +08:00
</html>
{{end}}
`
type ChartIf interface {
Canvas(string, int, int) string
JsonCode(*ChartDataType) (string, error)
NewChart(string) string
}
var ChartHandlers = make(map[string]ChartIf)
2013-09-05 00:55:21 +08:00
func handler(w http.ResponseWriter, r *http.Request) {
urls := strings.Split(r.URL.String(), "/")
if 2 > len(urls) {
w.Write([]byte("RouteError"))
2013-09-05 15:54:13 +08:00
return
}
file := urls[1] + ".chart"
file = filepath.Join(ChartDir, file)
2013-09-05 15:54:13 +08:00
datas, err := ParseDataFile(file)
2013-09-05 00:55:21 +08:00
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
}
2013-09-05 00:55:21 +08:00
2013-09-05 01:10:16 +08:00
canvas := chart.Canvas("line", prop.Height, prop.Width)
2013-09-05 00:55:21 +08:00
Args["Canvas"] = canvas
2013-09-05 01:10:16 +08:00
newChart := chart.NewChart("line")
2013-09-05 00:55:21 +08:00
Args["NewChart"] = newChart
if json, err := chart.JsonCode(c); err != nil {
w.Write([]byte(err.Error()))
return
} else {
Args["JsonCode"] = json
}
}
2013-09-05 15:54:13 +08:00
if t, err := template.New("foo").Parse(html); err != nil {
2013-09-05 00:55:21 +08:00
w.Write([]byte(err.Error()))
2013-09-05 15:54:13 +08:00
} else {
if err = t.ExecuteTemplate(w, "T", Args); err != nil {
w.Write([]byte(err.Error()))
}
2013-09-05 00:55:21 +08:00
}
}
func ListenAndServe(addr string) error {
http.HandleFunc("/", handler)
http.HandleFunc("/favicon.ico", func(w http.ResponseWriter, r *http.Request) {})
2013-09-05 15:54:13 +08:00
2013-09-05 00:55:21 +08:00
return http.ListenAndServe(addr, nil)
}