From 2372fa8bb9b0a46388e839f856a496cf189efb72 Mon Sep 17 00:00:00 2001 From: Bel LaPointe <153096461+breel-render@users.noreply.github.com> Date: Thu, 11 Apr 2024 17:02:03 -0600 Subject: [PATCH] route /api/v1/events/slack differently when INITIALIZE_SLACK=true --- main.go | 34 +++++++++++++++++++++++++++------- 1 file changed, 27 insertions(+), 7 deletions(-) diff --git a/main.go b/main.go index b35ede7..d79eb5e 100644 --- a/main.go +++ b/main.go @@ -1,6 +1,7 @@ package main import ( + "bytes" "context" "encoding/json" "fmt" @@ -9,8 +10,6 @@ import ( "net" "net/http" "os/signal" - "path" - "strings" "syscall" ) @@ -58,19 +57,40 @@ func listenAndServe(ctx context.Context, cfg Config) chan error { func newHandler(cfg Config) http.HandlerFunc { mux := http.NewServeMux() - mux.Handle("POST /api/v1/events/{src}/{$}", http.HandlerFunc(newHandlerPostAPIV1Events(cfg))) + mux.Handle("POST /api/v1/events/slack", http.HandlerFunc(newHandlerPostAPIV1EventsSlack(cfg))) return func(w http.ResponseWriter, r *http.Request) { b, _ := io.ReadAll(r.Body) + r.Body = io.NopCloser(bytes.NewReader(b)) log.Printf("%s %s | %s", r.Method, r.URL, b) + mux.ServeHTTP(w, r) } } -func newHandlerPostAPIV1Events(cfg Config) http.HandlerFunc { +func newHandlerPostAPIV1EventsSlack(cfg Config) http.HandlerFunc { + if cfg.InitializeSlack { + return handlerPostAPIV1EventsSlackInitialize + } + return _newHandlerPostAPIV1EventsSlack(cfg) +} + +func handlerPostAPIV1EventsSlackInitialize(w http.ResponseWriter, r *http.Request) { + b, _ := io.ReadAll(r.Body) + var challenge struct { + Token string + Challenge string + Type string + } + if err := json.Unmarshal(b, &challenge); err != nil { + http.Error(w, err.Error(), http.StatusBadRequest) + } + + json.NewEncoder(w).Encode(map[string]any{"challenge": challenge.Challenge}) +} + +func _newHandlerPostAPIV1EventsSlack(cfg Config) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { - src := path.Base(strings.TrimSuffix(r.URL.Path, "/")) - log.Printf("%s %s | src=%s", r.Method, r.URL, src) - json.NewEncoder(w).Encode(map[string]any{"src": src}) + http.Error(w, "not impl", http.StatusNotImplemented) } }