Try   HackMD

我想知道你的一切 - Webhook

client 與 server 之間互動最基本的形式,由 client 送出 request,server 回傳 response。

Image Not Showing Possible Reasons
  • The image file may be corrupted
  • The server hosting the image is unavailable
  • The image path is incorrect
  • The image format is not supported
Learn More →

這樣的使用方式在大部分的場景下都沒有特別的問題,但如果 client 想要持續地知道 server 發生的事件,就得要不間斷地一直送出 request,否則資訊就會出現不同步。

Image Not Showing Possible Reasons
  • The image file may be corrupted
  • The server hosting the image is unavailable
  • The image path is incorrect
  • The image format is not supported
Learn More →

(client 不送出 request,server 也就不會告訴 client 有沒有發生新的事件)

但如果每一個 client 都不眠不休地送出 request 只是為了知道前一秒 server 是不是有更新資料,這樣不止 client 很累,server 也需要無時無刻接受大量的 request,壓力非常的大,並且在大多數的時間,其實都沒有什麼更新的資料可以提供給 client。

現實生活

而類似的場景,在生活中畢畢皆是,假設今天我是一個軟體業的人力顧問(獵頭),以下就是我的日常。

(第一通)
我:嗨~請問是陳先生嗎?
陳:是的!
我:不知道你最近有沒有在考慮新的機會?
陳:(掛電話

(第二通)
我:嗨~請問是林小姐嗎?
林:我是,你有什麼事情嗎?
我:不知道你最近有沒有在考慮新的機會?
林:是有在看工作機會啦
我:那我手上有一份外商的前端工程師職缺,有興趣了解嗎?
林:我不喜歡外商誒,先不要

然後我的一天在幾乎是這樣的模式下過去了,非常的浪費生命,能不能你們自己下定決心看好想要的工作機會再聯絡我,那不是更好嗎!或者是等離職的時候知會我一下,這樣也可以在第一時間推薦你們相關的職缺。

能不能我提供電話或是名片給你們,等離職或是有想要了解的機會再主動打給我!

角色反轉

可以是 server 有更新資料,或者是有新事件發生的時候再來通知 client 嗎?

可以的!所以我們需要的就是 webhook ,而 webhook 只是把上圖中的角色顛倒,由 server 發送 request,client 回傳 response。

普遍的做法都是,先由 server 端定義好事件發生的時候會丟出何種規格的 request,然後再由 client 提供自己要接收這個 request 的 API endpoint。

試著做一次

今天我們是一個新聞網站,任何對站上新聞有興趣的使用者,都可以透過向我們註冊 webhook 的方式,來知道站上發布新聞的事件,以下是相關的資訊。

透過 POST https://timm.com/news/subscribe request body 如下

{
    "webhook_url":"https://super.com/notify"
}

每當有新聞發布的時候,我們就會根據目前全部有登錄的 webhook_url 以下面的方式發出通知。

POST https://super.com/notify

{
    "id":"9527",
    "title":"今晚打老虎",
    "created_time":"2022-11-25"
}

透過上述流程上的變動,成就一個雙贏的局面。
server:不用再一天到晚被 client request 查詢有沒有新的資料出現。
client:不用再一天到晚去問 server 東西更新了沒,躺著等就好。

實際使用

GitHub Webhook

透過將自己的 webhook url 放上 Github 這樣之後發生的一些事件就會透過這組 webhook url 傳遞出去。
e.g.

  1. main branch commit pushed
  2. pull request closed

Discord Webhook

透過將 Discord Server 產生的 webhook 放到其他地方,來接收事件,我們就可以利用 Discord Server 建立一組 webhook,來接收 GitHub 上面發生的事件,顯示在文字頻道上面

建立 webhook url

Image Not Showing Possible Reasons
  • The image file may be corrupted
  • The server hosting the image is unavailable
  • The image path is incorrect
  • The image format is not supported
Learn More →

收到事件後顯示訊息

Image Not Showing Possible Reasons
  • The image file may be corrupted
  • The server hosting the image is unavailable
  • The image path is incorrect
  • The image format is not supported
Learn More →