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 , IE6 bruh" ,
http.StatusBadRequest)
return;
}
fmt.Fprintf(w,"data:%vnn","data is cumming open up kid");
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, tera sabun slow ha kia");
};
</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