From fceecc86bbdbc11093c51930d7a30706a4af61ad Mon Sep 17 00:00:00 2001 From: Hans Kristian Hoel <hanskhoe@stud.ntnu.no> Date: Thu, 31 Oct 2019 10:36:25 +0100 Subject: [PATCH] crated func CallUrl for webhooks --- assignment2/webhook.go | 23 ++++++++++++++++++++++- 1 file changed, 22 insertions(+), 1 deletion(-) diff --git a/assignment2/webhook.go b/assignment2/webhook.go index f2f74bc..2eb2298 100644 --- a/assignment2/webhook.go +++ b/assignment2/webhook.go @@ -1,9 +1,12 @@ package assignment2 import ( + "bytes" "encoding/json" "fmt" + "io/ioutil" "net/http" + "strconv" ) var webhooks []WebhookRegistration //Webhook DB @@ -38,10 +41,28 @@ func WebhookHandeler(w http.ResponseWriter, r *http.Request) { func ServiceHandler(w http.ResponseWriter, r *http.Request) { switch r.Method { - case MethodPost: + case http.MethodPost: fmt.Println("Recive POST request") for _, v := range webhooks { go CallUrl(v.URL, "Resonse on registered event in webhook demo: "+v.Event) } + default: + http.Error(w, "Method is invalid "+r.Method, http.StatusBadRequest) + } +} +func CallUrl(url string, content string) { + fmt.Println("Attempting invocation of url " + url + "...") + res, err := http.Post(url, "string", bytes.NewReader([]byte(content))) + if err != nil { + fmt.Println("Error in HTTP request: " + err.Error()) } + + response, err := ioutil.ReadAll(res.Body) + if err != nil { + fmt.Println("Something is wrong with invocation response: " + err.Error()) + } + + fmt.Println("Webhook invoked. Received status code " + strconv.Itoa(res.StatusCode) + + " and body: " + string(response)) + } -- GitLab