Angular, EventSource, Go and wasted lifetime

If you have ever used EventSource and Angular and have read all the other blog posts and github issues and Stackoverflow posts and nothing worked, then you’ve probably come here and will happily leave knowing you solved your problem.

First of all I use cobra, I know, get to the point. As part of cobra I add the serve command, so I can go run main.go serve

This is the serve.go file

I set up the route, cors and run it

The server/handler/handler.go file

Here is the important part. I wasted the last 6 hours and previous to that 2 days on this issue.
If you’re serving this via nginx, you have to set this header X-Accel-Buffering = no.
If you don’t send this header responses will get buffered by nginx until the timeout it met then flushed to the client.
The above code has a ticker that ticks every second and sends a new “Server Sent Event”.

Why it didn’t work for me was, as you see above Event: "message". I had that set to “darko”.

The Angular service

eventSource.onmessage expects a message with the Event: "message" content. Since I had it set to “darko”,
the onmessage event never fired. If you for whatever reason need to send an event that is not a message type,
the eventSource.addEventListener is how you listen for that event.
As you might have seen in other blog posts or github issues, zonejs and EventSource aren’t the best of friends.
So you have to wrap it all in zone.run() so you can have real time updates, and not just when you unsubscribe from the Observable.

Finally, the component

and the component html

Finally, the nginx configuration for the development server. To serve it all.
Here I’m using es.dev.luketic on the local network.

3 Replies to “Angular, EventSource, Go and wasted lifetime”

Leave a Reply to dalu Cancel reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.