Documentation ¶
Overview ¶
Example ¶
package main import ( "fmt" "log" "net/http" "time" "github.com/rndz/sse" ) func main() { s := &Server{} go runClient() log.Fatal("HTTP server error: ", http.ListenAndServe("localhost:3000", s)) } type Server struct { } func (s *Server) ServeHTTP(rw http.ResponseWriter, req *http.Request) { flusher, ok := rw.(http.Flusher) if !ok { http.Error(rw, "Streaming unsupported!", http.StatusInternalServerError) return } 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", "*") for { fmt.Fprintf(rw, "event: ts\ndata: %s\n\n", time.Now()) fmt.Fprintf(rw, "event: new\ndata: %s\n\n", time.Now()) flusher.Flush() time.Sleep(time.Second * 2) return } } func runClient() { time.Sleep(1 * time.Second) cfg := &sse.Config{ URL: "http://localhost:3000", } client, err := sse.New(cfg) if err != nil { log.Fatal(err) } client.AddListener("ts", func(e sse.Event) { fmt.Printf("%+v\n", e) }) client.AddListener("error", func(e sse.Event) { fmt.Println("error ", e) }) client.AddListener("open", func(e sse.Event) { fmt.Println("open ", e) }) client.Connect() }
Output:
Index ¶
Examples ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
type Client ¶
Client is main struct that handles connecting/streaming/etc...
func (*Client) AddListener ¶
AddListener adds a listener for a given event type. A listener is simple callback function that passes Event struct.
type Config ¶
Config is a struct used to define and override default parameters:
Client - *http.Client, if non provided, http.DefaultClient will be used. URL - URL of SSE stream to connect to. Must be provided. No default value. Retry - time.Duration of how long should SSE client wait before trying to reconnect after disconnection. Default is 2 seconds. LastEventID - set LastEventID for the first requests.
Click to show internal directories.
Click to hide internal directories.