diff --git a/assignment2/webhook.go b/assignment2/webhook.go index f2f74bce4fe71b3cc1c94cf1c73a4e5da8ca01d8..2eb2298ffa23044f3ef5134cfa0896b5d8222e97 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)) + }