107 lines
1.8 KiB
Markdown
107 lines
1.8 KiB
Markdown
|
# What
|
||
|
|
||
|
Database changes notification library.
|
||
|
|
||
|
### Example
|
||
|
|
||
|
```go
|
||
|
package main
|
||
|
|
||
|
import (
|
||
|
"encoding/json"
|
||
|
"log"
|
||
|
"net/http"
|
||
|
|
||
|
"git.icod.de/dalu/notifier"
|
||
|
"github.com/gin-gonic/gin"
|
||
|
"gopkg.in/olahol/melody.v1"
|
||
|
)
|
||
|
|
||
|
func main() {
|
||
|
r := gin.Default()
|
||
|
m := melody.New()
|
||
|
n := notifier.NewNotifier(m)
|
||
|
h := NewHandler(n)
|
||
|
|
||
|
r.GET("/", h.Index)
|
||
|
r.GET("/ws", func(cx *gin.Context) {
|
||
|
m.HandleRequest(cx.Writer, cx.Request)
|
||
|
})
|
||
|
r.GET("/acme/ins", h.InsertDB)
|
||
|
|
||
|
go n.Listen(func(notification *notifier.Notification) {
|
||
|
b, e := json.Marshal(notification)
|
||
|
if e != nil {
|
||
|
log.Println(e.Error())
|
||
|
return
|
||
|
}
|
||
|
m.Broadcast(b)
|
||
|
})
|
||
|
r.Run(":5000")
|
||
|
}
|
||
|
|
||
|
type Handler struct {
|
||
|
notifier *notifier.Notifier
|
||
|
}
|
||
|
|
||
|
func NewHandler(n *notifier.Notifier) *Handler {
|
||
|
h := new(Handler)
|
||
|
h.notifier = n
|
||
|
return h
|
||
|
|
||
|
}
|
||
|
|
||
|
func (h *Handler) Index(cx *gin.Context) {
|
||
|
http.ServeFile(cx.Writer, cx.Request, "index.html")
|
||
|
}
|
||
|
|
||
|
func (h *Handler) InsertDB(cx *gin.Context) {
|
||
|
// Do database insert stuff
|
||
|
h.notifier.Notify("acme", "INSERT", []byte(`{"id": 1, "name": acme}`))
|
||
|
cx.JSON(201, map[string]interface{}{"status": "ok"})
|
||
|
}
|
||
|
```
|
||
|
|
||
|
```html
|
||
|
<html>
|
||
|
<head>
|
||
|
<title>Melody example: chatting</title>
|
||
|
</head>
|
||
|
|
||
|
<style>
|
||
|
#chat {
|
||
|
text-align: left;
|
||
|
background: #f1f1f1;
|
||
|
width: 500px;
|
||
|
min-height: 300px;
|
||
|
padding: 20px;
|
||
|
}
|
||
|
</style>
|
||
|
|
||
|
<body>
|
||
|
<div align="center">
|
||
|
<h3>Chat</h3>
|
||
|
<pre id="chat"></pre>
|
||
|
</div>
|
||
|
|
||
|
<script>
|
||
|
let url = "ws://localhost:5000/ws";
|
||
|
let ws = new WebSocket(url);
|
||
|
|
||
|
let chat = document.getElementById("chat");
|
||
|
|
||
|
let now = function () {
|
||
|
let iso = new Date().toISOString();
|
||
|
return iso.split("T")[1].split(".")[0];
|
||
|
};
|
||
|
|
||
|
ws.onmessage = function (msg) {
|
||
|
let line = now() + " " + msg.data + "\n";
|
||
|
chat.innerText += line;
|
||
|
};
|
||
|
</script>
|
||
|
</body>
|
||
|
</html>
|
||
|
```
|
||
|
|