github.com/blend/go-sdk@v1.20220411.3/webutil/webhook.go (about) 1 /* 2 3 Copyright (c) 2022 - Present. Blend Labs, Inc. All rights reserved 4 Use of this source code is governed by a MIT license that can be found in the LICENSE file. 5 6 */ 7 8 package webutil 9 10 import ( 11 "bytes" 12 "io" 13 "net/http" 14 "net/url" 15 16 "github.com/blend/go-sdk/ex" 17 ) 18 19 // Webhook is a configurable request. 20 type Webhook struct { 21 Method string `json:"method" yaml:"method"` 22 URL string `json:"url" yaml:"url"` 23 Headers map[string]string `json:"headers" yaml:"headers"` 24 Body string `json:"body" yaml:"body"` 25 } 26 27 // IsZero returns if the webhook is set. 28 func (wh Webhook) IsZero() bool { 29 return wh.URL == "" 30 } 31 32 // MethodOrDefault returns the method or a default. 33 func (wh Webhook) MethodOrDefault() string { 34 if wh.Method != "" { 35 return wh.Method 36 } 37 return "GET" 38 } 39 40 // Send sends the webhook. 41 func (wh Webhook) Send() (*http.Response, error) { 42 u, err := url.Parse(wh.URL) 43 if err != nil { 44 return nil, ex.New(err) 45 } 46 47 req := &http.Request{ 48 Method: wh.MethodOrDefault(), 49 URL: u, 50 } 51 headers := http.Header{} 52 for key, value := range wh.Headers { 53 headers.Add(key, value) 54 } 55 req.Header = headers 56 if wh.Body != "" { 57 req.Body = io.NopCloser(bytes.NewBufferString(wh.Body)) 58 req.ContentLength = int64(len(wh.Body)) 59 } 60 61 res, err := http.DefaultClient.Do(req) 62 if err != nil { 63 return nil, ex.New(err) 64 } 65 return res, nil 66 }