SSE
parent
5c2b6d18ec
commit
630ecd351f
|
@ -8,71 +8,89 @@
|
||||||
<body>
|
<body>
|
||||||
<h1>ntfy.sh</h1>
|
<h1>ntfy.sh</h1>
|
||||||
|
|
||||||
Topics:
|
<p>
|
||||||
<ul id="topics">
|
ntfy.sh is a super simple pub-sub notification service. It allows you to send desktop and (soon) phone notifications
|
||||||
</ul>
|
via scripts, without signup or cost. It's entirely free and open source.
|
||||||
|
</p>
|
||||||
|
|
||||||
<input type="text" id="topic" size="64" autofocus />
|
<p>
|
||||||
<button id="topicButton">Add topic</button>
|
<b>Usage:</b> You can subscribe to a topic either in this web UI, or in your own app by subscribing to an SSE/EventSource
|
||||||
<button onclick="notifyMe('test'); return false">Notify me!</button>
|
or JSON feed. Once subscribed, you can publish messages via PUT or POST.
|
||||||
|
</p>
|
||||||
|
|
||||||
<div id="error"></div>
|
<div id="error"></div>
|
||||||
|
|
||||||
|
<form id="subscribeForm">
|
||||||
|
<input type="text" id="topicField" size="64" autofocus />
|
||||||
|
<input type="submit" id="subscribeButton" value="Subscribe topic" />
|
||||||
|
</form>
|
||||||
|
|
||||||
|
Topics:
|
||||||
|
<ul id="topicsList">
|
||||||
|
</ul>
|
||||||
|
|
||||||
<script type="text/javascript">
|
<script type="text/javascript">
|
||||||
window.onload = function() {
|
let topics = {};
|
||||||
let topics = {};
|
|
||||||
|
|
||||||
const topicField = document.getElementById("topic");
|
const topicField = document.getElementById("topicField");
|
||||||
const topicsList = document.getElementById("topics");
|
const topicsList = document.getElementById("topicsList");
|
||||||
const topicButton = document.getElementById("topicButton");
|
const subscribeButton = document.getElementById("subscribeButton");
|
||||||
const errorField = document.getElementById("error");
|
const subscribeForm = document.getElementById("subscribeForm");
|
||||||
|
const errorField = document.getElementById("error");
|
||||||
|
|
||||||
const subscribe = function (topic) {
|
const subscribe = function (topic) {
|
||||||
let conn = new WebSocket(`ws://${document.location.host}/${topic}/ws`);
|
if (Notification.permission !== "granted") {
|
||||||
conn.onclose = function (evt) {
|
Notification.requestPermission().then(function (permission) {
|
||||||
errorField.innerHTML = "Connection closed";
|
if (permission === "granted") {
|
||||||
};
|
subscribeInternal(topic);
|
||||||
conn.onmessage = function (evt) {
|
}
|
||||||
notify(evt.data)
|
});
|
||||||
};
|
} else {
|
||||||
topics[topic] = conn;
|
subscribeInternal(topic);
|
||||||
|
|
||||||
let topicEntry = document.createElement('li');
|
|
||||||
topicEntry.innerHTML = `${topic} <button onclick="unsubscribe('${topic}')">Unsubscribe</button>`;
|
|
||||||
topicsList.appendChild(topicEntry);
|
|
||||||
};
|
|
||||||
|
|
||||||
const notify = function (msg) {
|
|
||||||
if (!("Notification" in window)) {
|
|
||||||
alert("This browser does not support desktop notification");
|
|
||||||
} else if (Notification.permission === "granted") {
|
|
||||||
var notification = new Notification(msg);
|
|
||||||
} else if (Notification.permission !== "denied") {
|
|
||||||
Notification.requestPermission().then(function (permission) {
|
|
||||||
if (permission === "granted") {
|
|
||||||
var notification = new Notification(msg);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
topicButton.onclick = function () {
|
|
||||||
if (!topicField.value) {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
subscribe(topicField.value);
|
|
||||||
return false;
|
|
||||||
};
|
|
||||||
|
|
||||||
if (!window["Notification"]) {
|
|
||||||
errorField.innerHTML = "Your browser does not support desktop notifications";
|
|
||||||
topicField.disabled = true;
|
|
||||||
topicButton.disabled = true;
|
|
||||||
} else if (!window["Notification"]) {
|
|
||||||
errorField.innerHTML = "Your browser does not support WebSockets.";
|
|
||||||
topicField.disabled = true;
|
|
||||||
topicButton.disabled = true;
|
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const subscribeInternal = function (topic) {
|
||||||
|
let eventSource = new EventSource(`${topic}/sse`);
|
||||||
|
eventSource.onerror = function (e) {
|
||||||
|
console.log(e);
|
||||||
|
errorField.innerHTML = "Error " + e;
|
||||||
|
};
|
||||||
|
eventSource.onmessage = function (e) {
|
||||||
|
const event = JSON.parse(e.data);
|
||||||
|
new Notification(event.message);
|
||||||
|
};
|
||||||
|
topics[topic] = eventSource;
|
||||||
|
|
||||||
|
let topicEntry = document.createElement('li');
|
||||||
|
topicEntry.id = `topic-${topic}`;
|
||||||
|
topicEntry.innerHTML = `${topic} <button onclick="unsubscribe('${topic}')">Unsubscribe</button>`;
|
||||||
|
topicsList.appendChild(topicEntry);
|
||||||
|
};
|
||||||
|
|
||||||
|
const unsubscribe = function(topic) {
|
||||||
|
topics[topic].close();
|
||||||
|
document.getElementById(`topic-${topic}`).remove();
|
||||||
|
};
|
||||||
|
|
||||||
|
subscribeForm.onsubmit = function () {
|
||||||
|
alert("hi")
|
||||||
|
if (!topicField.value) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
subscribe(topicField.value);
|
||||||
|
return false;
|
||||||
|
};
|
||||||
|
|
||||||
|
if (!window["Notification"] || !window["EventSource"]) {
|
||||||
|
errorField.innerHTML = "Your browser is not compatible to use the web-based desktop notifications.";
|
||||||
|
topicField.disabled = true;
|
||||||
|
subscribeButton.disabled = true;
|
||||||
|
} else if (Notification.permission === "denied") {
|
||||||
|
errorField.innerHTML = "You have blocked desktop notifications for this website. Please unblock them and refresh to use the web-based desktop notifications.";
|
||||||
|
topicField.disabled = true;
|
||||||
|
subscribeButton.disabled = true;
|
||||||
|
}
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
</body>
|
</body>
|
||||||
|
|
|
@ -5,6 +5,7 @@ import (
|
||||||
_ "embed" // required for go:embed
|
_ "embed" // required for go:embed
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
"errors"
|
"errors"
|
||||||
|
"fmt"
|
||||||
"github.com/gorilla/websocket"
|
"github.com/gorilla/websocket"
|
||||||
"io"
|
"io"
|
||||||
"log"
|
"log"
|
||||||
|
@ -31,8 +32,9 @@ const (
|
||||||
|
|
||||||
var (
|
var (
|
||||||
topicRegex = regexp.MustCompile(`^/[^/]+$`)
|
topicRegex = regexp.MustCompile(`^/[^/]+$`)
|
||||||
wsRegex = regexp.MustCompile(`^/[^/]+/ws$`)
|
|
||||||
jsonRegex = regexp.MustCompile(`^/[^/]+/json$`)
|
jsonRegex = regexp.MustCompile(`^/[^/]+/json$`)
|
||||||
|
sseRegex = regexp.MustCompile(`^/[^/]+/sse$`)
|
||||||
|
wsRegex = regexp.MustCompile(`^/[^/]+/ws$`)
|
||||||
wsUpgrader = websocket.Upgrader{
|
wsUpgrader = websocket.Upgrader{
|
||||||
ReadBufferSize: messageLimit,
|
ReadBufferSize: messageLimit,
|
||||||
WriteBufferSize: messageLimit,
|
WriteBufferSize: messageLimit,
|
||||||
|
@ -82,7 +84,9 @@ func (s *Server) handleInternal(w http.ResponseWriter, r *http.Request) error {
|
||||||
} else if r.Method == http.MethodGet && wsRegex.MatchString(r.URL.Path) {
|
} else if r.Method == http.MethodGet && wsRegex.MatchString(r.URL.Path) {
|
||||||
return s.handleSubscribeWS(w, r)
|
return s.handleSubscribeWS(w, r)
|
||||||
} else if r.Method == http.MethodGet && jsonRegex.MatchString(r.URL.Path) {
|
} else if r.Method == http.MethodGet && jsonRegex.MatchString(r.URL.Path) {
|
||||||
return s.handleSubscribeHTTP(w, r)
|
return s.handleSubscribeJSON(w, r)
|
||||||
|
} else if r.Method == http.MethodGet && sseRegex.MatchString(r.URL.Path) {
|
||||||
|
return s.handleSubscribeSSE(w, r)
|
||||||
} else if (r.Method == http.MethodPut || r.Method == http.MethodPost) && topicRegex.MatchString(r.URL.Path) {
|
} else if (r.Method == http.MethodPut || r.Method == http.MethodPost) && topicRegex.MatchString(r.URL.Path) {
|
||||||
return s.handlePublishHTTP(w, r)
|
return s.handlePublishHTTP(w, r)
|
||||||
}
|
}
|
||||||
|
@ -112,7 +116,7 @@ func (s *Server) handlePublishHTTP(w http.ResponseWriter, r *http.Request) error
|
||||||
return t.Publish(msg)
|
return t.Publish(msg)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s *Server) handleSubscribeHTTP(w http.ResponseWriter, r *http.Request) error {
|
func (s *Server) handleSubscribeJSON(w http.ResponseWriter, r *http.Request) error {
|
||||||
t := s.createTopic(strings.TrimSuffix(r.URL.Path[1:], "/json")) // Hack
|
t := s.createTopic(strings.TrimSuffix(r.URL.Path[1:], "/json")) // Hack
|
||||||
subscriberID := t.Subscribe(func (msg *message) error {
|
subscriberID := t.Subscribe(func (msg *message) error {
|
||||||
if err := json.NewEncoder(w).Encode(&msg); err != nil {
|
if err := json.NewEncoder(w).Encode(&msg); err != nil {
|
||||||
|
@ -131,6 +135,32 @@ func (s *Server) handleSubscribeHTTP(w http.ResponseWriter, r *http.Request) err
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (s *Server) handleSubscribeSSE(w http.ResponseWriter, r *http.Request) error {
|
||||||
|
t := s.createTopic(strings.TrimSuffix(r.URL.Path[1:], "/sse")) // Hack
|
||||||
|
subscriberID := t.Subscribe(func (msg *message) error {
|
||||||
|
var buf bytes.Buffer
|
||||||
|
if err := json.NewEncoder(&buf).Encode(&msg); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
m := fmt.Sprintf("data: %s\n\n", buf.String())
|
||||||
|
if _, err := io.WriteString(w, m); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if fl, ok := w.(http.Flusher); ok {
|
||||||
|
fl.Flush()
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
})
|
||||||
|
defer t.Unsubscribe(subscriberID)
|
||||||
|
w.Header().Set("Content-Type", "text/event-stream")
|
||||||
|
w.WriteHeader(http.StatusOK)
|
||||||
|
select {
|
||||||
|
case <-t.ctx.Done():
|
||||||
|
case <-r.Context().Done():
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
func (s *Server) handleSubscribeWS(w http.ResponseWriter, r *http.Request) error {
|
func (s *Server) handleSubscribeWS(w http.ResponseWriter, r *http.Request) error {
|
||||||
conn, err := wsUpgrader.Upgrade(w, r, nil)
|
conn, err := wsUpgrader.Upgrade(w, r, nil)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
|
|
Loading…
Reference in New Issue