My server code in golang
package main
import (
"fmt"
"log"
"net/http"
"github.com/rs/cors"
)
func main() {
mux := http.NewServeMux();
mux.HandleFunc("/sse" , handleSse)
c := cors.New(cors.Options{
AllowedOrigins: []string{"*"},
AllowedMethods: []string{http.MethodGet, http.MethodPost,
http.MethodDelete , http.MethodPut},
AllowCredentials: true,
})
handler := c.Handler(mux)
log.Fatal(http.ListenAndServe(":6969" , handler))
}
func handleSse(w http.ResponseWriter , r * http.Request){
w.Header().Set("Content-type","text/event-stream")
w.Header().Set("Cache-Control","no-cache")
w.Header().Set("Connection","keep-alive")
f , ok := w.(http.Flusher);
if !ok{
http.Error( w , "SSE not supported" ,
http.StatusBadRequest)
return;
}
fmt.Fprintf(w,"data:%v\n\n","sample data");
f.Flush();
}
client side code
<!DOCTYPE html>
<html lang="en">
<head>
<title>SSE</title>
</head>
<body>
SSE running
<script>
const event = new EventSource("http://localhost:6969/sse");
event.onmessage = () =>{
console.log("this dude is slow");
};
</script>
</body>
</html>
The problem I have that in network tab new text stream or response comes after 5.4 sec later. I want server to send response every 2 second I have tried infinite for loop in server code which is shown in some tutorial and it doesn't works
EDIT : The for loop handler function
func handleSse(w http.ResponseWriter , r * http.Request){
w.Header().Set("Content-type","text/event-stream")
w.Header().Set("Cache-Control","no-cache")
w.Header().Set("Connection","keep-alive")
w.WriteHeader(http.StatusOK)
f , ok := w.(http.Flusher);
if !ok{
http.Error( w , "SSE not supported , IE6 bruh" ,
http.StatusBadRequest)
return;
}
for i := 0 ; i < 10 ; i++{
fmt.Fprintln(w,"retry : 1000"); //This line also doesnot help
fmt.Fprintf(w,"data :%v\n\n","Sorry");
f.Flush();
//time.Sleep(1 * time.Second) //This line increase delay to 25 secs
}
}
reconnection time
; you can prove this by addingfmt.Fprintln(w, "retry: 1000")
above the line that sendsdata
). With SSE you want to keep the connection open - see this answer for a good example.