From 533fa86b7fc8c48c9471d9a205bba3f5dc1ba70e Mon Sep 17 00:00:00 2001 From: idanoo Date: Sun, 20 Nov 2022 17:44:58 +1300 Subject: [PATCH] Update to listen --- .env.example | 1 + go.mod | 2 ++ go.sum | 2 ++ main.go | 80 ++++++++++++++++++++++++++++++++++++++++++++++++++-- 4 files changed, 83 insertions(+), 2 deletions(-) create mode 100644 go.sum diff --git a/.env.example b/.env.example index c265e5b..8eb033c 100644 --- a/.env.example +++ b/.env.example @@ -1,3 +1,4 @@ MATRIX_WEBHOOK_URL= MATRIX_WEBHOOK_API_KEY= MATRIX_CHANNEL= +PORT= \ No newline at end of file diff --git a/go.mod b/go.mod index d3f908d..3f9678e 100644 --- a/go.mod +++ b/go.mod @@ -1,3 +1,5 @@ module tinker.nz/idanoo/go-mastodon-matrix-webhooks go 1.19 + +require github.com/joho/godotenv v1.4.0 // indirect diff --git a/go.sum b/go.sum new file mode 100644 index 0000000..8c9f290 --- /dev/null +++ b/go.sum @@ -0,0 +1,2 @@ +github.com/joho/godotenv v1.4.0 h1:3l4+N6zfMWnkbPEXKng2o2/MR5mSwTrBih4ZEkkz1lg= +github.com/joho/godotenv v1.4.0/go.mod h1:f4LDr5Voq0i2e/R5DDNOoa2zzDfwtkZa6DnEwAbqwq4= diff --git a/main.go b/main.go index 2f944f8..1212af8 100644 --- a/main.go +++ b/main.go @@ -1,7 +1,83 @@ package main -import "log" +import ( + "bytes" + "encoding/json" + "fmt" + "io/ioutil" + "log" + "net/http" + "os" + + "github.com/joho/godotenv" +) + +type IncomingMastoReq struct { + ID string `json:"id"` +} + +var MATRIX_WEBHOOK_URL string +var MATRIX_WEBHOOK_API_KEY string +var MATRIX_CHANNEL string +var PORT string + +func init() { + err := godotenv.Load() + if err != nil { + log.Fatal("Error loading .env file") + } + + MATRIX_WEBHOOK_URL = os.Getenv("MATRIX_WEBHOOK_URL") + if MATRIX_WEBHOOK_URL == "" { + log.Fatal("MATRIX_WEBHOOK_URL empty or invalid") + } + + MATRIX_WEBHOOK_API_KEY = os.Getenv("MATRIX_WEBHOOK_API_KEY") + if MATRIX_WEBHOOK_API_KEY == "" { + log.Fatal("MATRIX_WEBHOOK_API_KEY empty or invalid") + } + + MATRIX_CHANNEL = os.Getenv("MATRIX_CHANNEL") + if MATRIX_CHANNEL == "" { + log.Fatal("MATRIX_CHANNEL empty or invalid") + } + + PORT = os.Getenv("PORT") + if PORT == "" { + log.Fatal("PORT empty or invalid") + } +} func main() { - log.Printf("Test") + http.HandleFunc("/", handler) + if err := http.ListenAndServe(":"+PORT, nil); err != nil { + log.Fatal(err) + } +} + +func handler(w http.ResponseWriter, r *http.Request) { + var bodyBytes []byte + var err error + + if r.Body != nil { + bodyBytes, err = ioutil.ReadAll(r.Body) + if err != nil { + fmt.Printf("Body reading error: %v", err) + return + } + defer r.Body.Close() + } + + fmt.Printf("Headers: %+v\n", r.Header) + + if len(bodyBytes) > 0 { + var prettyJSON bytes.Buffer + if err = json.Indent(&prettyJSON, bodyBytes, "", "\t"); err != nil { + fmt.Printf("JSON parse error: %v", err) + return + } + fmt.Println(prettyJSON.String()) + } else { + fmt.Printf("Body: No Body Supplied\n") + } }