catbase/plugins/tappd/web.go

52 lines
1.1 KiB
Go
Raw Permalink Normal View History

2022-10-14 00:19:01 +00:00
package tappd
import (
"encoding/json"
2022-10-15 14:07:55 +00:00
"fmt"
2022-10-14 00:19:01 +00:00
"github.com/go-chi/chi/v5"
"github.com/rs/zerolog/log"
"net/http"
2022-10-15 14:07:55 +00:00
"os"
"path"
"strings"
2022-10-14 00:19:01 +00:00
)
func (p *Tappd) registerWeb() {
r := chi.NewRouter()
r.HandleFunc("/", p.serveImage)
2024-02-27 19:29:54 +00:00
p.b.GetWeb().RegisterWeb(r, "/tappd/{id}")
2022-10-14 00:19:01 +00:00
}
2022-10-15 14:07:55 +00:00
func (p *Tappd) getImg(id string) ([]byte, error) {
imgData, ok := p.imageMap[id]
if ok {
return imgData.Repr, nil
}
imgPath := p.c.Get("tappd.imagepath", "tappdimg")
entries, err := os.ReadDir(imgPath)
if err != nil {
log.Error().Err(err).Msgf("can't read image path")
return nil, err
}
for _, e := range entries {
if strings.HasPrefix(e.Name(), id) {
return os.ReadFile(path.Join(imgPath, e.Name()))
}
}
log.Error().Msgf("didn't find image")
return nil, fmt.Errorf("file not found")
}
2022-10-14 00:19:01 +00:00
func (p *Tappd) serveImage(w http.ResponseWriter, r *http.Request) {
id := chi.URLParam(r, "id")
2022-10-15 14:07:55 +00:00
data, err := p.getImg(id)
if err != nil {
log.Error().Err(err).Msgf("error getting image")
2022-10-14 00:19:01 +00:00
w.WriteHeader(404)
2022-10-15 14:07:55 +00:00
out, _ := json.Marshal(struct{ err string }{"could not find ID: " + err.Error()})
2022-10-14 00:19:01 +00:00
w.Write(out)
return
}
2022-10-15 14:07:55 +00:00
w.Write(data)
2022-10-14 00:19:01 +00:00
}