在之前的文章当中,基于websocket实现了一个简单的pub和sub模型,但是后面没有提供使用场景,回到文章的开头,一开始写这个是碰到一个需要做程序自动更新的问题,对方希望我提供一个解决思路。有了之前的积累,现在可以尝试配合这个应用场景进行一轮实验。
github webhook配置
以github为例,GitHub运行指定事件发生时,通知通过HTTP的POST请求调用外部服务。,github的webhook在页面上有解释:
Webhooks allow external services to be notified when certain events happen. When the specified events happen, we’ll send a POST request to each of the URLs you provide. Learn more in our Webhooks Guide.
那么先配置好github的webhook,回调的url填http://webhook.notr.tech/github?topic=common
broker添加接口
webhook配置完成了,接下来需要给broker添加一个针对webhook的处理接口
func (b *Broker) onGithub(w http.ResponseWriter, r *http.Request) {
r.ParseForm()
body, err := ioutil.ReadAll(r.Body)
if err != nil {
log.Println(err)
return
}
r.Body.Close()
topic := r.FormValue("topic")
msg := string(body)
log.Printf("recv publish topic: %s msg: %s\n", topic, string(body))
b.muEntry.RLock()
subscribers := b.entry[topic]
b.muEntry.RUnlock()
if subscribers == nil {
// drop message once no subscriber
// TODO: store msg
return
}
for _, s := range subscribers {
s.push(msg)
}
}
复制代码
测试
接下来需要进行测试:
- 启动broker
- 启动publisher
- 更新针对代码库进行修改或者合并等任何操作,我这里仅仅是add webhook
结果:
broker收到github调用的消息
subscriber获取到broker推送的消息
最后
在开发测试阶段,broker和subscriber都在我本机运行的,,但是github设置的webhook url是http://webhook.notr.tech,明显是访问不了我本机的,为了在开发过程中,为了更加专注于开发,我用了notr内网穿透这款工具,让github在调用webhook.notr.tech时,相当于github直接访问我本机http://127.0.0.1:80,在微信公众号/小程序,或者需要第三方回调的场景中,如果有需要可以尝试使用notr内网穿透