A changes notification package for database and notifications over websocket

Darko Luketic 5e1eaa73ed added Notifier.Close() 4 months ago
LICENSE 53e0f4374d initial 4 months ago
README.md 3fd7ba0682 update README.md 4 months ago
notifier.go 5e1eaa73ed added Notifier.Close() 4 months ago

README.md

What

Database changes notification library.

Example

/main.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"})
}

/index.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>

then run

go run main.go
curl localhost:5000/acme/ins
.
├── index.html
└── main.go

0 directories, 2 files