meme: use httpin

This commit is contained in:
Chris Sexton 2024-03-13 12:34:27 -04:00
parent 674e30125b
commit 35499ee213
1 changed files with 19 additions and 14 deletions

View File

@ -3,6 +3,7 @@ package meme
import ( import (
"encoding/json" "encoding/json"
"fmt" "fmt"
"github.com/ggicci/httpin"
"net/http" "net/http"
"net/url" "net/url"
"sort" "sort"
@ -17,8 +18,10 @@ func (p *MemePlugin) registerWeb(c bot.Connector) {
r := chi.NewRouter() r := chi.NewRouter()
r.HandleFunc("/slash", p.slashMeme(c)) r.HandleFunc("/slash", p.slashMeme(c))
r.Get("/img", p.img) r.Get("/img", p.img)
r.Put("/save/{name}", p.saveMeme) r.With(httpin.NewInput(SaveReq{})).
r.Post("/add", p.saveMeme) Put("/save/{name}", p.saveMeme)
r.With(httpin.NewInput(SaveReq{})).
Post("/add", p.saveMeme)
r.Delete("/rm/{name}", p.rmMeme) r.Delete("/rm/{name}", p.rmMeme)
r.Get("/edit/{name}", p.editMeme) r.Get("/edit/{name}", p.editMeme)
r.Get("/", p.webRoot) r.Get("/", p.webRoot)
@ -85,31 +88,33 @@ func (p *MemePlugin) rmMeme(w http.ResponseWriter, r *http.Request) {
mkCheckError(w)(err) mkCheckError(w)(err)
} }
type SaveReq struct {
Name string `in:"path=name"`
Config string `in:"form=config"`
URL string `in:"form=url"`
}
func (p *MemePlugin) saveMeme(w http.ResponseWriter, r *http.Request) { func (p *MemePlugin) saveMeme(w http.ResponseWriter, r *http.Request) {
name := chi.URLParam(r, "name") input := r.Context().Value(httpin.Input).(*SaveReq)
if name == "" {
name = r.FormValue("name")
}
checkError := mkCheckError(w) checkError := mkCheckError(w)
formats := p.c.GetMap("meme.memes", defaultFormats) formats := p.c.GetMap("meme.memes", defaultFormats)
formats[name] = r.FormValue("url") formats[input.Name] = input.URL
err := p.c.SetMap("meme.memes", formats) err := p.c.SetMap("meme.memes", formats)
checkError(err) checkError(err)
config := r.FormValue("config") if input.Config == "" {
if config == "" { input.Config = p.defaultFormatConfigJSON()
config = p.defaultFormatConfigJSON()
} }
configs := p.c.GetMap("meme.memeconfigs", map[string]string{}) configs := p.c.GetMap("meme.memeconfigs", map[string]string{})
configs[name] = config configs[input.Name] = input.Config
err = p.c.SetMap("meme.memeconfigs", configs) err = p.c.SetMap("meme.memeconfigs", configs)
checkError(err) checkError(err)
meme := webResp{ meme := webResp{
Name: name, Name: input.Name,
URL: formats[name], URL: formats[input.Name],
Config: configs[name], Config: configs[input.Name],
} }
p.Show(meme).Render(r.Context(), w) p.Show(meme).Render(r.Context(), w)