POST /v1/feeds plain html

main
Bel LaPointe 2025-04-28 22:15:58 -06:00
parent e4e5529887
commit 29cb008f38
2 changed files with 29 additions and 22 deletions

View File

@ -2,33 +2,38 @@ package handler
import (
"context"
"encoding/json"
"io"
"fmt"
"net/http"
"net/url"
"show-rss/src/feeds"
)
func (h Handler) feeds(w http.ResponseWriter, r *http.Request) error {
switch r.Method {
case http.MethodPost:
return h.feedsPost(r.Context(), r.Body)
if err := r.ParseForm(); err != nil {
return err
}
return h.feedsPost(r.Context(), r.Form)
default:
http.NotFound(w, r)
}
return nil
}
func (h Handler) feedsPost(ctx context.Context, r io.Reader) error {
var req struct {
URL string
Cron string
Pattern string
WebhookMethod string
WebhookURL string
WebhookBody string
}
if err := json.NewDecoder(r).Decode(&req); err != nil {
return err
func (h Handler) feedsPost(ctx context.Context, form url.Values) error {
var req feeds.Version
for k, v := range map[string]*string{
"url": &req.URL,
"cron": &req.Cron,
"pattern": &req.Pattern,
"webhookMethod": &req.WebhookMethod,
"webhookURL": &req.WebhookURL,
"webhookBody": &req.WebhookBody,
} {
if *v = form.Get(k); *v == "" {
return fmt.Errorf("no ?%s in %s", k, form.Encode())
}
}
_, err := feeds.Insert(ctx, req.URL, req.Cron, req.Pattern, req.WebhookMethod, req.WebhookURL, req.WebhookBody)

View File

@ -4,6 +4,7 @@ import (
"context"
"net/http"
"net/http/httptest"
"net/url"
"show-rss/src/cmd/server/handler"
"show-rss/src/db"
"show-rss/src/feeds"
@ -16,16 +17,17 @@ func TestFeeds(t *testing.T) {
h := handler.New(ctx)
t.Run("happy", func(t *testing.T) {
body := make(url.Values)
body.Set("url", "url")
body.Set("cron", "cron")
body.Set("pattern", "pattern")
body.Set("webhookMethod", "wmethod")
body.Set("webhookURL", "wurl")
body.Set("webhookBody", "wbody")
w := httptest.NewRecorder()
r := httptest.NewRequest(http.MethodPost, "/v1/feeds", strings.NewReader(`{
"url": "url",
"cron": "cron",
"pattern": "pattern",
"webhookMethod": "wmethod",
"webhookURL": "wurl",
"webhookBody": "wbody"
}`))
r := httptest.NewRequest(http.MethodPost, "/v1/feeds", strings.NewReader(body.Encode()))
r = r.WithContext(ctx)
r.Header.Set("Content-Type", "application/x-www-form-urlencoded")
h.ServeHTTP(w, r)
if w.Code != http.StatusOK {
t.Errorf("(%d) %s", w.Code, w.Body.Bytes())