Created
December 22, 2018 10:44
-
-
Save jtbonhomme/03dab578055349a5393d0d7a5f3b67a0 to your computer and use it in GitHub Desktop.
Pure random data generator
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"log" | |
"net/http" | |
"time" | |
"math/rand" | |
chart "github.com/wcharczuk/go-chart" | |
) | |
const SAMPLES = 200 | |
const SCALE = "24h" | |
func addData(ts *chart.TimeSeries, start time.Time, d time.Duration, samples int) { | |
t := start | |
r := rand.New(rand.NewSource(time.Now().UnixNano())) | |
for i := 0; i < samples; i++ { | |
ts.XValues = append(ts.XValues, t) | |
ts.YValues = append(ts.YValues, r.Float64()) | |
t = t.Add(d) | |
} | |
} | |
func drawChart(res http.ResponseWriter, req *http.Request) { | |
var graph *chart.Chart | |
var ts *chart.TimeSeries | |
ts = &chart.TimeSeries{ | |
XValues: []time.Time{}, | |
YValues: []float64{}, | |
} | |
graph = &chart.Chart{ | |
Series: []chart.Series{ts}, | |
} | |
duration, _ := time.ParseDuration(SCALE) | |
end := time.Now() | |
start := end.Add(-duration) | |
addData(ts, start, duration/SAMPLES, SAMPLES) | |
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() { | |
http.HandleFunc("/", drawChart) | |
log.Printf("Open http://localhost:8080\n") | |
log.Fatal(http.ListenAndServe(":8080", nil)) | |
} |
Author
jtbonhomme
commented
Dec 22, 2018
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment