Performs an HTTP POST to the url defined for the handler. If a filter function is defined, calls it to determine whether to POST. The payload for the POST is depends on the event type.
(ctx context.Context, event Event)
| 88 | // calls it to determine whether to POST. The payload for the POST is depends |
| 89 | // on the event type. |
| 90 | func (wh *Webhook) HandleEvent(ctx context.Context, event Event) bool { |
| 91 | |
| 92 | const contentType = "application/json" |
| 93 | var payload []byte |
| 94 | |
| 95 | // Different events post different content by default |
| 96 | switch event := event.(type) { |
| 97 | case *DocumentChangeEvent: |
| 98 | // skip event if this is for a non-winning rev and the winning rev only option is enabled |
| 99 | if !event.WinningRevChange && wh.options.DocumentChangedWinningRevOnly { |
| 100 | return false |
| 101 | } |
| 102 | payload = event.DocBytes |
| 103 | case *DBStateChangeEvent: |
| 104 | // for DBStateChangeEvent, post JSON document with the following format |
| 105 | //{ |
| 106 | // “admininterface":"127.0.0.1:4985", |
| 107 | // “dbname":"db", |
| 108 | // “localtime":"2015-10-07T11:20:29.138+01:00", |
| 109 | // "reason":"DB started from config”, |
| 110 | // “state”:"online" |
| 111 | //} |
| 112 | jsonOut, err := base.JSONMarshal(event.Doc) |
| 113 | if err != nil { |
| 114 | base.WarnfCtx(ctx, "Error marshalling doc for webhook post") |
| 115 | return false |
| 116 | } |
| 117 | payload = jsonOut |
| 118 | default: |
| 119 | base.WarnfCtx(ctx, "Webhook invoked for unsupported event type.") |
| 120 | return false |
| 121 | } |
| 122 | |
| 123 | if wh.filter != nil { |
| 124 | // If filter function is defined, use it to determine whether to post |
| 125 | success, err := wh.filter.CallValidateFunction(ctx, event) |
| 126 | if err != nil { |
| 127 | base.WarnfCtx(ctx, "Error calling webhook filter function: %v", err) |
| 128 | } |
| 129 | |
| 130 | // If filter returns false, cancel webhook post |
| 131 | if !success { |
| 132 | return false |
| 133 | } |
| 134 | } |
| 135 | |
| 136 | success := func() bool { |
| 137 | resp, err := wh.client.Post(wh.url, contentType, bytes.NewBuffer(payload)) |
| 138 | defer func() { |
| 139 | // Ensure we're closing the response, so it can be reused |
| 140 | if resp != nil && resp.Body != nil { |
| 141 | _, err := io.Copy(io.Discard, resp.Body) |
| 142 | if err != nil { |
| 143 | base.DebugfCtx(ctx, base.KeyEvents, "Error copying response body: %v", err) |
| 144 | } |
| 145 | err = resp.Body.Close() |
| 146 | if err != nil { |
| 147 | base.DebugfCtx(ctx, base.KeyEvents, "Error closing response body: %v", err) |