Skip to content

Commit

Permalink
feat: Add an API endpoint for retrieving the current view. (#822)
Browse files Browse the repository at this point in the history
This commit adds an endpoint so that the current image can be fetched
via curl or otherwise.
  • Loading branch information
betterengineering authored Jun 26, 2023
1 parent 7f88900 commit 5f3f6be
Showing 1 changed file with 32 additions and 0 deletions.
32 changes: 32 additions & 0 deletions server/browser/browser.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ package browser

import (
_ "embed"
"encoding/base64"
"encoding/json"
"fmt"
"html/template"
Expand Down Expand Up @@ -90,6 +91,7 @@ func NewBrowser(addr string, title string, watch bool, updateChan chan loader.Up

// API endpoints to support the React frontend.
r.HandleFunc("/api/v1/preview", b.previewHandler)
r.HandleFunc("/api/v1/preview.webp", b.imageHandler)
r.HandleFunc("/api/v1/push", b.pushHandler)
r.HandleFunc("/api/v1/schema", b.schemaHandler).Methods("GET")
r.HandleFunc("/api/v1/handlers/{handler}", b.schemaHandlerHandler).Methods("POST")
Expand Down Expand Up @@ -155,6 +157,36 @@ func (b *Browser) schemaHandlerHandler(w http.ResponseWriter, r *http.Request) {
w.Write([]byte(data))
}

func (b *Browser) imageHandler(w http.ResponseWriter, r *http.Request) {
err := r.ParseForm()
if err != nil {
w.WriteHeader(500)
http.Error(w, "bad form data", http.StatusBadRequest)
return
}

config := make(map[string]string)
for k, val := range r.Form {
config[k] = val[0]
}

webp, err := b.loader.LoadApplet(config)
if err != nil {
http.Error(w, "loading applet", http.StatusInternalServerError)
return
}

w.Header().Set("Content-Type", "image/webp")

data, err := base64.StdEncoding.DecodeString(webp)
if err != nil {
http.Error(w, "decoding webp", http.StatusInternalServerError)
return
}

w.Write(data)
}

func (b *Browser) previewHandler(w http.ResponseWriter, r *http.Request) {
// Parse the request form so we can use it as config values.
if err := r.ParseMultipartForm(100); err != nil {
Expand Down

0 comments on commit 5f3f6be

Please sign in to comment.