Created
September 22, 2019 22:10
-
-
Save R4wm/4139b73fa9038de8766aa79fe8f80291 to your computer and use it in GitHub Desktop.
example embedded png plots html outputter
This file contains 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 ( | |
"bytes" | |
"encoding/base64" | |
"fmt" | |
"log" | |
"math/rand" | |
"net/http" | |
"time" | |
"gonum.org/v1/plot" | |
"gonum.org/v1/plot/plotter" | |
"gonum.org/v1/plot/plotutil" | |
"gonum.org/v1/plot/vg" | |
) | |
const template = ` | |
<div> | |
<p>Fake data for now</p> | |
<img src="data:image/png;base64, %s" alt="phrase_search" /> | |
</div> | |
` | |
func getGraph() string { | |
// returns base64 encoded png string | |
rand.Seed(time.Now().UTC().UnixNano()) | |
p, err := plot.New() | |
if err != nil { | |
panic(err) | |
} | |
p.Title.Text = "Some Bible Search" | |
p.Y.Label.Text = "Count" | |
p.X.Label.Text = "Matthew" | |
err = plotutil.AddLinePoints(p, | |
"ThatPhrase", randomPoints(15), | |
) | |
if err != nil { | |
panic(err) | |
} | |
vgWid := 4 * vg.Inch | |
vgHig := 4 * vg.Inch | |
format := "png" | |
stuff, err := p.WriterTo(vgWid, vgHig, format) | |
if err != nil { | |
println("Failed WriterTo") | |
panic(err) | |
} | |
var buf bytes.Buffer | |
stuff.WriteTo(&buf) | |
//////////////////////////////// | |
// Write the html page // | |
//////////////////////////////// | |
encodedPNG := base64.StdEncoding.EncodeToString(buf.Bytes()) | |
return fmt.Sprintf(template, encodedPNG) | |
} | |
// randomPoints returns some random x, y points. | |
func randomPoints(n int) plotter.XYs { | |
pts := make(plotter.XYs, n) | |
for i := range pts { | |
fmt.Println("i: ", i) | |
if i == 0 { | |
pts[i].X = rand.Float64() | |
fmt.Printf("pts[%d].X + rand.Float64 = %v\n", i, pts[i].X) | |
} else { | |
pts[i].X = pts[i-1].X + rand.Float64() | |
} | |
pts[i].Y = pts[i].X + 10*rand.Float64() | |
} | |
fmt.Printf("randomPoints.pts: %v\n", pts) | |
return pts | |
} | |
func handler(w http.ResponseWriter, r *http.Request) { | |
graph := getGraph() | |
fmt.Fprintf(w, graph) | |
} | |
func main() { | |
http.HandleFunc("/", handler) | |
log.Fatal(http.ListenAndServe(":8080", nil)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment