go-chart/examples/rerender/main.go

49 lines
933 B
Go
Raw Normal View History

2018-10-11 20:18:46 -04:00
package main
import (
"log"
"net/http"
"sync"
"time"
2024-10-27 22:52:38 -04:00
"git.smarteching.com/zeni/go-chart/v2"
2018-10-11 20:18:46 -04:00
)
var lock sync.Mutex
var graph *chart.Chart
var ts *chart.TimeSeries
func addData(t time.Time, e time.Duration) {
lock.Lock()
ts.XValues = append(ts.XValues, t)
2019-02-13 19:09:26 -05:00
ts.YValues = append(ts.YValues, chart.TimeMillis(e))
2018-10-11 20:18:46 -04:00
lock.Unlock()
}
func drawChart(res http.ResponseWriter, req *http.Request) {
start := time.Now()
defer func() {
addData(start, time.Since(start))
}()
if len(ts.XValues) == 0 {
http.Error(res, "no data (yet)", http.StatusBadRequest)
return
}
res.Header().Set("Content-Type", "image/png")
if err := graph.Render(chart.PNG, res); err != nil {
log.Printf("%v", err)
}
}
func main() {
ts = &chart.TimeSeries{
XValues: []time.Time{},
YValues: []float64{},
}
graph = &chart.Chart{
Series: []chart.Series{ts},
}
http.HandleFunc("/", drawChart)
log.Fatal(http.ListenAndServe(":8080", nil))
}