{"id":1832,"date":"2015-05-16T10:29:18","date_gmt":"2015-05-16T09:29:18","guid":{"rendered":"http:\/\/denbeke.be\/blog\/?p=1832"},"modified":"2015-05-16T10:29:42","modified_gmt":"2015-05-16T09:29:42","slug":"simple-liveblog-to-demonstrate-websockets-in-go","status":"publish","type":"post","link":"https:\/\/denbeke.be\/blog\/programming\/simple-liveblog-to-demonstrate-websockets-in-go\/","title":{"rendered":"Simple Liveblog to demonstrate WebSockets in Go"},"content":{"rendered":"<p>Yesterday I had some time left and thought it was the perfect moment to write a very simple live blog to learn more about WebSockets (in Go).<\/p>\n<h3>Go<\/h3>\n<p>WebSockets are actually very easy in Go, they work just like the http handler. The required websocket package is not installed by default, but you can easily install the (by Go maintained) package:\u00a0<code>go get code.google.com\/p\/go.net\/websocket<\/code>.<\/p>\n<p>Time to create a\u00a0websocket handler:<\/p>\n<pre><code class=\"golang\">func main() {\r\n    http.Handle(\"\/\", websocket.Handler(HandleSocket))\r\n\r\n    if err := http.ListenAndServe(\":1234\", nil); err != nil {\r\n        log.Fatal(\"ListenAndServe:\", err)\r\n    }\r\n}<\/code><\/pre>\n<p>In the above snippet, <code>HandleSocket<\/code> is the name of your own defined handler function. In this easy example I created a handler function that will just send all received message on a socket back:<\/p>\n<pre><code class=\"golang\">func HandleSocket(ws *websocket.Conn) {\r\n\r\n    \/\/ Wait for incoming websocket messages\r\n    for {\r\n        var reply string\r\n\r\n        if err := websocket.Message.Receive(ws, &amp;reply); err != nil {\r\n            log.Println(\"Can't receive from socket:\", err)\r\n            break\r\n        }\r\n\r\n        log.Println(\"Received back from client: \" + reply)\r\n\r\n        msg := \"Received:  \" + reply\r\n        log.Println(\"Sending to client: \" + msg)\r\n\r\n        if err := websocket.Message.Send(ws, msg); err != nil {\r\n            log.Println(\"Can't send to socket:\", err)\r\n            break\r\n        }\r\n    }\r\n}<\/code><\/pre>\n<p>Of course I enhanced this Go code to create an actual liveblog demo.<\/p>\n<h3>Javascript<\/h3>\n<p>Now we have our websocket, we must actually do something with it in Javascript. The most simple implementation will prepend any new message to an html list with id <code>messages<\/code>:<\/p>\n<pre><code class=\"javascript\">var sock = null;\r\nvar wsuri = \"ws:\/\/localhost:1234\";\r\n\r\nwindow.onload = function() {\r\n\r\n    sock = new WebSocket(wsuri);\r\n\r\n    sock.onopen = function() {\r\n        console.log(\"connected to \" + wsuri);\r\n    }\r\n\r\n    sock.onclose = function(e) {\r\n        console.log(\"connection closed (\" + e.code + \")\");\r\n    }\r\n\r\n    sock.onmessage = function(e) {\r\n        $('&lt;li&gt;' + e.data '&lt;\/li&gt;').hide().prependTo('#messages').fadeIn(1000);\r\n    }\r\n};<\/code><\/pre>\n<p>We must also\u00a0be able to send messages\u00a0from an admin panel:<\/p>\n<pre><code class=\"javascript\">function send() {\r\n    var msg = document.getElementById('new_message').value;\r\n    document.getElementById('new_message').value = '';\r\n    sock.send(msg);\r\n};<\/code><\/pre>\n<h3>Liveblog<\/h3>\n<p>I combined the above little pieces to create a simple liveblog. The blog has an admin page on which someone can add messages, which are then broadcasted to all the other sockets.<\/p>\n<p>&nbsp;<\/p>\n<figure id=\"attachment_1833\" aria-describedby=\"caption-attachment-1833\" style=\"width: 417px\" class=\"wp-caption aligncenter\"><a href=\"http:\/\/denbeke.be\/blog\/uncategorized\/simple-liveblog-to-demonstrate-websockets-in-go\/attachment\/schermafbeelding-2015-05-16-om-10-55-08\/\" rel=\"attachment wp-att-1833\"><img loading=\"lazy\" class=\"size-full wp-image-1833\" src=\"http:\/\/denbeke.be\/blog\/wp-content\/uploads\/2015\/05\/Schermafbeelding-2015-05-16-om-10.55.08.png\" alt=\"Simple admin page\" width=\"417\" height=\"630\" srcset=\"https:\/\/denbeke.be\/blog\/wp-content\/uploads\/2015\/05\/Schermafbeelding-2015-05-16-om-10.55.08.png 417w, https:\/\/denbeke.be\/blog\/wp-content\/uploads\/2015\/05\/Schermafbeelding-2015-05-16-om-10.55.08-198x300.png 198w\" sizes=\"(max-width: 417px) 100vw, 417px\" \/><\/a><figcaption id=\"caption-attachment-1833\" class=\"wp-caption-text\">Simple admin page<\/figcaption><\/figure>\n<p>The source code of the demo is available on Github:\u00a0<a title=\"DenBeke\/Liveblog\" href=\"https:\/\/github.com\/DenBeke\/Liveblog\" target=\"_blank\">github.com\/DenBeke\/Liveblog<\/a><\/p>\n","protected":false},"excerpt":{"rendered":"<p>Yesterday I had some time left and thought it was the perfect moment to write a very simple live blog to learn more about WebSockets (in Go). Go WebSockets are actually very easy in Go, they work just like the http handler. The required websocket package is not installed by default, but you can easily [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":[],"categories":[235],"tags":[232,136,256],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v15.6.2 - https:\/\/yoast.com\/wordpress\/plugins\/seo\/ -->\n<title>Simple Liveblog to demonstrate WebSockets in Go &ndash; DenBeke<\/title>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/denbeke.be\/blog\/programming\/simple-liveblog-to-demonstrate-websockets-in-go\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"Simple Liveblog to demonstrate WebSockets in Go &ndash; DenBeke\" \/>\n<meta property=\"og:description\" content=\"Yesterday I had some time left and thought it was the perfect moment to write a very simple live blog to learn more about WebSockets (in Go). Go WebSockets are actually very easy in Go, they work just like the http handler. The required websocket package is not installed by default, but you can easily [&hellip;]\" \/>\n<meta property=\"og:url\" content=\"https:\/\/denbeke.be\/blog\/programming\/simple-liveblog-to-demonstrate-websockets-in-go\/\" \/>\n<meta property=\"og:site_name\" content=\"DenBeke\" \/>\n<meta property=\"article:published_time\" content=\"2015-05-16T09:29:18+00:00\" \/>\n<meta property=\"article:modified_time\" content=\"2015-05-16T09:29:42+00:00\" \/>\n<meta property=\"og:image\" content=\"http:\/\/denbeke.be\/blog\/wp-content\/uploads\/2015\/05\/Schermafbeelding-2015-05-16-om-10.55.08.png\" \/>\n<meta name=\"twitter:card\" content=\"summary\" \/>\n<meta name=\"twitter:creator\" content=\"@MthsBk\" \/>\n<meta name=\"twitter:site\" content=\"@MthsBk\" \/>\n<meta name=\"twitter:label1\" content=\"Est. reading time\">\n\t<meta name=\"twitter:data1\" content=\"2 minutes\">\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\"@context\":\"https:\/\/schema.org\",\"@graph\":[{\"@type\":\"WebSite\",\"@id\":\"https:\/\/denbeke.be\/blog\/#website\",\"url\":\"https:\/\/denbeke.be\/blog\/\",\"name\":\"DenBeke\",\"description\":\"Mathias Beke\",\"potentialAction\":[{\"@type\":\"SearchAction\",\"target\":\"https:\/\/denbeke.be\/blog\/?s={search_term_string}\",\"query-input\":\"required name=search_term_string\"}],\"inLanguage\":\"en-US\"},{\"@type\":\"ImageObject\",\"@id\":\"https:\/\/denbeke.be\/blog\/programming\/simple-liveblog-to-demonstrate-websockets-in-go\/#primaryimage\",\"inLanguage\":\"en-US\",\"url\":\"http:\/\/denbeke.be\/blog\/wp-content\/uploads\/2015\/05\/Schermafbeelding-2015-05-16-om-10.55.08.png\"},{\"@type\":\"WebPage\",\"@id\":\"https:\/\/denbeke.be\/blog\/programming\/simple-liveblog-to-demonstrate-websockets-in-go\/#webpage\",\"url\":\"https:\/\/denbeke.be\/blog\/programming\/simple-liveblog-to-demonstrate-websockets-in-go\/\",\"name\":\"Simple Liveblog to demonstrate WebSockets in Go &ndash; DenBeke\",\"isPartOf\":{\"@id\":\"https:\/\/denbeke.be\/blog\/#website\"},\"primaryImageOfPage\":{\"@id\":\"https:\/\/denbeke.be\/blog\/programming\/simple-liveblog-to-demonstrate-websockets-in-go\/#primaryimage\"},\"datePublished\":\"2015-05-16T09:29:18+00:00\",\"dateModified\":\"2015-05-16T09:29:42+00:00\",\"author\":{\"@id\":\"https:\/\/denbeke.be\/blog\/#\/schema\/person\/386878f712fe3fe22227216f087772dc\"},\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\/\/denbeke.be\/blog\/programming\/simple-liveblog-to-demonstrate-websockets-in-go\/\"]}]},{\"@type\":\"Person\",\"@id\":\"https:\/\/denbeke.be\/blog\/#\/schema\/person\/386878f712fe3fe22227216f087772dc\",\"name\":\"Mathias Beke\",\"image\":{\"@type\":\"ImageObject\",\"@id\":\"https:\/\/denbeke.be\/blog\/#personlogo\",\"inLanguage\":\"en-US\",\"url\":\"https:\/\/secure.gravatar.com\/avatar\/015ba35e6ce4f5859e3888ca99807575?s=96&d=mm&r=g\",\"caption\":\"Mathias Beke\"}}]}<\/script>\n<!-- \/ Yoast SEO plugin. -->","_links":{"self":[{"href":"https:\/\/denbeke.be\/blog\/wp-json\/wp\/v2\/posts\/1832"}],"collection":[{"href":"https:\/\/denbeke.be\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/denbeke.be\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/denbeke.be\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/denbeke.be\/blog\/wp-json\/wp\/v2\/comments?post=1832"}],"version-history":[{"count":7,"href":"https:\/\/denbeke.be\/blog\/wp-json\/wp\/v2\/posts\/1832\/revisions"}],"predecessor-version":[{"id":1840,"href":"https:\/\/denbeke.be\/blog\/wp-json\/wp\/v2\/posts\/1832\/revisions\/1840"}],"wp:attachment":[{"href":"https:\/\/denbeke.be\/blog\/wp-json\/wp\/v2\/media?parent=1832"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/denbeke.be\/blog\/wp-json\/wp\/v2\/categories?post=1832"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/denbeke.be\/blog\/wp-json\/wp\/v2\/tags?post=1832"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}