mi-v1/cmd/mi/posse.go

78 lines
1.3 KiB
Go
Raw Normal View History

2020-01-11 18:38:50 +00:00
package main
2020-01-11 20:18:59 +00:00
import (
"context"
2020-01-18 22:28:10 +00:00
"encoding/json"
2020-01-11 20:18:59 +00:00
"fmt"
2020-01-18 22:28:10 +00:00
"net/http"
2020-01-11 20:18:59 +00:00
"strings"
"github.com/hashicorp/go-multierror"
"within.website/ln"
)
type Pusher func(context.Context, Post) error
2020-01-11 18:38:50 +00:00
type Post struct {
2020-01-18 22:28:10 +00:00
Title string `json:"title"`
URL string `json:"url"`
Body string `json:"body"`
Tags []string `json:"tags"`
2020-01-11 18:38:50 +00:00
}
2020-01-11 20:18:59 +00:00
func (p Post) Format() string {
var sb strings.Builder
2020-01-18 22:28:10 +00:00
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)
}
2020-01-11 20:18:59 +00:00
for _, tg := range p.Tags {
2020-01-11 22:24:59 +00:00
tg = strings.ReplaceAll(tg, "-", "")
fmt.Fprintf(&sb, "#%s ", tg)
2020-01-11 20:18:59 +00:00
}
2020-01-18 22:28:10 +00:00
return strings.TrimSpace(sb.String())
2020-01-11 20:18:59 +00:00
}
func (p Post) F() ln.F {
return ln.F{
"post_title": p.Title,
"post_url": p.URL,
"post_tags": p.Tags,
2020-01-18 22:28:10 +00:00
"post_body": p.Body,
2020-01-11 20:18:59 +00:00
}
}
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
}
2020-01-18 22:28:10 +00:00
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)
}