diff --git a/docs/middleware/README.md b/docs/middleware/README.md index 6fa3872..3cbe442 100644 --- a/docs/middleware/README.md +++ b/docs/middleware/README.md @@ -25,6 +25,7 @@ To accelerate your development, the Flamego core team and the community have bui - [i18n](i18n.md) for providing internationalization and localization. - [captcha](captcha.md) for generating and validating captcha images. - [hcaptcha](hcaptcha.md) for providing [hCaptcha](https://www.hcaptcha.com/) verification. +- [sse](sse.md) for providing [Server-sent events](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events). ::: tip If you notice any middleware that is missing from the list, please don't hesitate to [send a pull request to this page](https://github.com/flamego/flamego.dev/edit/main/docs/middleware/README.md)! diff --git a/docs/middleware/sse.md b/docs/middleware/sse.md new file mode 100644 index 0000000..a406b82 --- /dev/null +++ b/docs/middleware/sse.md @@ -0,0 +1,81 @@ +--- +prev: + text: Middleware + link: ../middleware +--- + +# sse + +The sse middleware provides [Server-sent events](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events) integration for [Flame instances](../core-concepts.md#instances). + +You can read source code of this middleware on [GitHub](https://github.com/flamego/sse) and API documentation on [pkg.go.dev](https://pkg.go.dev/github.com/flamego/sse?tab=doc). + +## Installation + +The minimum requirement of Go is **1.18**. + +```:no-line-numbers +go get github.com/flamego/sse +``` + +## Usage examples + +:::: code-group +::: code-group-item main.go +```go:no-line-numbers{28} +package main + +import ( + "math/rand" + "net/http" + "time" + + "github.com/flamego/flamego" + "github.com/flamego/sse" + "github.com/flamego/template" +) + +var bulletins = []string{"Hello Flamego!", "Flamingo? No, Flamego!", "Most powerful routing syntax", "Slim core but limitless extensibility"} + +type bulletin struct { + Data string + PublishedAt time.Time +} + +func main() { + f := flamego.Classic() + f.Use(template.Templater(), flamego.Renderer()) + + f.Get("/", func(ctx flamego.Context, t template.Template) { + t.HTML(http.StatusOK, "index") + }) + + f.Get("/bulletin", sse.Bind(bulletin{}), func(msg chan<- *bulletin) { + for { + select { + case <-time.Tick(1 * time.Second): + msg <- &bulletin{ + Data: bulletins[rand.Intn(len(bulletins))], + PublishedAt: time.Now(), + } + } + } + }) + + f.Run() +} +``` +::: +::: code-group-item templates/index.html +```html:no-line-numbers + +

[]

+ +```