Skip to content

Commit

Permalink
Encode static files to avoid problems with special characters
Browse files Browse the repository at this point in the history
Serve figures in server mode for the same reason. It is also a good reference example if people want to build on top
  • Loading branch information
MetalBlueberry committed Aug 21, 2024
1 parent b83a081 commit ba200ef
Show file tree
Hide file tree
Showing 2 changed files with 59 additions and 11 deletions.
2 changes: 1 addition & 1 deletion examples/bar.html
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
<body>
<div id="plot"></div>
<script>
data = JSON.parse('{"data":[{"type":"bar","base":null,"hoverinfo":null,"hovertemplate":null,"hovertext":null,"meta":null,"offset":null,"text":null,"textposition":null,"texttemplate":null,"width":null,"x":[1,2,3],"y":[1,2,3]}],"layout":{"meta":null,"title":{"text":"A Figure Specified By Go Struct"}}}')
data = JSON.parse(atob('eyJkYXRhIjpbeyJ0eXBlIjoiYmFyIiwiYmFzZSI6bnVsbCwiaG92ZXJpbmZvIjpudWxsLCJob3ZlcnRlbXBsYXRlIjpudWxsLCJob3ZlcnRleHQiOm51bGwsIm1ldGEiOm51bGwsIm9mZnNldCI6bnVsbCwidGV4dCI6bnVsbCwidGV4dHBvc2l0aW9uIjpudWxsLCJ0ZXh0dGVtcGxhdGUiOm51bGwsIndpZHRoIjpudWxsLCJ4IjpbMSwyLDNdLCJ5IjpbMSwyLDNdfV0sImxheW91dCI6eyJtZXRhIjpudWxsLCJ0aXRsZSI6eyJ0ZXh0IjoiQSBGaWd1cmUgJ1NwZWNpZmllZCcgQnkgR28gU3RydWN0In19fQ=='))
Plotly.newPlot('plot', data);
</script>
</body>
Expand Down
68 changes: 58 additions & 10 deletions pkg/offline/plot.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package offline

import (
"bytes"
"encoding/base64"
"encoding/json"
"log"
"net/http"
Expand Down Expand Up @@ -34,17 +35,18 @@ func figToBuffer(fig types.Fig) *bytes.Buffer {
if err != nil {
panic(err)
}
tmpl, err := template.New("plotly").Parse(baseHtml)
tmpl, err := template.New("plotly").Parse(singleFileHTML)
if err != nil {
panic(err)
}
buf := &bytes.Buffer{}
data := struct {
Version types.Version
Content string
Version types.Version
B64Content string
}{
Version: fig.Info(),
Content: string(figBytes),
// Encode to avoid problems with special characters
B64Content: base64.StdEncoding.EncodeToString(figBytes),
}

err = tmpl.Execute(buf, data)
Expand All @@ -66,12 +68,18 @@ func Serve(fig types.Fig, opt ...Options) {
Handler: mux,
Addr: opts.Addr,
}
mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
buf := figToBuffer(fig)
buf.WriteTo(w)

mux.HandleFunc("/content", func(w http.ResponseWriter, r *http.Request) {
err := json.NewEncoder(w).Encode(fig)
if err != nil {
log.Printf("Error rendering template, %s", err)
w.WriteHeader(http.StatusInternalServerError)
}
})

log.Print("Starting server")
mux.HandleFunc("/", webPage(fig, "/content"))

log.Printf("Starting server at %s", srv.Addr)
if err := srv.ListenAndServe(); err != nil {
log.Print(err)
}
Expand All @@ -88,15 +96,55 @@ func computeOptions(def Options, opt ...Options) Options {
return def
}

var baseHtml = `
var singleFileHTML = `
<head>
<script src="{{ .Version.Cdn }}"></script>
</head>
<body>
<div id="plot"></div>
<script>
data = JSON.parse('{{ .Content }}')
data = JSON.parse(atob('{{ .B64Content }}'))
Plotly.newPlot('plot', data);
</script>
</body>
`

type serverHTMLdata struct {
Version types.Version
ContentURL string
}

func webPage(fig types.Fig, contentURL string) func(w http.ResponseWriter, r *http.Request) {
return func(w http.ResponseWriter, r *http.Request) {
tmpl := template.Must(template.New("server").Parse(serverHTML))
data := serverHTMLdata{
Version: fig.Info(),
ContentURL: contentURL,
}
err := tmpl.Execute(w, data)
if err != nil {
log.Printf("Error rendering template, %s", err)
w.WriteHeader(http.StatusInternalServerError)
return
}
}
}

var serverHTML = `
<head>
<script src="{{ .Version.Cdn }}"></script>
</head>
<body>
<div id="plot"></div>
<script>
const url = '{{ .ContentURL }}'
fetch(url)
.then(response => response.json()) // Parse the JSON data from the response
.then(data => {
// Use the fetched data to create the Plotly plot
Plotly.newPlot('plot', data);
})
.catch(error => console.error('Error fetching data:', error));
</script>
</body>
`

0 comments on commit ba200ef

Please sign in to comment.