From 0fb4aa53e9ebaabf49116a841ce1eb7a7827a1d1 Mon Sep 17 00:00:00 2001 From: Will Charczuk Date: Thu, 11 Oct 2018 17:18:46 -0700 Subject: [PATCH] adds a rerender example --- _examples/rerender/main.go | 50 ++++++++++++++++++++++++++++++++++++++ util/time.go | 5 ++++ 2 files changed, 55 insertions(+) create mode 100644 _examples/rerender/main.go diff --git a/_examples/rerender/main.go b/_examples/rerender/main.go new file mode 100644 index 0000000..8ba4ba6 --- /dev/null +++ b/_examples/rerender/main.go @@ -0,0 +1,50 @@ +package main + +import ( + "log" + "net/http" + "sync" + "time" + + "github.com/wcharczuk/go-chart/util" + + chart "github.com/wcharczuk/go-chart" +) + +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) + ts.YValues = append(ts.YValues, util.Time.Millis(e)) + 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)) +} diff --git a/util/time.go b/util/time.go index e48b10b..7d68f91 100644 --- a/util/time.go +++ b/util/time.go @@ -9,6 +9,11 @@ var ( type timeUtil struct{} +// Millis returns the duration as milliseconds. +func (tu timeUtil) Millis(d time.Duration) float64 { + return float64(d) / float64(time.Millisecond) +} + // TimeToFloat64 returns a float64 representation of a time. func (tu timeUtil) ToFloat64(t time.Time) float64 { return float64(t.UnixNano())