Skip to content

Commit ff317fc

Browse files
fix serve and refactor
1 parent 4b5f552 commit ff317fc

File tree

1 file changed

+14
-25
lines changed

1 file changed

+14
-25
lines changed

offline/plot.go

Lines changed: 14 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,6 @@ package offline
33
import (
44
"bytes"
55
"encoding/json"
6-
"fmt"
76
"io/ioutil"
87
"log"
98
"net/http"
@@ -20,22 +19,18 @@ type Options struct {
2019

2120
// ToHtml saves the figure as standalone HTML. It still requires internet to load plotly.js from CDN.
2221
func ToHtml(fig *grob.Fig, path string) {
23-
figBytes, err := json.Marshal(fig)
24-
if err != nil {
25-
panic(err)
26-
}
27-
tmpl, err := template.New("plotly").Parse(baseHtml)
28-
if err != nil {
29-
panic(err)
30-
}
31-
buf := &bytes.Buffer{}
32-
tmpl.Execute(buf, string(figBytes))
22+
buf := figToBuffer(fig)
3323
ioutil.WriteFile(path, buf.Bytes(), os.ModePerm)
3424
}
3525

3626
// Show displays the figure in your browser.
3727
// Use serve if you want a persistent view
3828
func Show(fig *grob.Fig) {
29+
buf := figToBuffer(fig)
30+
browser.OpenReader(buf)
31+
}
32+
33+
func figToBuffer(fig *grob.Fig) *bytes.Buffer {
3934
figBytes, err := json.Marshal(fig)
4035
if err != nil {
4136
panic(err)
@@ -46,10 +41,11 @@ func Show(fig *grob.Fig) {
4641
}
4742
buf := &bytes.Buffer{}
4843
tmpl.Execute(buf, string(figBytes))
49-
browser.OpenReader(buf)
44+
return buf
5045
}
5146

5247
// Serve creates a local web server that displays the image using plotly.js
48+
// Is a good alternative to Show to avoid creating tmp files.
5349
func Serve(fig *grob.Fig, opt ...Options) {
5450
opts := computeOptions(Options{
5551
Addr: "localhost:8080",
@@ -60,23 +56,16 @@ func Serve(fig *grob.Fig, opt ...Options) {
6056
Handler: mux,
6157
Addr: opts.Addr,
6258
}
63-
mux.HandleFunc("/data", func(w http.ResponseWriter, r *http.Request) {
64-
log.Print("Served data")
65-
encoder := json.NewEncoder(w)
66-
err := encoder.Encode(fig)
67-
if err != nil {
68-
log.Printf("Error! %s", err)
69-
}
70-
})
7159
mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
72-
log.Print("Served page")
73-
fmt.Fprint(w, baseHtml)
60+
buf := figToBuffer(fig)
61+
buf.WriteTo(w)
7462
})
7563

7664
log.Print("Starting server")
77-
err := srv.ListenAndServe()
78-
log.Print(err)
79-
log.Print("Plot served")
65+
if err := srv.ListenAndServe(); err != nil {
66+
log.Print(err)
67+
}
68+
log.Print("Stop server")
8069
}
8170

8271
func computeOptions(def Options, opt ...Options) Options {

0 commit comments

Comments
 (0)