Skip to content

Commit

Permalink
Merge pull request #3 from go-zoox/feat/context-support-sse
Browse files Browse the repository at this point in the history
feat(context): support sse
  • Loading branch information
whatwewant committed Jun 7, 2023
2 parents 1f7b62e + 935ea99 commit 048773e
Show file tree
Hide file tree
Showing 2 changed files with 65 additions and 0 deletions.
54 changes: 54 additions & 0 deletions components/context/see/body.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
package sse

import (
"fmt"
"net/http"
"time"
)

// SSE ...
type SSE interface {
Retry(delat time.Duration)
Event(name, data string)
Comment(comment string)
}

// sse ...
type sse struct {
id int
writer http.ResponseWriter
flusher http.Flusher
}

func New(rw http.ResponseWriter) SSE {
rw.WriteHeader(200)
rw.Header().Set("Content-Type", "text/event-stream")
rw.Header().Set("Cache-Control", "no-cache")
rw.Header().Set("Connection", "keep-alive")
rw.Header().Set("Access-Control-Allow-Origin", "*")

return &sse{
writer: rw,
flusher: rw.(http.Flusher),
}
}

func (s *sse) Retry(delay time.Duration) {
s.writer.Write([]byte(fmt.Sprintf("retry: %d\n", delay/time.Millisecond)))
s.flusher.Flush()
}

func (s *sse) Event(name string, data string) {
s.id++

s.writer.Write([]byte("event: " + name + "\n"))
s.writer.Write([]byte(fmt.Sprintf("id: %d\n", s.id)))
s.writer.Write([]byte("data: " + data + "\n\n"))

s.flusher.Flush()
}

func (s *sse) Comment(comment string) {
s.writer.Write([]byte(": " + comment + "\n"))
s.flusher.Flush()
}
11 changes: 11 additions & 0 deletions context.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ import (
"github.com/go-zoox/zoox/components/context/form"
"github.com/go-zoox/zoox/components/context/param"
"github.com/go-zoox/zoox/components/context/query"
sse "github.com/go-zoox/zoox/components/context/see"
"github.com/go-zoox/zoox/components/context/state"
"github.com/go-zoox/zoox/components/context/user"
"github.com/go-zoox/zoox/utils"
Expand Down Expand Up @@ -56,6 +57,7 @@ type Context struct {
body body.Body

// response
sse sse.SSE

//
cookie cookie.Cookie
Expand Down Expand Up @@ -202,6 +204,15 @@ func (ctx *Context) AddHeader(key string, value string) {
ctx.Writer.Header().Add(key, value)
}

// SSE sets the response header for server-sent events.
func (ctx *Context) SSE() sse.SSE {
if ctx.body == nil {
ctx.sse = sse.New(ctx.Writer)
}

return ctx.sse
}

// BasicAuth returns the user/password pair for Basic Authentication.
func (ctx *Context) BasicAuth() (username string, password string, ok bool) {
return ctx.Request.BasicAuth()
Expand Down

0 comments on commit 048773e

Please sign in to comment.