<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Elliot Forbes on Medium]]></title>
        <description><![CDATA[Stories by Elliot Forbes on Medium]]></description>
        <link>https://medium.com/@elliot_f?source=rss-eb71d34fbe09------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*LRJXPZHYCZ0_ThiKf-n-Ag.jpeg</url>
            <title>Stories by Elliot Forbes on Medium</title>
            <link>https://medium.com/@elliot_f?source=rss-eb71d34fbe09------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 16 Nov 2026 17:17:40 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@elliot_f/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Writing a Frontend Web Framework with WebAssembly And Go]]></title>
            <link>https://medium.com/hackernoon/writing-a-frontend-web-framework-with-webassembly-and-go-ff84cd1346fe?source=rss-eb71d34fbe09------2</link>
            <guid isPermaLink="false">https://medium.com/p/ff84cd1346fe</guid>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[webassembly]]></category>
            <dc:creator><![CDATA[Elliot Forbes]]></dc:creator>
            <pubDate>Sun, 04 Nov 2018 13:53:36 GMT</pubDate>
            <atom:updated>2019-04-27T10:50:20.574Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*LRkt5ifeRaCfstSc.jpg" /></figure><p><a href="https://hackernoon.com/tagged/javascript">JavaScript</a> Frontend frameworks have undoubtedly helped to push the boundaries of what was previously possible in the context of a browser. Ever more complex applications have come out built on top of the likes of React, Angular and VueJS to name but a few and there’s the well known joke about how a new frontend <a href="https://hackernoon.com/tagged/framework">framework</a> seems to come out every day.</p><p>However, this pace of development is exceptionally good news for developers around the world. With each new framework, we discover better ways of handling state, or rendering efficiently with things like the shadow DOM.</p><p>The latest trend however, seems to be moving towards writing these frameworks in languages other than JavaScript and compiling them into WebAssembly. We’re starting to see major improvements in the way that JavaScript and WebAssembly communicates thanks to the likes of <a href="https://twitter.com/linclark">Lin Clark</a> and we’ll undoubtedly see more major improvements as WebAssembly starts to become more prominent in our lives.</p><h3>Introduction</h3><p>So, in this tutorial, I thought it would be a good idea to build the base of an incredibly simple frontend framework written in Go that compiles into WebAssembly. At a minimum, this will include the following features:</p><ul><li>Function Registration</li><li>Components</li><li>Super Simplistic-Routing</li></ul><p>I’m warning you now though that these are going to be incredibly simple and nowhere near production ready. If this is article is somewhat popular, I’ll hopefully be taking it forward however, and trying to build something that meets the requirements of a semi-decent frontend framework.</p><blockquote><strong><em>Github:</em></strong><em> The full source code of this project can be found on my github account. If you fancy contributing to the project, feel free, I’d be happy to get any pull requests!</em></blockquote><p><a href="https://github.com/elliotforbes/oak">elliotforbes/oak</a></p><h3>Starting Point</h3><p>Right, let’s dive into our editor of choice and start coding! The first thing we’ll want to do is create a really simple index.html that will act as our entry point for our frontend framework:</p><pre>&lt;!doctype html&gt;<br>&lt;!--<br>Copyright 2018 The Go Authors. All rights reserved.<br>Use of this source code is governed by a BSD-style<br>license that can be found in the LICENSE file.<br>--&gt;<br>&lt;html&gt;<br><br>&lt;head&gt;<br>	&lt;meta charset=&quot;utf-8&quot;&gt;<br>	&lt;title&gt;Go wasm&lt;/title&gt;<br>	&lt;script src=&quot;./static/wasm_exec.js&quot;&gt;&lt;/script&gt;<br>	&lt;script src=&quot;./static/entrypoint.js&quot;&gt;&lt;/script&gt;<br>&lt;/head&gt;<br>&lt;body&gt;	<br><br>  &lt;div class=&quot;container&quot;&gt;<br>    &lt;h2&gt;Oak WebAssembly Framework&lt;/h2&gt;<br>  &lt;/div&gt;<br>&lt;/body&gt;<br><br>&lt;/html&gt;</pre><p>You’ll notice these have 2 js files being imported at the top, these allow us to execute our finished WebAssembly binary. The first of which is about 414 lines long so, in the interest of keeping this tutorial readable, I recommend you download it from here: <a href="https://github.com/elliotforbes/oak/blob/master/examples/blog/static/wasm_exec.js">https://github.com/elliotforbes/oak/blob/master/examples/blog/static/wasm_exec.js</a></p><p>The second is our entrypoint.js file. This will fetch and run the lib.wasm that we’ll be building very shortly.</p><pre>// static/entrypoint.js<br>const go = new Go();<br>WebAssembly.instantiateStreaming(fetch(&quot;lib.wasm&quot;), go.importObject).then((result) =&gt; {<br>    go.run(result.instance);<br>});</pre><p>Finally, now that we have that out of the way, we can start diving into some Go code! Create a new file called main.go which will contain the entry point to our Oak Web Framework!</p><pre>// main.go<br>package main<br><br>func main() {<br>	println(&quot;Oak Framework Initialized&quot;)<br>}</pre><p>This is as simple as it gets. We’ve created a really simple Go program that should just print out Oak Framework Initialized when we open up our web app. To verify that everything works, we need to compile this using the following command:</p><pre>$ <strong>GOOS=js GOARCH=wasm go build -o lib.wasm main.go</strong></pre><p>This should then build our Go code and output our lib.wasm file which we referenced in our entrypoint.js file.</p><p>Awesome, if everything worked, then we are ready to try it out in the browser! We can use a really simple file server like this:</p><pre>// server.go<br>package main<br><br>import (<br>	&quot;flag&quot;<br>	&quot;log&quot;<br>	&quot;net/http&quot;<br>)<br><br>var (<br>	listen = flag.String(&quot;listen&quot;, &quot;:8080&quot;, &quot;listen address&quot;)<br>	dir    = flag.String(&quot;dir&quot;, &quot;.&quot;, &quot;directory to serve&quot;)<br>)<br><br>func main() {<br>	flag.Parse()<br>	log.Printf(&quot;listening on %q...&quot;, *listen)<br>	log.Fatal(http.ListenAndServe(*listen, http.FileServer(http.Dir(*dir))))<br>}</pre><p>You can then serve your application by typing go run server.go and you should be able to access your app from <a href="http://localhost:8080.">http://localhost:8080.</a></p><h3>Function Registration</h3><p>Ok, so we’ve got a fairly basic print statement working, but in the grand scheme of things, I don’t quite think that qualifies it as a Web Framework just yet.</p><p>Let’s take a look at how we can build functions in Go and register these so we can call them in our index.html. We’ll create a new utility function which will take in both a string which will be the name of our function as well as the Go function it will map to.</p><p>Add the following to your existing main.go file:</p><pre>// main.go<br>import &quot;syscall/js&quot;<br><br>// RegisterFunction<br>func RegisterFunction(funcName string, myfunc func(i []js.Value)) {<br>	js.Global().Set(funcName, js.NewCallback(myfunc))<br>}</pre><p>So, this is where things start to become a bit more useful. Our framework now allows us to register functions so users of the framework can start creating their own functionality.</p><p>Other projects using our framework can start to register their own functions that can subsequently be used within their own frontend applications.</p><h3>Components</h3><p>So, I guess the next thing we need to consider adding to our framework is the concept of components. Basically, I want to be able to define a components/ directory within a project that uses this, and within that directory I want to be able to build like a home.go component that features all the code needed for my homepage.</p><p>So, how do we go about doing this?</p><p>Well, React tends to feature classes that feature render() functions which return the HTML/JSX/whatever code you wish to render for said component. Let’s steal this and use it within our own components.</p><p>I essentially want to be able to do something like this within a project that uses this framework:</p><pre>package components<br><br>type HomeComponent struct{}<br><br>var Home HomeComponent<br><br>func (h HomeComponent) Render() string {<br>	return &quot;&lt;h2&gt;Home Component&lt;/h2&gt;&quot;<br>}</pre><p>So, within my components package, I define a HomeComponent which features a Render() method which returns our HTML.</p><p>In order to add components to our framework, we’ll keep it simple and just define an interface to which any components we subsequently define will have to adhere to. Create a new file called components/comopnent.go within our Oak framework:</p><pre>// components/component.go<br>package component<br><br>type Component interface {<br>	Render() string<br>}</pre><p>What happens if we want to add new functions to our various components? Well, this allows us to do just that. We can use the oak.RegisterFunction call within the init function of our component to register any functions we want to use within our component!</p><pre>package components<br><br>import (<br>	&quot;syscall/js&quot;<br><br>	&quot;github.com/elliotforbes/oak&quot;<br>)<br><br>type AboutComponent struct{}<br><br>var About AboutComponent<br><br>func init() {<br>	oak.RegisterFunction(&quot;coolFunc&quot;, CoolFunc)<br>}<br><br>func CoolFunc(i []js.Value) {<br>	println(&quot;does stuff&quot;)<br>}<br><br>func (a AboutComponent) Render() string {<br>	return `&lt;div&gt;<br>						&lt;h2&gt;About Component Actually Works&lt;/h2&gt;<br>						&lt;button onClick=&quot;coolFunc();&quot;&gt;Cool Func&lt;/button&gt;<br>					&lt;/div&gt;`<br>}</pre><p>When we combine this with a router, we should be able to see our HTML being rendered to our page and we should be able to click that button which calls coolFunc() and it will print out does stuff within our browser console!</p><p>Awesome, let’s see how we can go about building a simple router now.</p><h3>Building a Router</h3><p>Ok, so we’ve got the concept of components within our web framework down. We’ve almost finished right?</p><p>Not quite, the next thing we’ll likely need is a means to navigate between different components. Most frameworks seem to have a &lt;div&gt; with a particular id that they bind to and render all their components within, so we’ll steal that same tactic within Oak.</p><p>Let’s create a router/router.go file within our oak framework so that we can start hacking away.</p><p>Within this, we’ll want to map string paths to components, we wont do any URL checking, we’ll just keep everything in memory for now to keep things simple:</p><pre>// router/router.go<br>package router<br><br>import (<br>	&quot;syscall/js&quot;<br><br>	&quot;github.com/elliotforbes/oak/component&quot;<br>)<br><br>type Router struct {<br>	Routes map[string]component.Component<br>}<br><br>var router Router<br><br>func init() {<br>	router.Routes = make(map[string]component.Component)<br>}</pre><p>So within this, we’ve created a new Router struct which contains Routes which are a map of strings to the components we defined in the previous section.</p><p>Routing won’t be a mandatory concept within our framework, we’ll want users to choose when they wish to initialize a new router. So let’s create a new function that will register a Link function and also bind the first route in our map to our &lt;div id=&quot;view&quot;/&gt; html tag:</p><pre>// router/router.go<br>// ...<br>func NewRouter() {<br>	js.Global().Set(&quot;Link&quot;, js.NewCallback(Link))<br>	js.Global().Get(&quot;document&quot;).Call(&quot;getElementById&quot;, &quot;view&quot;).Set(&quot;innerHTML&quot;, &quot;&quot;)<br>}<br><br>func RegisterRoute(path string, component component.Component) {<br>	router.Routes[path] = component<br>}<br><br>func Link(i []js.Value) {<br>	println(&quot;Link Hit&quot;)<br><br>	comp := router.Routes[i[0].String()]<br>	html := comp.Render()<br><br>	js.Global().Get(&quot;document&quot;).Call(&quot;getElementById&quot;, &quot;view&quot;).Set(&quot;innerHTML&quot;, html)<br>}</pre><p>You should notice, we’ve created a RegisterRoute function which allows us to register a path to a given component.</p><p>Our Link function is also pretty cool in the sense that it will allow us to navigate between various components within a project. We can specify really simple &lt;button&gt; elements to allow us to navigate to registered paths like so:</p><pre>&lt;button onClick=&quot;Link(&#39;link&#39;)&quot;&gt;Clicking this will render our mapped Link component&lt;/button&gt;</pre><p>Awesome, so we’ve got a really simple router up and running now, if we wanted to use this in a simple application we could do so like this:</p><pre>// my-project/main.go<br>package main<br><br>import (<br>	&quot;github.com/elliotforbes/oak&quot;<br>	&quot;github.com/elliotforbes/oak/examples/blog/components&quot;<br>	&quot;github.com/elliotforbes/oak/router&quot;<br>)<br><br>func main() {<br>	// Starts the Oak framework<br>	oak.Start()<br><br>	// Starts our Router<br>	router.NewRouter()<br>	router.RegisterRoute(&quot;home&quot;, components.Home)<br>	router.RegisterRoute(&quot;about&quot;, components.About)<br><br>	// keeps our app running<br>	done := make(chan struct{}, 0)<br>	&lt;-done<br>}</pre><h3>A Full Example</h3><p>With all of this put together, we can start building really simple web applications that feature components and routing. If you want to see a couple of examples as to how this works, then check out the examples within the official repo: <a href="https://github.com/elliotforbes/oak/tree/master/examples">elliotforbes/oak/examples</a></p><h3>Challenges Going Forward</h3><p>The code in this framework is in no way production ready, but I’m hoping this post kicks off good discussion as to how we can start building more production ready frameworks in Go.</p><p>If nothing else, it starts the journey of identifying what still has to be done to make this a viable alternative to the likes of React/Angular/VueJS, all of which are phenomenal frameworks that massively speed up developer productivity.</p><p>I’m hoping this article motivates some of you to go off and start looking at how you can improve on this incredibly simple starting point.</p><h3>Conclusion</h3><p>If you enjoyed this tutorial, then please feel free to share it to your friends, on your twitter, or wherever you feel like, it really helps the site and directly supports me writing more!</p><p>I’m also on YouTube, so feel free to subscribe to my channel for more Go content:</p><p><a href="https://youtube.com/tutorialedge">TutorialEdge</a></p><blockquote><em>The full source code for the Oak framework can be found here: </em><a href="https://github.com/elliotforbes/oak/"><em>github.com/elliotforbes/oak</em></a><em>. Feel free to submit PRs!</em></blockquote><p><em>Originally published at </em><a href="https://tutorialedge.net/golang/writing-frontend-web-framework-webassembly-go/"><em>tutorialedge.net</em></a><em>.</em></p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fupscri.be%2Fdde502%3Fas_embed%3Dtrue&amp;dntp=1&amp;url=https%3A%2F%2Fupscri.be%2Fhackernoon%2F&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=upscri" width="800" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/3c851dac986ab6dbb2d1aaa91205a8eb/href">https://medium.com/media/3c851dac986ab6dbb2d1aaa91205a8eb/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ff84cd1346fe" width="1" height="1" alt=""><hr><p><a href="https://medium.com/hackernoon/writing-a-frontend-web-framework-with-webassembly-and-go-ff84cd1346fe">Writing a Frontend Web Framework with WebAssembly And Go</a> was originally published in <a href="https://medium.com/hackernoon">HackerNoon.com</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Go Face Recognition Tutorial — Part 1]]></title>
            <link>https://medium.com/hackernoon/go-face-recognition-tutorial-part-1-373357230baa?source=rss-eb71d34fbe09------2</link>
            <guid isPermaLink="false">https://medium.com/p/373357230baa</guid>
            <category><![CDATA[face-recognition]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[Elliot Forbes]]></dc:creator>
            <pubDate>Fri, 28 Sep 2018 15:13:08 GMT</pubDate>
            <atom:updated>2019-04-27T10:51:36.362Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6k6udG_aPIGHHZpfRXameg.jpeg" /></figure><p>The whole area of <a href="https://hackernoon.com/tagged/face">Face</a> Recognition is something I love reading about. Implementing one yourself makes you sound like you are Tony Stark and you can use them for a variety of different projects such as an automatic lock on your door, or building a surveillance system for your office.</p><p>In this <a href="https://hackernoon.com/tagged/tutorial">tutorial</a>, we are going to be building our own, really simple face recognition based system in Go using a few existing libraries. We’ll start by doing simple face recognition on still images and seeing how that works and we’ll then be expanding upon this to look into real-time face recognition on video feeds in part 2 of this mini-series.</p><h3>Video Tutorial</h3><p>This tutorial is also available in video format! If you want to support me and my channel then please like and subscribe :)</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FcLrRLA9y1i4%3Ffeature%3Doembed&amp;url=http%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DcLrRLA9y1i4&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FcLrRLA9y1i4%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="640" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/72fc2c530a6558ab045bf8c2b9fd77b0/href">https://medium.com/media/72fc2c530a6558ab045bf8c2b9fd77b0/href</a></iframe><h3>The Kagami/go-face package</h3><p>For the basis of this tutorial, we’ll be using the <a href="https://github.com/Kagami/go-face">kagami/go-face</a> package which wraps around the dlib machine learning toolkit!</p><blockquote><em>Kagami actually wrote about how he went about writing this package. It’s definitely an interesting read and you can find it here: </em><a href="https://hackernoon.com/face-recognition-with-go-676a555b8a7e"><em>https://hackernoon.com/face-recognition-with-go-676a555b8a7e</em></a></blockquote><h4>The dlib toolkit</h4><p>The Dlib toolkit is built in C++ and is incredible at both face and object recognition/detection. According to its documentation, it scores around 99.4% accuracy on detecting labeled faces in the Wild benchmark which is incredible and it’s the reason why so many other third-party libraries utilize it as their base.</p><blockquote><em>I’ve covered the Dlib toolkit’s Python library — face_recognition in a previous tutorial. If you want to check out the python equivalent of this tutorial, here it is: </em><a href="https://tutorialedge.net/python/intro-face-recognition-in-python/"><em>An introduction to Face Recognition in Python</em></a></blockquote><h3>Setup</h3><p>I’m not going to lie, getting this up and running is slightly more painful than your standard Go package. You’ll need to install both pkg-config and dlib on your machine. If you are running on MacOS then this is the command:</p><pre>$ brew install pkg-config dlib <br>$ sed -i &#39;&#39; &#39;s/^Libs: .*/&amp; -lblas -llapack/&#39; /usr/local/lib/pkgconfig/dlib-1.pc</pre><h3>Getting Started</h3><p>We’ll first of all need to download the `kagami/go-face` package which can be done with the following `go get` command:</p><pre>$ go get -u github.com/Kagami/go-face</pre><p>Create a new directory called go-face-recognition in your GOPATH directory. Within this directory create a new file called main.go, this is where all of our source code is going to reside.</p><p>Once you’ve done this, you will need to grab the files from the image/ directory in the <a href="https://github.com/TutorialEdge/go-face-recognition-tutorial">TutorialEdge/go-face-recognition-tutorial</a> repo. The easiest way to do this is to clone the repo into another directory and just copy the image directory into your current working directory:</p><pre>$ git clone <a href="https://github.com/TutorialEdge/go-face-recognition-tutorial.git">https://github.com/TutorialEdge/go-face-recognition-tutorial.git</a></pre><p>Once that has been successfully cloned, we have both the .dat files that we need in order to kick off our face recognition program. You should also see a list of other .jpg files which contain the faces of some of the Marvel Avengers.</p><pre>package main<br><br>import (<br>	&quot;fmt&quot;<br><br>	&quot;github.com/Kagami/go-face&quot;<br>)<br><br>const dataDir = &quot;testdata&quot;<br><br>func main() {<br>	fmt.Println(&quot;Facial Recognition System v0.01&quot;)<br><br>	rec, err := face.NewRecognizer(dataDir)<br>	if err != nil {<br>		fmt.Println(&quot;Cannot initialize recognizer&quot;)<br>	}<br>	defer rec.Close()<br><br>	fmt.Println(&quot;Recognizer Initialized&quot;)<br>}</pre><p>Ok, so if we try and run our program at this point, we should see both Facial Recognition System v0.01 and Recognizer Initialized in our program’s output. We’ve successfully set everything we need up in order to do some cool advanced facial recognition!</p><h3>Counting Faces in a Picture</h3><p>Our first real test of this package will be to test to see whether we can accurately count the number of faces in a photograph. For the purpose of this tutorial, I will be using this photo:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/354/0*qkyqz_7-n6of3FOj.jpg" /></figure><p>As you can see, nothing fancy, just the solitary face of Tony Stark.</p><p>So, we now need to extend our existing program to be able to analyze this image and then count the number of faces within said image:</p><pre>package main<br><br>import (<br>	&quot;fmt&quot;<br>	&quot;log&quot;<br>	&quot;path/filepath&quot;<br><br>	&quot;github.com/Kagami/go-face&quot;<br>)<br><br>const dataDir = &quot;testdata&quot;<br><br>func main() {<br>	fmt.Println(&quot;Facial Recognition System v0.01&quot;)<br><br>	rec, err := face.NewRecognizer(dataDir)<br>	if err != nil {<br>		fmt.Println(&quot;Cannot initialize recognizer&quot;)<br>	}<br>	defer rec.Close()<br><br>	fmt.Println(&quot;Recognizer Initialized&quot;)<br><br>	// we create the path to our image with filepath.Join<br>	avengersImage := filepath.Join(dataDir, &quot;tony-stark.jpg&quot;)<br><br>	// we then call RecognizeFile passing in the path<br>	// to our file to retrieve the number of faces and any<br>	// potential errors<br>	faces, err := rec.RecognizeFile(avengersImage)<br>	if err != nil {<br>		log.Fatalf(&quot;Can&#39;t recognize: %v&quot;, err)<br>	}<br>	// we print out the number of faces in our image<br>	fmt.Println(&quot;Number of Faces in Image: &quot;, len(faces))<br><br>}</pre><p>When we run this, we should see the following output:</p><pre>$ go run main.go <br>Facial Recognition System v0.01 <br>Recognizer Initialized <br>Number of Faces in Image: 1</pre><p>Awesome, we’ve been able to analyze an image and determine that the image contains the face of one person. Let’s try a more complex image with more of the Avengers in it:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/980/0*cGjZDM_DpJ49-SX0.jpg" /></figure><p>When we update line 24:</p><pre>avengersImage := filepath.Join(dataDir, &quot;avengers-01.jpg&quot;)</pre><p>And re-run our program, you should see that our program is able to determine that 2 people are in this new image.</p><h3>Recognizing Faces:</h3><p>Sweet, so we’re able to calculate the number of faces in an image, now what about actually determining who those people are?</p><p>To do this, we’ll need a number of reference photos. For example, if we wanted to be able to recognize Tony Stark out of a photo, we would need example photos tagged with his name. The recognition software would then be able to analyze photos for faces with his likeness and match them together.</p><p>So, let’s take our avengers-02.jpeg as our reference image for Tony Stark and then see if we can identify him from the image we previously used for him.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6k6udG_aPIGHHZpfRXameg.jpeg" /><figcaption>avengers-02.jpeg</figcaption></figure><pre>avengersImage := filepath.Join(dataDir, &quot;avengers-02.jpeg&quot;)<br><br>faces, err := rec.RecognizeFile(avengersImage)<br>if err != nil {<br>	log.Fatalf(&quot;Can&#39;t recognize: %v&quot;, err)<br>}<br>fmt.Println(&quot;Number of Faces in Image: &quot;, len(faces))<br><br>var samples []face.Descriptor<br>var avengers []int32<br>for i, f := range faces {<br>	samples = append(samples, f.Descriptor)<br>	// Each face is unique on that image so goes to its own category.<br>	avengers = append(avengers, int32(i))<br>}<br><br>labels := []string{<br>	&quot;Dr Strange&quot;,<br>	&quot;Tony Stark&quot;,<br>	&quot;Bruce Banner&quot;,<br>	&quot;Wong&quot;,<br>}</pre><pre>// Pass samples to the recognizer.<br>rec.SetSamples(samples, avengers)</pre><p>So, in the above code, we’ve gone through all of the faces in order from left to right and labeled them with their appropriate names. Our recognition system can then use these reference samples to try and perform it’s own facial recognition on subsequent files.</p><p>Let’s try testing out our recognition system with our existing image of Tony Stark and seeing if it’s able to recognize this based of the face descriptor it generated from the avengers-02.jpeg file:</p><pre>testTonyStark := filepath.Join(dataDir, &quot;tony-stark.jpg&quot;)<br>tonyStark, err := rec.RecognizeSingleFile(testTonyStark)<br>if err != nil {<br>	log.Fatalf(&quot;Can&#39;t recognize: %v&quot;, err)<br>}<br>if tonyStark == nil {<br>	log.Fatalf(&quot;Not a single face on the image&quot;)<br>}<br>avengerID := rec.Classify(tonyStark.Descriptor)<br>if avengerID &lt; 0 {<br>	log.Fatalf(&quot;Can&#39;t classify&quot;)<br>}<br><br>fmt.Println(avengerID)<br>fmt.Println(labels[avengerID])</pre><p>Let’s now try to validate that this wasn’t a fluke and try to see if our image recognition system works with an image of Dr Strange.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/980/0*a2uefeB_uBSIC4uF.jpg" /></figure><pre>testDrStrange := filepath.Join(dataDir, &quot;dr-strange.jpg&quot;)<br>drStrange, err := rec.RecognizeSingleFile(testDrStrange)<br>if err != nil {<br>	log.Fatalf(&quot;Can&#39;t recognize: %v&quot;, err)<br>}<br>if drStrange == nil {<br>	log.Fatalf(&quot;Not a single face on the image&quot;)<br>}<br>avengerID = rec.Classify(drStrange.Descriptor)<br>if avengerID &lt; 0 {<br>	log.Fatalf(&quot;Can&#39;t classify&quot;)<br>}</pre><p>And finally, let’s try this out using Wong’s image:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*gyb1Kix-ZOx6xaV_.jpg" /></figure><pre>testWong := filepath.Join(dataDir, &quot;wong.jpg&quot;)<br>wong, err := rec.RecognizeSingleFile(testWong)<br>if err != nil {<br>	log.Fatalf(&quot;Can&#39;t recognize: %v&quot;, err)<br>}<br>if wong == nil {<br>	log.Fatalf(&quot;Not a single face on the image&quot;)<br>}<br>avengerID = rec.Classify(wong.Descriptor)<br>if avengerID &lt; 0 {<br>	log.Fatalf(&quot;Can&#39;t classify&quot;)<br>}<br>fmt.Println(avengerID)<br>fmt.Println(labels[avengerID])</pre><p>When you run this all together, you should see the following output:</p><pre>$ go run main.go <br>Facial Recognition System v0.01 <br>Recognizer Initialized <br>Number of Faces in Image: 4 <br>1 Tony Stark <br>0 Dr Strange <br>3 Wong</pre><p>Awesome, we’ve managed to build up a really simple face recognition system that allows us to identify the various different Avengers.</p><blockquote><em>Challenge: Build up a number of reference files on all of the Avengers and try to extract out the face recognition code snippets into a reusable function</em></blockquote><h3>Complete Source Code:</h3><p>The complete source code for this tutorial can be found in Github: <a href="https://github.com/TutorialEdge/go-face-recognition-tutorial">Tutorialedge/go-face-recognition-tutorial</a></p><h3>Conclusion</h3><p>In this tutorial, we successfully managed to build a really simple face recognition system that works on still images. This will hopefully form the basis of the next part of this tutorial series, in which we look at how to do this in a real-time context on a video stream.</p><p>Hopefully you enjoyed this tutorial, if you did then please let me know in the comments section down below!</p><p><em>Originally published at </em><a href="https://tutorialedge.net/golang/go-face-recognition-tutorial-part-one/"><em>tutorialedge.net</em></a><em>.</em></p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fupscri.be%2Fdde502%3Fas_embed%3Dtrue&amp;dntp=1&amp;url=https%3A%2F%2Fupscri.be%2Fhackernoon%2F&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=upscri" width="800" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/3c851dac986ab6dbb2d1aaa91205a8eb/href">https://medium.com/media/3c851dac986ab6dbb2d1aaa91205a8eb/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=373357230baa" width="1" height="1" alt=""><hr><p><a href="https://medium.com/hackernoon/go-face-recognition-tutorial-part-1-373357230baa">Go Face Recognition Tutorial — Part 1</a> was originally published in <a href="https://medium.com/hackernoon">HackerNoon.com</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[This story has been migrated to TutorialEdge, find it here: https://tutorialedge.net/blog/my-notes-f]]></title>
            <link>https://medium.com/a-cloud-guru/my-notes-for-certified-kubernetes-application-developer-part-1-core-concepts-d1bab7bc2446?source=rss-eb71d34fbe09------2</link>
            <guid isPermaLink="false">https://medium.com/p/d1bab7bc2446</guid>
            <category><![CDATA[cloud-computing]]></category>
            <category><![CDATA[distributed-systems]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[software]]></category>
            <category><![CDATA[kubernetes]]></category>
            <dc:creator><![CDATA[Elliot Forbes]]></dc:creator>
            <pubDate>Fri, 07 Sep 2018 08:22:35 GMT</pubDate>
            <atom:updated>2019-08-20T20:19:14.821Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GBhB_njKh-3tkBJ3E5W_Lg.png" /></figure><p>This story has been migrated to TutorialEdge, find it here: <a href="https://tutorialedge.net/blog/my-notes-for-certified-kubernetes/">https://tutorialedge.net/blog/my-notes-for-certified-kubernetes/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d1bab7bc2446" width="1" height="1" alt=""><hr><p><a href="https://medium.com/a-cloud-guru/my-notes-for-certified-kubernetes-application-developer-part-1-core-concepts-d1bab7bc2446">This story has been migrated to TutorialEdge, find it here: https://tutorialedge.net/blog/my-notes-f</a> was originally published in <a href="https://medium.com/a-cloud-guru">A Cloud Guru</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Advanced Testing in Go - Tutorial]]></title>
            <link>https://medium.com/hackernoon/advanced-testing-in-go-tutorial-28b89d3a813?source=rss-eb71d34fbe09------2</link>
            <guid isPermaLink="false">https://medium.com/p/28b89d3a813</guid>
            <category><![CDATA[testing]]></category>
            <category><![CDATA[go-tutorial]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Elliot Forbes]]></dc:creator>
            <pubDate>Fri, 31 Aug 2018 18:41:56 GMT</pubDate>
            <atom:updated>2019-04-27T10:52:22.641Z</atom:updated>
            <content:encoded><![CDATA[<p>Welcome fellow coders! In this <a href="https://hackernoon.com/tagged/tutorial">tutorial</a>, we are going to be taking a look at some of the more advanced testing practices used by the Go language developers in the official <a href="https://hackernoon.com/tagged/golang">Golang</a>/go repo.</p><p>I feel this approach, of actually studying what has been done in a production system, will hopefully give you some insight into the best ways to test your own production-level Go programs.</p><blockquote><em>If you are entirely new to testing your Go-based programs, then I suggest you check out my other tutorial: </em><a href="https://tutorialedge.net/golang/intro-testing-in-go/"><em>an introduction to testing in go</em></a></blockquote><h3>Video Tutorial</h3><p>This tutorial is available in video format. If you wish to support me and my content then please like and subscribe! :D</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FS1O0XI0scOM%3Ffeature%3Doembed&amp;url=http%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DS1O0XI0scOM&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FS1O0XI0scOM%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/0593d0c4cb2d3f5fae5c0641dbb46405/href">https://medium.com/media/0593d0c4cb2d3f5fae5c0641dbb46405/href</a></iframe><h3>Achieving Good Coverage with Table Driven Tests</h3><p>Let’s start our journey in the strings package. If you have a look at the top of the strings_test.go file within src/strings/ you should see a number of arrays defined and populated.</p><p>For example, take a look at lastIndexTests which is an array of type IndexTest:</p><pre>var lastIndexTests = []IndexTest{<br>	{&quot;&quot;, &quot;&quot;, 0},<br>	{&quot;&quot;, &quot;a&quot;, -1},<br>	{&quot;&quot;, &quot;foo&quot;, -1},<br>	{&quot;fo&quot;, &quot;foo&quot;, -1},<br>	{&quot;foo&quot;, &quot;foo&quot;, 0},<br>	{&quot;foo&quot;, &quot;f&quot;, 0},<br>	{&quot;oofofoofooo&quot;, &quot;f&quot;, 7},<br>	{&quot;oofofoofooo&quot;, &quot;foo&quot;, 7},<br>	{&quot;barfoobarfoo&quot;, &quot;foo&quot;, 9},<br>	{&quot;foo&quot;, &quot;&quot;, 3},<br>	{&quot;foo&quot;, &quot;o&quot;, 2},<br>	{&quot;abcABCabc&quot;, &quot;A&quot;, 3},<br>	{&quot;abcABCabc&quot;, &quot;a&quot;, 6},<br>}</pre><p>This array is used to test the LastIndex function within the strings.go file with a number of negative and positive cases. Each of these IndexTest elements feature a standard string, a separator, and an out integer value and have a struct that looks like this:</p><pre>type IndexTest struct {<br>	s   string<br>	sep string<br>	out int<br>}</pre><p>These tests are then triggered by the TestLastIndex() function which runs through all of these test cases and checks to see whether the results returned from the lastIndex function match the expected results outlined in the array.</p><p>This same practice is done numerous times for numerous different functions and this helps to guarantee that when any code changes are made to these functions, the expected functionality will not change.</p><h3>Use the testdata Directory</h3><p>In certain situations, you won’t be able to specify your expected input and output as an array of elements like in the above example. You may be trying to test how you read + write to files on the filesystem or how you parse proprietary data formats and so on.</p><p>If this is the case then one option is to create a testdata directory and store any files you may need for testing within that directory.</p><p>A great example of this can again be found within the Standard Library under src/archive/tar/ in which a testdata/ directory is defined and contains a number of .tar files that are subsequently used for testing.</p><p>Some fairly complex examples of tests using these files can be found in the reader_test.go file.</p><pre>func TestReader(t *testing.T) {<br>	vectors := []struct {<br>		file    string    // Test input file<br>		headers []*Header // Expected output headers<br>		chksums []string  // MD5 checksum of files, leave as nil if not checked<br>		err     error     // Expected error to occur<br>	}{{<br>		file: &quot;testdata/gnu.tar&quot;,<br>		headers: []*Header{{<br>			Name:     &quot;small.txt&quot;,<br>			Mode:     0640,<br>			Uid:      73025,<br>			Gid:      5000,<br>			Size:     5,<br>			ModTime:  time.Unix(1244428340, 0),<br>			Typeflag: &#39;0&#39;,<br>			Uname:    &quot;dsymonds&quot;,<br>			Gname:    &quot;eng&quot;,<br>			Format:   FormatGNU,<br>		}, {<br>			Name:     &quot;small2.txt&quot;,<br>			Mode:     0640,<br>			Uid:      73025,<br>			Gid:      5000,<br>			Size:     11,<br>			ModTime:  time.Unix(1244436044, 0),<br>			Typeflag: &#39;0&#39;,<br>			Uname:    &quot;dsymonds&quot;,<br>			Gname:    &quot;eng&quot;,<br>			Format:   FormatGNU,<br>		}},<br>		chksums: []string{<br>			&quot;e38b27eaccb4391bdec553a7f3ae6b2f&quot;,<br>			&quot;c65bd2e50a56a2138bf1716f2fd56fe9&quot;,<br>		},<br>  }, <br>  // more test cases</pre><p>In the above function you’ll see that the core developers are combining the first technique we covered here in combination with files from the testdata/ directory to ensure that when a sample .tar file is opened, the files and their checksums match their expectations.</p><h3>Mocking HTTP Requests</h3><p>As soon as you start writing production-level APIs and services, it’s likely you’ll start interacting with other services and being able to test the way that you interact with these services is just as important as testing other parts of your codebase.</p><p>However, you may be interacting with REST APIs that perform CRUD actions on databases and as such, you don’t want these changes actually being committed to your database when you are just trying to test things are working.</p><p>So, in order to get around this problem, we can mock HTTP responses using the net/http/httptest package which is our best friend in these situations.</p><pre>package main_test<br><br>import (<br>	&quot;fmt&quot;<br>	&quot;io&quot;<br>	&quot;io/ioutil&quot;<br>	&quot;net/http&quot;<br>	&quot;net/http/httptest&quot;<br>	&quot;testing&quot;<br>)<br><br>func TestHttp(t *testing.T) {<br>  // <br>	handler := func(w http.ResponseWriter, r *http.Request) {<br>    // here we write our expected response, in this case, we return a<br>    // JSON string which is typical when dealing with REST APIs<br>		io.WriteString(w, &quot;{ \&quot;status\&quot;: \&quot;expected service response\&quot;}&quot;)<br>	}<br><br>	req := httptest.NewRequest(&quot;GET&quot;, &quot;https://tutorialedge.net&quot;, nil)<br>	w := httptest.NewRecorder()<br>	handler(w, req)<br><br>	resp := w.Result()<br>	body, _ := ioutil.ReadAll(resp.Body)<br>haha<br>	fmt.Println(resp.StatusCode)<br>	fmt.Println(resp.Header.Get(&quot;Content-Type&quot;))<br>	fmt.Println(string(body))<br>}</pre><p>In the above test case, we basically overwrite the response we expect from our URL and then continue to test other parts of our system that rely upon that response.</p><h3>The Use of Separate Packages</h3><p>If we have a look at the strings_test.go file and inspect the package at the top, you should notice that it doesn’t reside within the same package that the strings.go file resides within.</p><p>The reason for this? It helps you to avoid cyclic imports. In some scenarios, you’ll need to import a package in your *_test.go file to adequately write your tests. If the package you import in already has a reference to the package you are trying to test, you may see issues with cyclic dependencies.</p><h3>Differentiate your Unit and Integration Tests</h3><blockquote><em>I originally found out about this tip from: </em><a href="https://medium.com/@povilasve/go-advanced-tips-tricks-a872503ac859"><em>Go Advanced Tips Tricks</em></a></blockquote><p>If you are writing tests for large enterprise Go systems then you’ll more than likely have a set of both integration and unit tests ensuring the validity of your system.</p><p>More often than not however, you’ll find your integration tests taking far longer to run as opposed to your unit tests due to the fact they could be reaching out to other systems.</p><p>In this case, it makes sense to put your integration tests into *_integration_test.go files and adding // +build integration to the top of your test file:</p><pre>// +build integration<br><br>package main_test<br><br>import (<br>	&quot;fmt&quot;<br>	&quot;testing&quot;<br>)<br><br>func TestMainIntegration(t *testing.T) {<br>	fmt.Println(&quot;My Integration Test&quot;)<br>}</pre><p>In order to run this suite of integration tests you can call go test like so:</p><pre>➜  advanced-go-testing-tutorial git:(master) ✗ go test -tags=integration<br>My Integration Test<br>PASS<br>ok      _/Users/elliot/Documents/Projects/tutorials/golang/advanced-go-testing-tutorial 0.006s</pre><h3>Conclusion</h3><p>So, in this tutorial, we had a look at some of the more advanced testing techniques and tricks employed by the Go language maintainers.</p><p>Hopefully, you found this useful and it gave you the insight needed to go off and improve your own go tests. If you found it useful, or have any further questions, then please don’t hesitate to let me know in the comments section below!</p><p><em>Originally published at </em><a href="https://tutorialedge.net/golang/advanced-go-testing-tutorial/"><em>tutorialedge.net</em></a><em>.</em></p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fupscri.be%2Fdde502%3Fas_embed%3Dtrue&amp;dntp=1&amp;url=https%3A%2F%2Fupscri.be%2Fhackernoon%2F&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=upscri" width="800" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/3c851dac986ab6dbb2d1aaa91205a8eb/href">https://medium.com/media/3c851dac986ab6dbb2d1aaa91205a8eb/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=28b89d3a813" width="1" height="1" alt=""><hr><p><a href="https://medium.com/hackernoon/advanced-testing-in-go-tutorial-28b89d3a813">Advanced Testing in Go - Tutorial</a> was originally published in <a href="https://medium.com/hackernoon">HackerNoon.com</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Go WebAssembly — Building a Calculator Tutorial]]></title>
            <link>https://medium.com/hackernoon/go-webassembly-building-a-calculator-tutorial-70fff89db6a9?source=rss-eb71d34fbe09------2</link>
            <guid isPermaLink="false">https://medium.com/p/70fff89db6a9</guid>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[webassembly]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[build-a-calculator]]></category>
            <category><![CDATA[go-webassembly]]></category>
            <dc:creator><![CDATA[Elliot Forbes]]></dc:creator>
            <pubDate>Sun, 26 Aug 2018 13:09:58 GMT</pubDate>
            <atom:updated>2019-04-27T10:53:26.302Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*S4ndDSZ5uUdEjlzmn8bXGA.png" /></figure><p>Welcome All! With Go v1.11 having just been released with an experimental port to WebAssembly included, I thought it would be awesome to see how we can write our own Go programs that compile straight to WebAssembly!</p><p>So, in this article, we are going to be building a really simple calculator to give us an idea as to how we can write functions that can be exposed to the frontend, evaluate DOM elements and subsequently update any DOM elements with the results from any functions we call.</p><p>This will hopefully show you what it takes to write and compile your own Go-based programs for your frontend applications.</p><blockquote><em>If you haven’t guessed from the opening line, Go v1.11 will be required in order for this </em><a href="https://hackernoon.com/tagged/tutorial"><em>tutorial</em></a><em> to work!</em></blockquote><h3>Video Tutorial</h3><p>If you want to support me and my efforts then check out the video version of this tutorial and subscribe to my channel!</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2F4kBvvk2Bzis%3Ffeature%3Doembed&amp;url=http%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3D4kBvvk2Bzis&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2F4kBvvk2Bzis%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/3ffcb07ff0c6124546c7048734915737/href">https://medium.com/media/3ffcb07ff0c6124546c7048734915737/href</a></iframe><h3>Introduction</h3><p>So what does this really mean for Go and Web developers? Well, it gives us the ability to write our frontend web apps using the Go language and subsequently all its cool features such as its type safety, its <a href="https://tutorialedge.net/golang/concurrency-with-golang-goroutines/">goroutines</a> and more.</p><p>Now, this isn’t the first time we’ve seen the Go language being used for frontend purposes. GopherJS has been around for quite a while now and is pretty damn mature, however, the difference is that it compiles Go code to JS and not to WebAssembly.</p><h3>A Simple Example</h3><p>Let’s start off with a really simple example, this will simply output Hello World in the console whenever we click a button in our web page. Sounds exciting I know, but we can very quickly build this up into something more functional and cooler:</p><pre>package main<br><br>func main() {<br>	println(&quot;Hello World&quot;)<br>}</pre><p>Now, in order to compile this, you’ll have to set GOARCH=wasm and GOOS=js and you’ll also have to specify the name of your file using the -o flag like so:</p><pre>$ GOARCH=wasm GOOS=js go build -o lib.wasm main.go</pre><p>This command should compile our code into a lib.wasm file within our current working directory. We’ll be using the WebAssembly.instantiateStreaming() function to load this into our page within our index.html. Note - this code was stolen from the official Go language repo:</p><pre>&lt;!doctype html&gt;<br>&lt;!--<br>Copyright 2018 The Go Authors. All rights reserved.<br>Use of this source code is governed by a BSD-style<br>license that can be found in the LICENSE file.<br>--&gt;<br>&lt;html&gt;<br><br>&lt;head&gt;<br>	&lt;meta charset=&quot;utf-8&quot;&gt;<br>	&lt;title&gt;Go wasm&lt;/title&gt;<br>&lt;/head&gt;<br><br>&lt;body&gt;<br><br>	&lt;script src=&quot;wasm_exec.js&quot;&gt;&lt;/script&gt;<br><br>	&lt;script&gt;<br>		if (!WebAssembly.instantiateStreaming) { // polyfill<br>			WebAssembly.instantiateStreaming = async (resp, importObject) =&gt; {<br>				const source = await (await resp).arrayBuffer();<br>				return await WebAssembly.instantiate(source, importObject);<br>			};<br>		}<br><br>		const go = new Go();<br>		<br>		let mod, inst;<br><br>		WebAssembly.instantiateStreaming(fetch(&quot;lib.wasm&quot;), go.importObject).then((result) =&gt; {<br>			mod = result.module;<br>			inst = result.instance;<br>			document.getElementById(&quot;runButton&quot;).disabled = false;<br>		});<br><br>		async function run() {<br>			await go.run(inst);<br>			inst = await WebAssembly.instantiate(mod, go.importObject); // reset instance<br>		}<br><br>	&lt;/script&gt;<br><br>	&lt;button onClick=&quot;run();&quot; id=&quot;myButton&quot; disabled&gt;Run&lt;/button&gt;<br>&lt;/body&gt;<br>&lt;/html&gt;</pre><p>We’ll also need the wasm_exec.js file which can be found <a href="https://github.com/golang/go/blob/master/misc/wasm/wasm_exec.js">here</a>. Download that and save it alongside your index.html.</p><pre>$ wget <a href="https://github.com/golang/go/blob/master/misc/wasm/wasm_exec.js">https://github.com/golang/go/blob/master/misc/wasm/wasm_exec.js</a></pre><p>And, we also have a simple net/http based file server, again stolen from <a href="https://github.com/golang/go/wiki/WebAssembly">here</a>, to serve up our index.html and our various other WebAssembly files:</p><pre>package main<br><br>import (<br>	&quot;flag&quot;<br>	&quot;log&quot;<br>	&quot;net/http&quot;<br>)<br><br>var (<br>	listen = flag.String(&quot;listen&quot;, &quot;:8080&quot;, &quot;listen address&quot;)<br>	dir    = flag.String(&quot;dir&quot;, &quot;.&quot;, &quot;directory to serve&quot;)<br>)<br><br>func main() {<br>	flag.Parse()<br>	log.Printf(&quot;listening on %q...&quot;, *listen)<br>	log.Fatal(http.ListenAndServe(*listen, http.FileServer(http.Dir(*dir))))<br>}</pre><p>When you navigate to localhost:8080 once you’ve kicked off this server, you should see that the Run button is clickable and if you open up your console in the browser, you should see that it prints out Hello World every time you click the button!</p><p>Awesome, we’ve managed to successfully compile a really simple Go -&gt; WebAssembly project and get it working in the browser.</p><h3>A More Complex Example</h3><p>Now for the good bit. Say, we wanted to create a more complex example that featured DOM manipulation, custom Go functions that could be bound to button clicks and more. Well thankfully, it’s not too difficult!</p><h3>Registering Functions</h3><p>We’ll start off by creating a few functions of our own that we want to expose to our frontend. I’m feeling rather unoriginal today so these are going to be just add and subtract.</p><p>These functions take in an array of type js.Value and use the js.Global().Set() function to set output to equal the result of any calculations done within our function. For good measure, we also print out to the console what the result is as well:</p><pre>func add(i []js.Value) {<br>	js.Global().Set(&quot;output&quot;, js.ValueOf(i[0].Int()+i[1].Int()))<br>	println(js.ValueOf(i[0].Int() + i[1].Int()).String())<br>}<br><br>func subtract(i []js.Value) {<br>	js.Global().Set(&quot;output&quot;, js.ValueOf(i[0].Int()-i[1].Int()))<br>	println(js.ValueOf(i[0].Int() - i[1].Int()).String())<br>}<br><br>func registerCallbacks() {<br>	js.Global().Set(&quot;add&quot;, js.NewCallback(add))<br>	js.Global().Set(&quot;subtract&quot;, js.NewCallback(subtract))<br>}<br><br>func main() {<br>	c := make(chan struct{}, 0)<br><br>	println(&quot;WASM Go Initialized&quot;)<br>	// register functions<br>	registerCallbacks()<br>	&lt;-c<br>}</pre><p>You’ll notice that we’ve modified our main function slightly by calling make and creating a new channel. This effectively turns our previously short-lived program into a long-running one. We also call another function registerCallbacks() that acts almost like a router, but instead creates new Callbacks that effectively bind our newly created functions to our frontend.</p><p>In order for this to work, we have to very slightly modify the <a href="https://hackernoon.com/tagged/javascript">JavaScript</a> code within our index.html to run our program instance as soon as it’s fetched it:</p><pre>const go = new Go();<br>let mod, inst;<br>WebAssembly.instantiateStreaming(fetch(&quot;lib.wasm&quot;), go.importObject).then(async (result) =&gt; {<br>	mod = result.module;<br>	inst = result.instance;<br>	await go.run(inst)<br>});</pre><p>Load this up in your browser once again and you should see that, without any button presses, WASM Go Initialized prints out in the console. This means that everything has worked.</p><p>We can then start calling out to these functions from the likes of &lt;button&gt; elements like so:</p><pre>&lt;button onClick=&quot;add(2,3);&quot; id=&quot;addButton&quot;&gt;Add&lt;/button&gt;<br>&lt;button onClick=&quot;subtract(10,3);&quot; id=&quot;subtractButton&quot;&gt;Subtract&lt;/button&gt;</pre><p>Remove the existing Run button and add these two new buttons to your index.html. When you reload the page in the browser and open up the console, you should be able to see the outputs of this function printing out.</p><p>We are slowly but surely starting to get somewhere with this!</p><h3>Evaluating DOM Elements</h3><p>So, I guess the next stage, is to start evaluating DOM elements and using their values instead of hard-coded values.</p><p>Let’s modify the add() function so that I can pass in 2 ids of &lt;input/&gt; elements and then add the values of these elements like so:</p><pre>func add(i []js.Value) {<br>	value1 := js.Global().Get(&quot;document&quot;).Call(&quot;getElementById&quot;, i[0].String()).Get(&quot;value&quot;).String()<br>	value2 := js.Global().Get(&quot;document&quot;).Call(&quot;getElementById&quot;, i[1].String()).Get(&quot;value&quot;).String()<br>	js.Global().Set(&quot;output&quot;, value1+value2)<br>	println(value1 + value2)<br>}</pre><p>We can then update our index.html to have the following code:</p><pre>&lt;input type=&quot;text&quot; id=&quot;value1&quot;/&gt;<br>&lt;input type=&quot;text&quot; id=&quot;value2&quot;/&gt;<br><br>&lt;button onClick=&quot;add(&#39;value1&#39;, &#39;value2&#39;);&quot; id=&quot;addButton&quot;&gt;Add&lt;/button&gt;</pre><p>If you enter some numeric values into both our inputs and then click the Add button, you should hopefully see a concatenation of the two values print out in the console.</p><p>What have we forgotten? We need to parse these string values as int values:</p><pre>func add(i []js.Value) {<br>	value1 := js.Global().Get(&quot;document&quot;).Call(&quot;getElementById&quot;, i[0].String()).Get(&quot;value&quot;).String()<br>	value2 := js.Global().Get(&quot;document&quot;).Call(&quot;getElementById&quot;, i[1].String()).Get(&quot;value&quot;).String()<br><br>	int1, _ := strconv.Atoi(value1)<br>	int2, _ := strconv.Atoi(value2)<br><br>	js.Global().Set(&quot;output&quot;, int1+int2)<br>	println(int1 + int2)<br>}</pre><p>You’ll probably notice that I’m not handling errors here as I’m feeling lazy, and this is just for show.</p><p>Try recompiling this code now and reloading your browser, you should notice that if we enter the values 22 and 3 in both our inputs, it successfully outputs 25 in the console.</p><h3>Manipulating DOM elements</h3><p>Our calculator wouldn’t be very good if it didn’t actually report the results within our page, so let’s fix that now by taking in a third id that we’ll output the results to:</p><pre>func add(i []js.Value) {<br>	value1 := js.Global().Get(&quot;document&quot;).Call(&quot;getElementById&quot;, i[0].String()).Get(&quot;value&quot;).String()<br>	value2 := js.Global().Get(&quot;document&quot;).Call(&quot;getElementById&quot;, i[1].String()).Get(&quot;value&quot;).String()<br><br>	int1, _ := strconv.Atoi(value1)<br>	int2, _ := strconv.Atoi(value2)<br><br>	js.Global().Get(&quot;document&quot;).Call(&quot;getElementById&quot;, i[2].String()).Set(&quot;value&quot;, int1+int2)<br>}</pre><p>Finally, let’s update our subtract method:</p><pre>func subtract(i []js.Value) {<br>	value1 := js.Global().Get(&quot;document&quot;).Call(&quot;getElementById&quot;, i[0].String()).Get(&quot;value&quot;).String()<br>	value2 := js.Global().Get(&quot;document&quot;).Call(&quot;getElementById&quot;, i[1].String()).Get(&quot;value&quot;).String()<br><br>	int1, _ := strconv.Atoi(value1)<br>	int2, _ := strconv.Atoi(value2)<br><br>	js.Global().Get(&quot;document&quot;).Call(&quot;getElementById&quot;, i[2].String()).Set(&quot;value&quot;, int1-int2)<br>}</pre><p>Our finished index.html should look something like this:</p><pre>&lt;!doctype html&gt;<br>&lt;!--<br>Copyright 2018 The Go Authors. All rights reserved.<br>Use of this source code is governed by a BSD-style<br>license that can be found in the LICENSE file.<br>--&gt;<br>&lt;html&gt;<br><br>&lt;head&gt;<br>	&lt;meta charset=&quot;utf-8&quot;&gt;<br>	&lt;title&gt;Go wasm&lt;/title&gt;<br>&lt;/head&gt;<br><br>&lt;body&gt;<br><br>	&lt;script src=&quot;wasm_exec.js&quot;&gt;&lt;/script&gt;<br><br>	&lt;script&gt;<br>		if (!WebAssembly.instantiateStreaming) { // polyfill<br>			WebAssembly.instantiateStreaming = async (resp, importObject) =&gt; {<br>				const source = await (await resp).arrayBuffer();<br>				return await WebAssembly.instantiate(source, importObject);<br>			};<br>		}<br><br>		const go = new Go();<br>		let mod, inst;<br>		WebAssembly.instantiateStreaming(fetch(&quot;lib.wasm&quot;), go.importObject).then(async (result) =&gt; {<br>			mod = result.module;<br>			inst = result.instance;<br>			await go.run(inst)<br>		});<br><br>	&lt;/script&gt;<br><br>	&lt;input type=&quot;text&quot; id=&quot;value1&quot;/&gt;<br>	&lt;input type=&quot;text&quot; id=&quot;value2&quot;/&gt;<br><br>	&lt;button onClick=&quot;add(&#39;value1&#39;, &#39;value2&#39;, &#39;result&#39;);&quot; id=&quot;addButton&quot;&gt;Add&lt;/button&gt;<br>	&lt;button onClick=&quot;subtract(&#39;value1&#39;, &#39;value2&#39;, &#39;result&#39;);&quot; id=&quot;subtractButton&quot;&gt;Subtract&lt;/button&gt;<br><br>	&lt;input type=&quot;text&quot; id=&quot;result&quot;&gt;<br><br>&lt;/body&gt;<br><br>&lt;/html&gt;</pre><h3>Conclusion</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*o9ehcShXgOwJGqiqtzldyA.png" /><figcaption>The finished product!</figcaption></figure><p>So, in this tutorial, we managed to learn how we can compile our Go programs into WebAssembly using the new v1.11 of the Go language. We created a really simple calculator that exposes functions from our Go code to our frontend and also does a bit of DOM parsing and manipulation to boot.</p><p>Hopefully, you found this article useful/interesting! If you did, then I’d love to hear from you in the comments section below. If you wish to support my work then please feel free to subscribe to my YouTube channel: <a href="https://youtube.com/tutorialedge">TutorialEdge</a>.</p><p><em>Originally published at </em><a href="https://tutorialedge.net/golang/go-webassembly-tutorial/"><em>tutorialedge.net</em></a><em>.</em></p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fupscri.be%2Fdde502%3Fas_embed%3Dtrue&amp;dntp=1&amp;url=https%3A%2F%2Fupscri.be%2Fhackernoon%2F&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=upscri" width="800" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/3c851dac986ab6dbb2d1aaa91205a8eb/href">https://medium.com/media/3c851dac986ab6dbb2d1aaa91205a8eb/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=70fff89db6a9" width="1" height="1" alt=""><hr><p><a href="https://medium.com/hackernoon/go-webassembly-building-a-calculator-tutorial-70fff89db6a9">Go WebAssembly — Building a Calculator Tutorial</a> was originally published in <a href="https://medium.com/hackernoon">HackerNoon.com</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How I scaled my static website to a global market for a fraction of the cost on AWS]]></title>
            <link>https://medium.com/a-cloud-guru/scaling-your-static-site-to-a-global-market-for-a-fraction-of-the-cost-on-aws-12d23f30f877?source=rss-eb71d34fbe09------2</link>
            <guid isPermaLink="false">https://medium.com/p/12d23f30f877</guid>
            <category><![CDATA[cloud-computing]]></category>
            <category><![CDATA[serverless]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[web-hosting]]></category>
            <category><![CDATA[aws]]></category>
            <dc:creator><![CDATA[Elliot Forbes]]></dc:creator>
            <pubDate>Wed, 15 Aug 2018 16:03:42 GMT</pubDate>
            <atom:updated>2018-09-25T20:56:00.321Z</atom:updated>
            <content:encoded><![CDATA[<h4>Migrating from a server-based solution to S3 static website resulted in increased performance and decreased costs</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*51bJ76Bd17cqFgY6gmnxaA.png" /></figure><p>For the past few years, I’ve been building a website to host <a href="https://tutorialedge.net/">free programming tutorials</a>. This site started in 2014 as a passion project, and represents thousands of hours of blood, sweat, and tears — it’s my pride and joy.</p><p>Now, I realize it’s not perfect — but it’s free, and provides an opportunity for me to hone my own skills while encouraging others to learn programming. My passion project has turned into a successful and growing side project which needed to scale without costing me a fortune.</p><h4>In the beginning — there was a server</h4><p>The site originated in 2014 as nothing more than a handful of game development tutorials which reflected my interests. By January of 2016, the site had reached a grand total of 150–200 users per day.</p><p>Over the years this traffic continued to grow, and the demand on my solitary server continued to increase. The additional traffic required an upgrade to my Linode server instances — this allowed the Laravel-based website to continue running without collapsing for the short-term.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ORP0Xm_53rM9ZLi14Pts8g.png" /></figure><p>After a very long time building out my site in Laravel and playing with things to determine what works, I ended up migrating to Hugo — a static site builder that doesn’t require PHP or a fancy framework.</p><p>At the time, moving to Hugo improved the speed of the site to a fair extent. It also reduced server costs since I was no longer relying on a MySQL database to host the content. I also ended up drinking the AWS kool-aid and migrating my site onto a T2 micro instance.</p><p>The architecture diagram for the site looked something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Nu7uSinQiNNmwr9ppjwpIQ.png" /></figure><p>For a while, things were quiet.</p><p>My build pipeline was sorted. I was writing new content and trying to improve the site. And the traffic was growing. It was a peaceful time.</p><h4><strong>The challenge — performance</strong></h4><p>After a while, I started to notice the website began to slow down. Website performance was starting to noticeably degrade, and I had an inkling as to why this was happening.</p><p>When using the popular Website Speed Test tool Pingdom, at peak usage times, I was seeing massive Wait times of around <strong>0.8s on average</strong> before all of the other requests would start resolving. The final load time was roughly 1.5–2.5 seconds.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/990/1*EyeVHjRL4o_Lnp-LGtQ9zQ.png" /></figure><p>Notice in this example how there’s a large wait time on the second request after the DNS resolution. These metrics were taken during a period of fairly minimal traffic, but it provides some insight on the performance degradation.</p><h4>The plan — considering my options</h4><p>Going forward, I figured there were two choices:</p><ol><li>Spin up a load balancer and an auto-scaling group, and deploy my application to however many T2 instances were needed.</li><li>Migrate away from T2 and into S3 with CloudFront.</li></ol><p><strong>Option 1<br></strong>The first option was very appealing to me. I had recently been learning Terraform and creating resilient Go APIs, and had already configured my site to use LetsEncrypt for HTTPS only traffic.</p><p>However, this option would not be cheap. This approach meant increased costs and idle CPU capacity with more management required. My AWS invoice was already creeping up every month as I worked with more services and built more tutorials — so I was apprehensive about adding more instances to my bill.</p><p><strong>Option 2<br></strong>The second option was something I thought would be far riskier. I’d have to find a way to migrate my live site from a T2 instance to an S3 bucket using CloudFront and Route53 on the front-end to manage traffic.</p><p>I’m a massive advocate of everything being encrypted, so it was a hard requirement that the site would continue to be served via HTTPS. Thankfully, this could easily be achieved by using Amazon’s ACM service and requesting a certificate using email verification</p><h4>The decision — migrate to a static site on S3</h4><p>The first port of call when it came to migrating my site was the CI/CD pipeline. This was incredibly simple with TravisCI and looks like this:</p><pre>language: python</pre><pre>install:</pre><pre>  - wget https://github.com/gohugoio/hugo/releases/download/v0.34/hugo_0.34_Linux-64bit.deb</pre><pre>  - sudo dpkg -i hugo*.deb</pre><pre>script:</pre><pre>  - hugo --buildDrafts</pre><pre>  - cp -r scripts public/</pre><pre>deploy:</pre><pre>  provider: s3</pre><pre>  ... all my S3 creds</pre><p>Every time someone commits to the master branch of my repo, this kicks-off a build and uploads it to my production S3 bucket.</p><p>Once the CI/CD pipeline was in place, I pushed through a simple change and ensured the bucket’s configuration was correct.</p><p>Et Voila! — the static files I would be serving were all there and ready to go.</p><p>After I was confident in the rest of my CloudFlare configuration and the Route 53 setup, I migrated the nameservers of my site to point to Amazon’s. After 24 hours I was good to go and I had successfully completed the migration. I could now decommission the original T2.micro instance.</p><p>When configuring the CloudFront distribution, I chose for my site to be cached and served from all possible edge locations.</p><p>This means that whenever someone from Australia comes and requests my site, a cache lookup will be done first at the edge location — and if it’s a cache hit, the site’s load time will be incredibly low. Otherwise, it’ll be served from the origin S3 bucket and cached for any subsequent requests.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9eTAdjkyoV1koHs0bm-93g.png" /><figcaption>The map of all of AWS’ Edge locations</figcaption></figure><p>Whilst this option costs more, the performance increases are definitely worth it and the total cost will still fall well short of my previous monthly spend.</p><blockquote>Special thanks to <a href="https://twitter.com/alanr194">Alan Reid</a> who helped me with the S3, CloudFront and Route 53 configuration</blockquote><h4>The results — faster, cheaper, better!</h4><p>After the migration was complete, the results were astounding. I had dropped my load time from around 1.5s — 2.5s down to a <strong>freaking 234ms</strong> as highlighted in the below screenshot. This is an insane performance improvement.</p><p>Have a look at these request times, the largest proportion of time is now spent on DNS resolution and even then it’s just over 0.1s.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MaFf0IsAqv0lSlYJHu_cFA.png" /><figcaption>We are no longer in Wait hell!</figcaption></figure><p>According to Pingdom, my site is now faster than 99% of all other sites tested. And as you can see, there are still a few more things that I can improve upon!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Uxm9WXFN82my0qTInPoAqQ.png" /></figure><p>But the most astounding thing about this migration is that not only has it drastically improved the performance of my site, it’s also improved the resiliency as I’m no longer reliant on a single T2 instance keeping me going.</p><p>Regarding the economics, the costs of hosting the site have been reduced from roughly $20/month down to around $7/month:</p><ul><li>Route53 is about $0.50/month</li><li>CloudFront is about $6.50/month</li><li>And a small amount is being spent on S3 bucket storage</li></ul><p>This is an incredible saving and puts my mind at ease. If ever should the stars align and my site sees a massive surge of traffic, it will be resilient without costing me a fortune!</p><h4>Conclusion</h4><p>Having sampled numerous different ways of deploying and hosting a static site, this is without a doubt one of the best approaches.</p><p>It’s that perfect blend of performance and cost. The simplicity makes it an accessible choice for everyone looking to host their own sites that are massively resilient and hugely scalable.</p><p><a href="https://youtube.com/tutorialedge">TutorialEdge</a></p><p>Hopefully, you found this thrilling tale of turbulence and triumph interesting! If you did and wish to support me then please feel free to check out my YouTube channel or add me on <a href="https://www.linkedin.com/in/elliotforbes/">LinkedIn</a>!</p><figure><a href="https://acloud.guru/membership?utm_source=medium&amp;utm_medium=blog&amp;utm_content=&amp;utm_campaign="><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OyGo8x0Zg516xq40xhji1Q.png" /></a></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=12d23f30f877" width="1" height="1" alt=""><hr><p><a href="https://medium.com/a-cloud-guru/scaling-your-static-site-to-a-global-market-for-a-fraction-of-the-cost-on-aws-12d23f30f877">How I scaled my static website to a global market for a fraction of the cost on AWS</a> was originally published in <a href="https://medium.com/a-cloud-guru">A Cloud Guru</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a Network Command Line Interface in Go]]></title>
            <link>https://medium.com/hackernoon/building-a-network-command-line-interface-in-go-fd57b31df3fe?source=rss-eb71d34fbe09------2</link>
            <guid isPermaLink="false">https://medium.com/p/fd57b31df3fe</guid>
            <category><![CDATA[go]]></category>
            <category><![CDATA[interface-in-go]]></category>
            <category><![CDATA[build-a-go-interface]]></category>
            <category><![CDATA[network-command-line-go]]></category>
            <category><![CDATA[golang]]></category>
            <dc:creator><![CDATA[Elliot Forbes]]></dc:creator>
            <pubDate>Mon, 30 Jul 2018 10:16:01 GMT</pubDate>
            <atom:updated>2019-04-27T10:54:08.781Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nSXJUJT9XXMxwm54sIyV5w.jpeg" /><figcaption>credit — <a href="http://www.lighthouseabudhabi.org/global-network/">http://www.lighthouseabudhabi.org/global-network/</a></figcaption></figure><p>In this article, we are going to be building a very simple Command Line Interface in Go using the urfave/cli package available on Github here: <a href="https://github.com/urfave/cli">https://github.com/urfave/cli</a>.</p><p>I’ve been doing one or two domain migrations across various hosting providers recently and thought it would be a cool idea to build a tool or program that could be used to query things like the Nameservers of a website, the CNAMEs, the IP addresses and so on.</p><p>The overall aim of this particular tutorial is to give you an idea as to how you can build your own CLIs that could do a wide variety of other things such as <a href="https://hackernoon.com/tagged/network">network</a> monitoring, image manipulation and so on.</p><blockquote><em>The full code for this tutorial can be found here: </em><a href="https://github.com/TutorialEdge/Go/tree/master/go-cli-tutorial"><em>TutorialEdge/Go/go-cli-tutorial</em></a></blockquote><h3>Popular Projects</h3><p><a href="https://hackernoon.com/tagged/golang">Golang</a> is growing massively in popularity and we have seen large enterprise companies such as Hashicorp adopt the language for quite a number of different tools and systems. And for good reason, the design of Go lends itself incredibly well to these styles of application and the ability to cross-compile a binary executable for all major platforms easily is a massive win.</p><h3>Getting Started</h3><p>Let’s create a new directory on our computer called go-cli/ or something along those lines. We’ll be creating a directory structure that will look like this for our project:</p><pre>go-cli/<br>- pkg/<br>- cmd/my-cli/<br>- vendor/<br>- README.md<br>- ...</pre><blockquote><em>This structure follows the widely accepted </em><a href="https://github.com/golang-standards/project-layout"><em>Go project layout</em></a><em> guide available on Github.</em></blockquote><h3>Getting Into The Code</h3><p>Now that we’ve got a basic project structure down, we can start to work on our application. First of all, we will need a new file called cli.go within our new cmd/my-cli/ directory. We’ll populate this with a very simple Hello World type of application and use this as the base from which we’ll grow from.</p><pre>// cmd/my-cli/cli.go<br>package main<br><br>import (<br>  &quot;fmt&quot;<br>)<br><br>func main() {<br>  fmt.Println(&quot;Go CLI v0.01&quot;)<br>}</pre><p>We can then attempt to run this from our project’s root directory by typing:</p><pre>➜ go run cmd/my-cli/cli.go Go CLI v0.01</pre><p>Excellent, we’ve got the makings of our new CLI sorted, let’s now look at how we can add a few commands and make it somewhat useful.</p><h3>Our First Command</h3><p>As we’ll be using the urfave/cli package we’ll need to download this package locally in order to use it, we can do that through a simple go get command like so:</p><pre>$ go get github.com/urfave/cli</pre><p>Now that we have the necessary package, let’s update our cli.go file to use this package and create a new CLI application for us:</p><pre>// cmd/my-cli/cli.go<br>import (<br>  &quot;log&quot;<br>  &quot;os&quot;<br><br>  &quot;github.com/urfave/cli&quot;<br>)<br><br>func main() {<br>  err := cli.NewApp().Run(os.Args)<br>  if err != nil {<br>    log.Fatal(err)<br>  }<br>}</pre><p>When we run this now, you’ll see it fleshes out our programs response and adds things like the version, how we use the cli and the various commands we have at our disposal.</p><pre>➜  go run cmd/my-cli/cli.go<br>NAME:<br>   cli - A new cli application<br><br>USAGE:<br>   cli [global options] command [command options] [arguments...]<br><br>VERSION:<br>   0.0.0<br><br>COMMANDS:<br>     help, h  Shows a list of commands or help for one command<br><br>GLOBAL OPTIONS:<br>   --help, -h     show help<br>   --version, -v  print the version</pre><p>Awesome, this is very quickly starting to look like a more polished project and not just a minor side project!</p><p>We can now start adding our own Commands. Each of these commands will match up with one of our tests, so we’ll have one command: ns which, when triggered and supplied with a url will go off and lookup the Name Servers of that particular host.</p><p>Our final list of commands will look something like this:</p><ul><li>ns - will retrieve the name servers</li><li>cname - will lookup the CNAME for a given host</li><li>mx - will lookup the mail exchange records for a given host</li><li>ip - will lookup the IP addresses for a given host.</li></ul><p>Nice and simple, let’s get started by creating our first command:</p><pre>package main<br><br>import (<br>	&quot;fmt&quot;<br>	&quot;log&quot;<br>	&quot;net&quot;<br>	&quot;os&quot;<br><br>	&quot;github.com/urfave/cli&quot;<br>)<br><br>func main() {<br>	app := cli.NewApp()<br>	app.Name = &quot;Website Lookup CLI&quot;<br>	app.Usage = &quot;Let&#39;s you query IPs, CNAMEs, MX records and Name Servers!&quot;<br><br>	// We&#39;ll be using the same flag for all our commands<br>	// so we&#39;ll define it up here<br>	myFlags := []cli.Flag{<br>		cli.StringFlag{<br>			Name:  &quot;host&quot;,<br>			Value: &quot;tutorialedge.net&quot;,<br>		},<br>	}<br><br>	// we create our commands<br>	app.Commands = []cli.Command{<br>		{<br>			Name:  &quot;ns&quot;,<br>			Usage: &quot;Looks Up the NameServers for a Particular Host&quot;,<br>			Flags: myFlags,<br>			// the action, or code that will be executed when<br>			// we execute our `ns` command<br>			Action: func(c *cli.Context) error {<br>				// a simple lookup function<br>				ns, err := net.LookupNS(c.String(&quot;url&quot;))<br>				if err != nil {<br>					return err<br>				}<br>				// we log the results to our console<br>				// using a trusty fmt.Println statement<br>				for i := 0; i &lt; len(ns); i++ {<br>					fmt.Println(ns[i].Host)<br>				}<br>				return nil<br>			},<br>		},<br>	}<br><br>	// start our application<br>	err := app.Run(os.Args)<br>	if err != nil {<br>		log.Fatal(err)<br>	}<br>}</pre><p>We can then try to run this by typing:</p><pre>$ go run cmd/my-cli/cli.go ns --url tutorialedge.net</pre><p>This should then return the name servers for my site and print them out in the terminal. We can also do a run the help command which will show us exactly how to use our new command within our CLI.</p><h3>Looking up IP Addresses</h3><p>All of our command definitions will look really similar within our program, with the exception of how we go about printing out the results. The net.LookupIP() function returns a slice of IP addresses and as such we’ll have to iterate over these in order to print them out in a nice fashion:</p><pre>{<br>	Name:  &quot;ip&quot;,<br>	Usage: &quot;Looks up the IP addresses for a particular host&quot;,<br>	Flags: myFlags,<br>	Action: func(c *cli.Context) error {<br>		ip, err := net.LookupIP(c.String(&quot;host&quot;))<br>		if err != nil {<br>			fmt.Println(err)<br>		}<br>		for i := 0; i &lt; len(ip); i++ {<br>			fmt.Println(ip[i])<br>		}<br>		return nil<br>	},<br>},</pre><h3>Looking up our CNAME</h3><p>We can then add our cname command which will use the net.LookupCNAME() function with our passed in host and return a single CNAME string which we can then print out:</p><pre>{<br>	Name:  &quot;cname&quot;,<br>	Usage: &quot;Looks up the CNAME for a particular host&quot;,<br>	Flags: myFlags,<br>	Action: func(c *cli.Context) error {<br>		cname, err := net.LookupCNAME(c.String(&quot;host&quot;))<br>		if err != nil {<br>			fmt.Println(err)<br>		}<br>		fmt.Println(cname)<br>		return nil<br>	},<br>},</pre><h3>Looking up MX Records</h3><p>Finally, we want to be able to query the Mail Exchange records for our given host, we can do that by using the net.LookupMX() function and passing in our host. This will return a slice of mx records which, like our IPs, we’ll have to iterate over in order to print out:</p><pre>{<br>	Name:  &quot;mx&quot;,<br>	Usage: &quot;Looks up the MX records for a particular host&quot;,<br>	Flags: myFlags,<br>	Action: func(c *cli.Context) error {<br>		mx, err := net.LookupMX(c.String(&quot;host&quot;))<br>		if err != nil {<br>			fmt.Println(err)<br>		}<br>		for i := 0; i &lt; len(mx); i++ {<br>			fmt.Println(mx[i].Host, mx[i].Pref)<br>		}<br>		return nil<br>	},<br>}, </pre><h3>Building our CLI</h3><p>Now that we have a basic CLI up and running, it’s time to build it so that we can use it in anger.</p><pre>$ go build cmd/my-cli/cli.go</pre><p>This should compile a cli executable which we can then run like so:</p><pre>$ ./cli help<br>NAME:<br>   Website Lookup CLI - Let&#39;s you query IPs, CNAMEs, MX records and Name Servers!<br><br>USAGE:<br>   cli [global options] command [command options] [arguments...]<br><br>VERSION:<br>   0.0.0<br><br>COMMANDS:<br>     ns       Looks Up the NameServers for a Particular Host<br>     cname    Looks up the CNAME for a particular host<br>     ip       Looks up the IP addresses for a particular host<br>     mx       Looks up the MX records for a particular host<br>     help, h  Shows a list of commands or help for one command<br><br>GLOBAL OPTIONS:<br>   --help, -h     show help<br>   --version, -v  print the version</pre><p>As you can see, all of our commands have been successfully listed in the COMMANDS section of the output.</p><h3>Conclusion</h3><p>So, in this tutorial we’ve managed to successfully build a really simple, yet effective CLI using the urface/cli package from Github. The CLI can be cross-compiled for any of the major operating systems with minimal fuss and it features all the functionality that you would expect from a production-grade command line interface.</p><p>If you liked my article and wish to support me, then please feel free to check out my YouTube Channel:</p><p><a href="https://youtube.com/tutorialedge">TutorialEdge</a></p><p><em>Originally published at </em><a href="https://tutorialedge.net/golang/building-a-cli-in-go/"><em>tutorialedge.net</em></a><em>.</em></p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fupscri.be%2Fdde502%3Fas_embed%3Dtrue&amp;dntp=1&amp;url=https%3A%2F%2Fupscri.be%2Fhackernoon%2F&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=upscri" width="800" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/3c851dac986ab6dbb2d1aaa91205a8eb/href">https://medium.com/media/3c851dac986ab6dbb2d1aaa91205a8eb/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fd57b31df3fe" width="1" height="1" alt=""><hr><p><a href="https://medium.com/hackernoon/building-a-network-command-line-interface-in-go-fd57b31df3fe">Building a Network Command Line Interface in Go</a> was originally published in <a href="https://medium.com/hackernoon">HackerNoon.com</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a HackerNews Clone in VueJS]]></title>
            <link>https://medium.com/hackernoon/building-a-hackernews-clone-in-vuejs-f746b1eb2aa4?source=rss-eb71d34fbe09------2</link>
            <guid isPermaLink="false">https://medium.com/p/f746b1eb2aa4</guid>
            <category><![CDATA[hacker-news-vuejs]]></category>
            <category><![CDATA[hacker-news-clone]]></category>
            <category><![CDATA[hacker-news-vuejs-clone]]></category>
            <category><![CDATA[hacker-news]]></category>
            <category><![CDATA[vuejs]]></category>
            <dc:creator><![CDATA[Elliot Forbes]]></dc:creator>
            <pubDate>Mon, 16 Jul 2018 11:26:01 GMT</pubDate>
            <atom:updated>2019-04-27T10:55:01.055Z</atom:updated>
            <content:encoded><![CDATA[<p>In this project series we are going to be building a simplistic version of <a href="https://hackernoon.com/tagged/hackernews">HackerNews</a> in <a href="https://hackernoon.com/tagged/vuejs">VueJS</a> from scratch. This will hopefully cover some of the key topics you will need to become familiar with if you wish to develop your own applications using the framework.</p><p>After playing a lot with VueJS over the past few months and I’m a huge fan of the framework. Thus, I thought it would be the perfect candidate to base the first ever project series for TutorialEdge on. I hope you enjoy this and find it worthwhile!</p><p>Throughout this project we will be integrating with the <a href="https://github.com/HackerNews/API">HackerNews API</a> so that we can focus on the frontend JavaScript code and not have to worry about implementing the backend.</p><h3>Video Tutorial</h3><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FAdGsg8kBVkM%3Ffeature%3Doembed&amp;url=http%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DAdGsg8kBVkM&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FAdGsg8kBVkM%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/41091d6732df3f590c3c6dfad884de9e/href">https://medium.com/media/41091d6732df3f590c3c6dfad884de9e/href</a></iframe><p>The goal of this project is to show you everything it takes to build a complete, fully functioning frontend application using the VueJS framework. We’ll walk through everything from setting up your project, to hitting a few APIs in order to retrieve any articles and rendering these nicely on our site!</p><p>We’ll cover the following topics:</p><ul><li>Setting up a VueJS project using the vue-cli</li><li>Creating your first component</li><li>An introduction to routing in your Single Page Application</li><li>Hitting API endpoints in your components</li><li>Dynamic routing in a Single Page Application</li></ul><p>If you wish for me to extend this or feel I should expand upon anything then please let me know by tweeting me: <a href="https://twitter.com/elliot_f">@Elliot_F</a></p><h3>Github Source Code!</h3><blockquote>The full source code for this project can be found here: <a href="https://github.com/elliotforbes/hackernews-vuejs">elliotforbes/hackernews-vuejs</a></blockquote><p>Feel free to steal this and use this for your own personal gain, but if you do end up making a million off it, I expect at least a beer if you ever stumble across me in the wild!</p><h3>The Finished Product!</h3><p>After following this series through to completion, you should hopefully have a finished product that will look a little something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*_Fy_vbdc_hHGKToR.png" /></figure><p>Nothing too fancy I am sure you will agree, but a very decent starting point that developers new to the framework can extend and make their own!</p><blockquote><em>Check out the next tutorial in this series here: </em><a href="https://tutorialedge.net/projects/hacker-news-clone-vuejs/part-1-setting-up-vuejs-project/"><em>Part 1 — Setting Up Your Development Environment</em></a></blockquote><h3>Tutorials</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/0*5CzcRjHNjI3fOiWD.png" /></figure><p><a href="https://tutorialedge.net/projects/hacker-news-clone-vuejs/part-1-setting-up-vuejs-project/">Part 1 — Setting Up Our VueJS Project 3 Minutes</a></p><p><a href="https://tutorialedge.net/projects/hacker-news-clone-vuejs/part-1-setting-up-vuejs-project/">In this tutorial, we are going to be setting up our basic project that will form the base of our HackerNews clone</a></p><p><a href="https://tutorialedge.net/projects/hacker-news-clone-vuejs/part-1-setting-up-vuejs-project/">Published: Monday, Mar 19, 2018</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/0*CdIYzA0U2FXmMH4v.png" /></figure><p><a href="https://tutorialedge.net/projects/hacker-news-clone-vuejs/part-2-creating-few-components/">Part 2 — Creating a Few Components 5 Minutes</a></p><p><a href="https://tutorialedge.net/projects/hacker-news-clone-vuejs/part-2-creating-few-components/">In this tutorial, we are going to be creating a few components to our HackerNews clone and fleshing out our project.</a></p><p><a href="https://tutorialedge.net/projects/hacker-news-clone-vuejs/part-2-creating-few-components/">Published: Monday, Mar 19, 2018</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/0*c0umtzQjTLXnHU3b.png" /></figure><p><a href="https://tutorialedge.net/projects/hacker-news-clone-vuejs/part-3-adding-a-few-routes/">Part 3 — Adding a Few Routes To Our App 4 Minutes</a></p><p><a href="https://tutorialedge.net/projects/hacker-news-clone-vuejs/part-3-adding-a-few-routes/">In this tutorial, we are going to setting up our application to use the vue router and add a few simple routes to our application.</a></p><p><a href="https://tutorialedge.net/projects/hacker-news-clone-vuejs/part-3-adding-a-few-routes/">Published: Monday, Mar 19, 2018</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/0*hPtqdKzolJDMw7Gz.png" /></figure><p><a href="https://tutorialedge.net/projects/hacker-news-clone-vuejs/part-4-hitting-an-api/">Part 4 — Hitting The HackerNews API 5 Minutes</a></p><p><a href="https://tutorialedge.net/projects/hacker-news-clone-vuejs/part-4-hitting-an-api/">In this tutorial, we are going to start hitting some APIs and showing some of the top stories on our HackerNews clone.</a></p><p><a href="https://tutorialedge.net/projects/hacker-news-clone-vuejs/part-4-hitting-an-api/">Published: Monday, Mar 19, 2018</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/0*_5ee9RmjgVO87OUg.png" /></figure><p><a href="https://tutorialedge.net/projects/hacker-news-clone-vuejs/part-5-single-news-article-view/">Part 5 — Viewing Individual News Articles 6 Minutes</a></p><p><a href="https://tutorialedge.net/projects/hacker-news-clone-vuejs/part-5-single-news-article-view/">In this tutorial, we are going to add some more routes and components to our application to view individual news items and the comments</a></p><p><a href="https://tutorialedge.net/projects/hacker-news-clone-vuejs/part-5-single-news-article-view/">Published: Monday, Mar 19, 2018</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/0*FkwUkiAlzYTxfNZ2.png" /></figure><p><a href="https://tutorialedge.net/projects/hacker-news-clone-vuejs/part-6-advanced-components/">Part 6 — Advanced Components 5 Minutes</a></p><p><a href="https://tutorialedge.net/projects/hacker-news-clone-vuejs/part-6-advanced-components/">In this tutorial, we are going to split out our application into more components and use some of the more advanced features such as props and transitions.</a></p><p><a href="https://tutorialedge.net/projects/hacker-news-clone-vuejs/part-6-advanced-components/">Published: Monday, Mar 19, 2018</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/0*t9DGLDwBsTcSx0I2.png" /></figure><p><a href="https://tutorialedge.net/projects/hacker-news-clone-vuejs/part-7-managing-state-with-vuex-vuejs/">Part 7 — Managing State with Vuex in your VueJS Applications 7 Minutes</a></p><p><a href="https://tutorialedge.net/projects/hacker-news-clone-vuejs/part-7-managing-state-with-vuex-vuejs/">In this tutorial, we are going to look at how you can manage state within your VueJS applications using vuex</a></p><p><a href="https://tutorialedge.net/projects/hacker-news-clone-vuejs/part-7-managing-state-with-vuex-vuejs/">Published: Monday, Mar 19, 2018</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/0*6p2se6_LXo_EIazP.png" /></figure><p><a href="https://tutorialedge.net/projects/hacker-news-clone-vuejs/">2 Minutes</a></p><p><a href="https://tutorialedge.net/projects/hacker-news-clone-vuejs/">In this series we look at how you can build your own HackerNews clone using Vue.JS</a></p><p><a href="https://tutorialedge.net/projects/hacker-news-clone-vuejs/">Published: Monday, Mar 19, 2018</a></p><p><em>Originally published at </em><a href="https://tutorialedge.net/projects/hacker-news-clone-vuejs/"><em>tutorialedge.net</em></a><em>.</em></p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fupscri.be%2Fdde502%3Fas_embed%3Dtrue&amp;dntp=1&amp;url=https%3A%2F%2Fupscri.be%2Fhackernoon%2F&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=upscri" width="800" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/3c851dac986ab6dbb2d1aaa91205a8eb/href">https://medium.com/media/3c851dac986ab6dbb2d1aaa91205a8eb/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f746b1eb2aa4" width="1" height="1" alt=""><hr><p><a href="https://medium.com/hackernoon/building-a-hackernews-clone-in-vuejs-f746b1eb2aa4">Building a HackerNews Clone in VueJS</a> was originally published in <a href="https://medium.com/hackernoon">HackerNoon.com</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building Real-time ReactJS Applications with Socket.Io]]></title>
            <link>https://codeburst.io/building-real-time-reactjs-applications-with-socket-io-7bd8775eb122?source=rss-eb71d34fbe09------2</link>
            <guid isPermaLink="false">https://medium.com/p/7bd8775eb122</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[software]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Elliot Forbes]]></dc:creator>
            <pubDate>Sun, 15 Jul 2018 14:55:15 GMT</pubDate>
            <atom:updated>2018-07-17T16:33:37.266Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*St5crFq6GyphKeEs6ak96w.png" /></figure><p>In this article, we are going to be looking at how you can implement real-time websocket-based communication within your ReactJS web application.</p><h3>Why Websockets?</h3><p>I’ve covered this numerous times in previous articles on this site as to why we should use websockets within our applications.</p><p>The benefits are numerous, and when we use socket.io, these benefits can be realized with minimal added complexity.</p><p>Let’s have a look at a real-life example. Imagine you had a real-time monitoring application that continually polled the status of the fleet of 100 servers that currently host your services.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cA3WC_hUkFC4bL9kn4e3ZA.png" /><figcaption>Image credit: <a href="https://devcentral.f5.com/articles/load-balancing-websockets">https://devcentral.f5.com/articles/load-balancing-websockets</a></figcaption></figure><p>With traditional HTTP requests, you could send out a new HTTP request to validate the status of a server once every minute. Whilst this would certainly work, it would mean you would be creating a new TCP connection 100 times per minute for your fleet of servers. This adds up to 6000 times per hour, or <strong>144,000 </strong>per day.</p><p>If each of these services sent back a JSON status response that looked like this:</p><pre>{ <br>    &quot;service_status&quot;: &quot;good&quot;, <br>    &quot;last_issue&quot;: &quot;2018-07-15T13:51:53.415Z&quot; <br>}</pre><p>Each HTTP response from our server could amount to roughly 200–300Kb in size <em>per</em> response. This equates to roughly <strong>41GB of network traffic per day,</strong> just on polling the status of your 100 servers.</p><p>This represents a somewhat conservative example if you start to consider the scale of some large enterprises. These enterprises might maintain tens, if not hundreds of thousands of servers and by utilizing HTTP to poll status, you could very quickly find yourself chocking the network for minimal added value.</p><p>If we migrated our application to use websockets, we could reduce this to 100 TCP connections that would be persistent throughout the course of the day.</p><p>These bi-directional connections could then be used to push status updates only when they start seeing issues. As such, you could find yourself drastically saving the amount of network traffic generated.</p><h3>Scaffolding our Application</h3><p>To avoid any confusion, we’ll be creating a blank react application using the create-react-app tool:</p><pre>$ create-react-app my-new-app</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gtpri1a4LUw40CdaUD6yeg.png" /><figcaption>Our newly created React App!</figcaption></figure><p>Once this has gone away and successfully created our application, we can then proceed to install the necessary libraries we will need in order to build our real-time application.</p><pre>$ yarn add socket.io-client</pre><h3>Our api.js File</h3><p>Now that we have all of our dependencies installed and ready to go, it’s time to define the file that will perform our websocket connection and also allow us to interact with the newly opened connection.</p><p>Create a new file within an api directory and add the following:</p><pre>// api/index.js <br>import openSocket from &#39;socket.io-client&#39;; <br>const socket = openSocket(&#39;http://localhost:5000/&#39;); </pre><pre>function connect(cb) { <br>    socket.on(&#39;chat&#39;, (message) =&gt; { <br>        console.log(message) <br>        cb(message); <br>    }) <br>} </pre><pre>export { connect }</pre><p>You’ll notice within this that we have first imported the necessary socket.io-client library. We’ve then created a socket connection that connects to the hard coded http://localhost:5000 backend websocket service.</p><p>Below this we’ve then defined a connect() function which takes in a callback as a parameter. Within the body of this function we define what happens when our frontend client receives a socket.io message of type chat. In this case we simply log what was received and then call our inputted callback function, passing in the received message to that.</p><h3>Updating your App.js</h3><p>So, now that we have defined our connect function within our api/index.js file, we can start the process of connecting to our websocket endpoint and sending and receiving messages.</p><p>We’ll first have to import our new api/index.js file at the top of our app.js file. Once we’ve done that we can define a constructor if there isn’t one already and within that we’ll be calling connect() and passing in a callback function that will simply console.log our returned message.</p><pre>import React, { Component } from &#39;react&#39;;<br>import logo from &#39;./logo.svg&#39;;<br>import &#39;./App.css&#39;;<br>import { connect } from &#39;./api&#39;;<br><br>class App extends Component {<br><br>  constructor(props) {<br>    super(props);<br>    connect(message =&gt; {<br>      console.log(message);<br>    });<br>  }<br><br>  render() {<br>    return (<br>      &lt;div className=&quot;App&quot;&gt;<br>        &lt;header className=&quot;App-header&quot;&gt;<br>          &lt;img src={logo} className=&quot;App-logo&quot; alt=&quot;logo&quot; /&gt;<br>          &lt;h1 className=&quot;App-title&quot;&gt;Welcome to React&lt;/h1&gt;<br>        &lt;/header&gt;<br>        &lt;p className=&quot;App-intro&quot;&gt;<br>          To get started, edit &lt;code&gt;src/App.js&lt;/code&gt; and save to reload.<br>        &lt;/p&gt;<br>      &lt;/div&gt;<br>    );<br>  }<br>}<br><br>export default App;</pre><p>Once you’ve done this, save your file and reload your application within your browser. You should see within your console tab the words hello world returned when you make a successful connection to the backend websocket server.</p><h3>Our Backend System</h3><p>Our backend system is very simple, but can be extended to your heart’s content. This will actually be the base for a new series that I’m building on creating a real-time chat application that runs on AWS. If you want to stay tuned to when this comes out then please feel free to follow me on twitter: <a href="https://twiter.com/Elliot_f">@Elliot_f</a></p><p>So, the below code simply sets up a socket.io endpoint that runs on http://localhost:5000. When a user connects to this websocket endpoint, it will then log that a new client has successfully connected and it will emit a Hello World message back to the client.</p><pre>import express from &quot;express&quot;;<br>const app = express();<br>const server = require(&#39;http&#39;).createServer(app);<br>const io = require(&#39;socket.io&#39;)(server);<br><br>io.set(&#39;origins&#39;, &#39;*:*&#39;);<br>io.on(&#39;connection&#39;, async (socket: any) =&gt; {<br>	console.log(&quot;Client Successfully Connected&quot;);<br><br>	io.emit(&#39;chat&#39;, &quot;hello world&quot;);<br>})<br><br>server.listen(5000, () =&gt; {<br>	console.log(&quot;Backend Server is running on http://localhost:5000&quot;);<br>})</pre><p>I recommend checking our the backend directory here: <a href="https://github.com/TutorialEdge/react-typescript-real-time-chat/tree/241b6b404a821e7566e5353a4605db9b107a83f5">TypeScript/react-typescript-real-time-chat</a> which features the appropriate configuration files needed to run this on your own machine.</p><p>When you create the necessary config files and perform a yarn install or npm install, you will then be able to build and run this project by calling:</p><p>This will concurrently watch for any code changes, compiles our TypeScript files down to a dist/ directory and subsequently runs these files using nodemon.</p><p>Once this is started and you are running your frontend application, you should be able to see Hello World being successfully logged in your browser inspector when you connect to the backend.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vq-iYsyewy7e-C6oYSvsJA.png" /><figcaption>Our App, successfully communicating with our backend!!</figcaption></figure><h3>Conclusion</h3><p>So, hopefully this tutorial has been successful in getting you started with both React and Socket.io so that you can build up your own complex, awesome real-time applications.</p><p>If you need any additional help, or would like to know more, please feel free to tweet me <a href="https://twitter.com/@elliot_f">@Elliot_f</a> or let me know in the comments section below.</p><p><em>Originally published at </em><a href="https://tutorialedge.net/javascript/react/react-socket-io-tutorial/"><em>tutorialedge.net</em></a><em>.</em></p><figure><a href="http://bit.ly/codeburst"><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*i3hPOj27LTt0ZPn5TQuhZg.png" /></a></figure><blockquote>✉️ <em>Subscribe to </em>CodeBurst’s<em> once-weekly </em><a href="http://bit.ly/codeburst-email"><strong><em>Email Blast</em></strong></a><strong><em>, </em></strong>🐦 <em>Follow </em>CodeBurst<em> on </em><a href="http://bit.ly/codeburst-twitter"><strong><em>Twitter</em></strong></a><em>, view </em>🗺️ <a href="http://bit.ly/2018-web-dev-roadmap"><strong><em>The 2018 Web Developer Roadmap</em></strong></a><em>, and </em>🕸️ <a href="http://bit.ly/learn-web-dev-codeburst"><strong><em>Learn Full Stack Web Development</em></strong></a><em>.</em></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7bd8775eb122" width="1" height="1" alt=""><hr><p><a href="https://codeburst.io/building-real-time-reactjs-applications-with-socket-io-7bd8775eb122">Building Real-time ReactJS Applications with Socket.Io</a> was originally published in <a href="https://codeburst.io/">codeburst</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Cloud Agnostic Architecture is a Myth]]></title>
            <link>https://medium.com/hackernoon/cloud-agnostic-architecture-is-a-myth-53eac80be85d?source=rss-eb71d34fbe09------2</link>
            <guid isPermaLink="false">https://medium.com/p/53eac80be85d</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[cloud-computing]]></category>
            <dc:creator><![CDATA[Elliot Forbes]]></dc:creator>
            <pubDate>Mon, 18 Jun 2018 21:11:45 GMT</pubDate>
            <atom:updated>2019-04-27T10:56:02.970Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>Vendor lock-in — being locked into a specific cloud provider through the use of services specific to that cloud provider</blockquote><p>I’ve been working with my head in the cloud for the past 2 years now and one thing is pretty certain — Cloud-agnostic <a href="https://hackernoon.com/tagged/architecture">Architecture</a> is a <a href="https://hackernoon.com/tagged/myth">Myth</a>, at least in a conventional sense.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/396/1*9IUlRHqoUXUfGUHhT8wcmA.jpeg" /><figcaption>Overly-generic stock photo to represent vendor lock-in.</figcaption></figure><p>In this article, I’ll be discussing the current state of cloud services and how being truly cloud-agnostic is not only something we can’t quite achieve, but why it isn’t necessarily something you may want to achieve.</p><h3>Dockerizing Your Application</h3><p>Our first port of call is Docker. I am a seriously massive advocate for containerization technologies such as Docker and have recently given talks demonstrating how these technologies could massively improve the way we build and deploy software.</p><p>One of the key advantages of Docker that I like to highlight, is its ability to reduce the friction when it comes to migrating from one cloud service provider to another. You specify everything that your application needs to run in terms of runtime, environment variables and any setup scripts and you are able to start said container almost everywhere. I say *almost* as there are some very minor exceptions such as Windows-only images etc.</p><p>This essentially means that the Python application we need to run can be containerized and dropped into any managed container service such as ECS. The underlying container platform will then manage the container lifecycle and provide additional benefits such as logging and monitoring should we wish.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2f7MvYF3q_M9PBABYwztbQ.png" /></figure><p>The underlying OCI-compliant container runtime will then handle any discrepancies between hosts and run your application as you intended it to run with minimal fuss.</p><blockquote>When it comes to trying to avoid vendor lock-in, containerization is an incredibly low-hanging fruit.</blockquote><h3>The Growth of Terraform</h3><p>Terraform is the latest “shiny thing” that I’ve had the pleasure of playing with in my travels and I’m very much a fan of the CLI and how it lets you define your infrastructure as code.</p><p>You can specify the provider you wish to use as well as the access keys and secret keys and when you run terraform apply , the CLI will the go away and spin up the appropriate infrastructure for you to then deploy on top of:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9c8624d3ff8a6315c6d8533c90db0fbf/href">https://medium.com/media/9c8624d3ff8a6315c6d8533c90db0fbf/href</a></iframe><p>If you subsequently need to tear down your infrastructure, you can with ease using the terraform destroy command, which is a command that sounds freaking awesome.</p><blockquote>If you are looking for a good reference manual on Terraform, then I highly recommend the Yevgeniy’s book:</blockquote><p><a href="https://amzn.to/2t7UW1P">Terraform: Up and Running: Writing Infrastructure as Code</a></p><p>Now, this is great for spinning up your system’s required infrastructure on a specific cloud provider, but this means we will have to write multiple Terraform scripts for each of the distinct cloud providers.</p><p>This isn’t entirely out of the question, but we then have to maintain these scripts going forward in such a manner that we can ensure their correctness should we need to fail over to a given provider. There also needs to be a certain level of knowledge regarding the underlying platform in order to be explicit about what instance types you are spinning up or what size these instances need to be.</p><p>From an application developer’s point-of-view, you may not necessarily have to, or want to, care about what AMI you are creating your t2.micro instances from, you may just care about developing your application and having somewhere stable to run said application so that it can serve your paying customers.</p><h4>The Nuances between Services</h4><p>One of the potential solutions to this that I have seen mentioned is to implement a layer of abstraction above all cloud service providers and essentially define your application’s underlying infrastructure as a series of blocks. Essentially an extension on top of Terraform that would have the ability to spin up cloud-platform agnostic infrastructure.</p><p>This Terraform-esque abstraction layer would then have the job of interfacing with whichever cloud platform it so chooses and spinning up said infrastructure. This would let you define say, a simple web app, as 1x “Load Balancer” and 2x “Small Server”.</p><p>To some, this seems like the obvious solution, but when it comes to implementing this abstraction layer and dealing with the nuances between how different services are exposed, this becomes next to impossible.</p><p>Trying to handle this at an application level would be next to impossible and your codebase would be riddled with hundreds, if not thousands of conditional flags in order to cover a large number of services. Could we abstract this into a service-broker or SDK? Maybe, but it just shifts our initial problem left.</p><h3>Kubernetes</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*asW0I729N8Pe8E-WWDPaRA.jpeg" /></figure><p>So, Kubernetes is incredible and I’ve discussed some of its potential benefits for Enterprise environments here:</p><p><a href="https://medium.com/@elliot_f/can-kubernetes-revolutionize-the-enterprise-world-86f4ec147d1f">Can Kubernetes Revolutionize The Enterprise World?</a></p><p>Kubernetes, in combination with Docker and Terraform, may actually be somewhat of a good answer when it comes to attempting to be agnostic. It’s also something that has been explored by a number of different companies and individuals and we are starting to see managed solutions come about such as Triton.</p><p><a href="https://www.joyent.com/blog/triton-kubernetes-multicloud">Multi-cloud Kubernetes with Triton | Joyent</a></p><p>These federated kube-clusters (klusters?) can then be treated as an amalgamous lump of compute that can then run and manage any container-based applications you may wish to run.</p><p>The biggest advantage of this is that application developers need just worry about how they want their application to look and does abstract away the underlying infrastructure.</p><p>But then this isn’t perfect, these services are still very young and have yet to hit the mainstream. It’ll most likely be a while before these services become mature enough to be picked up by larger enterprises.</p><h3>The Value of Managed Services</h3><blockquote>Vendor lock-in — The art of leveraging specific services from a cloud provider in order to provide value to clients</blockquote><p>One of the biggest things I’ve seen people disregard when talking about vendor lock-in, is the fact that there is a huge advantage in leveraging these managed services for your own gain.</p><p>When considering the use of these managed services, development teams need to weigh up how much of an advantage these services provide and consider how much of a disadvantage they are subsequently put at by locking themselves into said service.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/810/1*5hFKU7blT5nm9qQgptAPHw.png" /><figcaption>Building a service like this yourself would take years of work. With managed services, it can be done in a day!</figcaption></figure><p>If service X from AWS, or Azure, or GCP can provide you a massive advantage over your competition then it surely doesn’t make sense to avoid using said service because of vendor lock-in. If anything, by actively leveraging these services you may find yourself able to iterate faster with new ideas and push the bounds of what we are currently capable of.</p><p>If we consider the likes of AWS’ RDS, if we were to attempt to host our own database instance on an EC2 instance and manage this ourselves, we would end up spending hundreds of hours attempting to achieve the same level of resiliency, or performance that an out-of-the-box RDS offering provides.</p><p>This article goes into a more detailed comparison for self-hosted vs RDS:</p><p><a href="https://cloud.netapp.com/blog/migrating-mysql-database-ec2-hosted-amazon-rds">MySQL Database Migration: EC2 Hosted vs. Amazon RDS</a></p><h3>Conclusion</h3><p>Whilst vendor lock-in is something you should <em>somewhat </em>consider when designing and developing your applications, I would put far more stock in the advantage of using said managed service as long as you understand its constraints fully. Being mindful of the fact that you are relying heavily on these services is far more valuable in the long run and can give you an edge should you leverage these in appropriate ways.</p><p>As it stands however, being able to remain fully agnostic of cloud provider is just not possible. More work will have to be done in order to provide that level of abstraction above said provider and at this point it’s just turtles all the way down.</p><p>Hopefully, you enjoyed these ramblings, if you don’t agree with anything or would like to add to this then please feel free to let me know in the comments section below!</p><p>If you’d like to support me then feel free to follow me on twitter: @Elliot_f or subscribe to my YouTube channel!</p><p><a href="http://youtube.com/tutorialedge">TutorialEdge</a></p><p>N.B — This article was peer-reviewed by my good friend <a href="https://twitter.com/alanr194">Alan Reid</a> so please @ him if you see any mistakes!</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fupscri.be%2Fdde502%3Fas_embed%3Dtrue&amp;dntp=1&amp;url=https%3A%2F%2Fupscri.be%2Fhackernoon%2F&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=upscri" width="800" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/3c851dac986ab6dbb2d1aaa91205a8eb/href">https://medium.com/media/3c851dac986ab6dbb2d1aaa91205a8eb/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=53eac80be85d" width="1" height="1" alt=""><hr><p><a href="https://medium.com/hackernoon/cloud-agnostic-architecture-is-a-myth-53eac80be85d">Cloud Agnostic Architecture is a Myth</a> was originally published in <a href="https://medium.com/hackernoon">HackerNoon.com</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>