@@ -3,7 +3,6 @@ package offline
3
3
import (
4
4
"bytes"
5
5
"encoding/json"
6
- "fmt"
7
6
"io/ioutil"
8
7
"log"
9
8
"net/http"
@@ -20,22 +19,18 @@ type Options struct {
20
19
21
20
// ToHtml saves the figure as standalone HTML. It still requires internet to load plotly.js from CDN.
22
21
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 )
33
23
ioutil .WriteFile (path , buf .Bytes (), os .ModePerm )
34
24
}
35
25
36
26
// Show displays the figure in your browser.
37
27
// Use serve if you want a persistent view
38
28
func Show (fig * grob.Fig ) {
29
+ buf := figToBuffer (fig )
30
+ browser .OpenReader (buf )
31
+ }
32
+
33
+ func figToBuffer (fig * grob.Fig ) * bytes.Buffer {
39
34
figBytes , err := json .Marshal (fig )
40
35
if err != nil {
41
36
panic (err )
@@ -46,10 +41,11 @@ func Show(fig *grob.Fig) {
46
41
}
47
42
buf := & bytes.Buffer {}
48
43
tmpl .Execute (buf , string (figBytes ))
49
- browser . OpenReader ( buf )
44
+ return buf
50
45
}
51
46
52
47
// 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.
53
49
func Serve (fig * grob.Fig , opt ... Options ) {
54
50
opts := computeOptions (Options {
55
51
Addr : "localhost:8080" ,
@@ -60,23 +56,16 @@ func Serve(fig *grob.Fig, opt ...Options) {
60
56
Handler : mux ,
61
57
Addr : opts .Addr ,
62
58
}
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
- })
71
59
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 )
74
62
})
75
63
76
64
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" )
80
69
}
81
70
82
71
func computeOptions (def Options , opt ... Options ) Options {
0 commit comments