Ecosyste.ms: Awesome
An open API service indexing awesome lists of open source software.
https://github.com/ahnlabcloudmatelabs/go-fiber-sse
Server Send Event handler for fiber
https://github.com/ahnlabcloudmatelabs/go-fiber-sse
Last synced: 26 days ago
JSON representation
Server Send Event handler for fiber
- Host: GitHub
- URL: https://github.com/ahnlabcloudmatelabs/go-fiber-sse
- Owner: ahnlabcloudmatelabs
- License: mit
- Created: 2023-11-01T04:14:29.000Z (about 1 year ago)
- Default Branch: main
- Last Pushed: 2023-11-01T05:18:17.000Z (about 1 year ago)
- Last Synced: 2024-08-28T11:44:29.139Z (4 months ago)
- Language: Go
- Homepage:
- Size: 3.91 KB
- Stars: 0
- Watchers: 3
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
# go-fiber-sse
## Install
```sh
go get github.com/cloudmatelabs/go-fiber-sse
```## Usage
```go
package mainimport (
"bufio"
"fmt"
"time""github.com/gofiber/fiber/v2"
"github.com/cloudmatelabs/go-fiber-sse"
)func main() {
app := fiber.New()app.Get("/sse", func(c *fiber.Ctx) error {
i := 0return sse.Handler(c, sse.Options{
Tick: func(c *fiber.Ctx, w *bufio.Writer, close func()) {
i++if i > 3 {
close()
return
}fmt.Fprintf(w, "data: %d - %s\n\n", i, time.Now().Format(time.RFC3339Nano))
},
OnClosed: func(c *fiber.Ctx, err error) {
fmt.Println("Connection is closed:", err)
},
Sleep: time.Second,
})
})app.Get("/", func(c *fiber.Ctx) error {
c.Response().Header.Set("Content-Type", "text/html")
return c.SendString(`SSE Messages
if (typeof(EventSource) === 'undefined') {
document.getElementById("result").innerHTML = "Sorry, your browser does not support server-sent events...";
}const source = new EventSource("http://127.0.0.1:3000/sse");
source.addEventListener('open', (event) => {
document.getElementById("result").innerHTML += 'connected<br>';
})source.addEventListener('message', (event) => {
document.getElementById("result").innerHTML += event.data + "<br>";
})source.addEventListener('error', (event) => {
document.getElementById("result").innerHTML += 'connection lost<br>';source.close()
document.getElementById("result").innerHTML += 'closed<br>';
})`)
})app.Listen("localhost:3000")
}
```