在以前的文章当中,基于websocket实现了一个简单的pub和sub模型,可是后面没有提供使用场景,回到文章的开头,一开始写这个是碰到一个须要作程序自动更新的问题,对方但愿我提供一个解决思路。有了以前的积累,如今能够尝试配合这个应用场景进行一轮实验。git
以github为例,GitHub运行指定事件发生时,通知经过HTTP的POST请求调用外部服务。,github的webhook在页面上有解释:github
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.
golang
那么先配置好github的webhook,回调的url填http://webhook.notr.tech/github?topic=common
web
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)
}
}
复制代码
接下来须要进行测试:微信
结果:websocket
broker收到github调用的消息app
subscriber获取到broker推送的消息socket
在开发测试阶段,broker和subscriber都在我本机运行的,,可是github设置的webhook url是http://webhook.notr.tech,明显是访问不了我本机的,为了在开发过程当中,为了更加专一于开发,我用了notr内网穿透这款工具,让github在调用webhook.notr.tech时,至关于github直接访问我本机http://127.0.0.1:80,在微信公众号/小程序,或者须要第三方回调的场景中,若是有须要能够尝试使用notr内网穿透ide