From 847cd83fd5b9b8a6675478b64e3838aea6214318 Mon Sep 17 00:00:00 2001 From: bel Date: Sat, 13 Apr 2024 09:26:02 -0600 Subject: [PATCH] extract into writeJSON --- main.go | 21 +++++++++++++++++---- 1 file changed, 17 insertions(+), 4 deletions(-) diff --git a/main.go b/main.go index 77340c0..ad8cb2b 100644 --- a/main.go +++ b/main.go @@ -3,6 +3,7 @@ package main import ( "bytes" "context" + "encoding/csv" "encoding/json" "errors" "fmt" @@ -97,7 +98,7 @@ func newHandlerGetAPIV1Messages(cfg Config) http.HandlerFunc { return } - json.NewEncoder(w).Encode(map[string]any{"messages": messages}) + writeJSON(w, map[string]any{"messages": messages}) } } @@ -119,7 +120,7 @@ func newHandlerGetAPIV1Threads(cfg Config) http.HandlerFunc { return } - json.NewEncoder(w).Encode(map[string]any{"threads": threads}) + writeJSON(w, map[string]any{"threads": threads}) } } @@ -137,7 +138,7 @@ func newHandlerGetAPIV1ThreadsThread(cfg Config) http.HandlerFunc { return } - json.NewEncoder(w).Encode(map[string]any{"thread": map[string]any{"messages": messages}}) + writeJSON(w, map[string]any{"thread": map[string]any{"messages": messages}}) } } @@ -168,7 +169,7 @@ func handlerPostAPIV1EventsSlackInitialize(w http.ResponseWriter, r *http.Reques return } - json.NewEncoder(w).Encode(map[string]any{"challenge": challenge.Challenge}) + writeJSON(w, map[string]any{"challenge": challenge.Challenge}) } func _newHandlerPostAPIV1EventsSlack(cfg Config) http.HandlerFunc { @@ -243,3 +244,15 @@ func parseSince(s string) (time.Time, error) { return time.Time{}, fmt.Errorf("failed to parse since=%q", s) } + +func writeJSON(w http.ResponseWriter, v interface{}) error { + return json.NewEncoder(w).Encode(v) +} + +func writeCSV(w http.ResponseWriter, fields []string, values [][]string) error { + enc := csv.NewWriter(w) + if err := enc.Write(fields); err != nil { + return err + } + return enc.WriteAll(values) +}