mi-v1/cmd/mi/posse.go

78 lines
1.3 KiB
Go

package main
import (
"context"
"encoding/json"
"fmt"
"net/http"
"strings"
"github.com/hashicorp/go-multierror"
"within.website/ln"
)
type Pusher func(context.Context, Post) error
type Post struct {
Title string `json:"title"`
URL string `json:"url"`
Body string `json:"body"`
Tags []string `json:"tags"`
}
func (p Post) Format() string {
var sb strings.Builder
if p.Title != "" {
fmt.Fprintf(&sb, "%s\n\n", p.Title)
}
if p.URL != "" {
fmt.Fprintf(&sb, "%s\n\n", p.URL)
}
if p.Body != "" {
fmt.Fprintf(&sb, "%s\n\n", p.Body)
}
for _, tg := range p.Tags {
tg = strings.ReplaceAll(tg, "-", "")
fmt.Fprintf(&sb, "#%s ", tg)
}
return strings.TrimSpace(sb.String())
}
func (p Post) F() ln.F {
return ln.F{
"post_title": p.Title,
"post_url": p.URL,
"post_tags": p.Tags,
"post_body": p.Body,
}
}
func (mi *Mi) Push(ctx context.Context, p Post) error {
ln.Log(ctx, p)
var result error
for _, per := range mi.pushers {
if err := per(ctx, p); err != nil {
result = multierror.Append(result, err)
}
}
return result
}
func (mi *Mi) PostPOSSE(w http.ResponseWriter, r *http.Request) {
var data Post
err := json.NewDecoder(r.Body).Decode(&data)
if err != nil {
http.Error(w, "bad data", http.StatusBadRequest)
ln.Error(r.Context(), err)
return
}
mi.Push(r.Context(), data)
}