<?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 Supun Muthutantrige on Medium]]></title>
        <description><![CDATA[Stories by Supun Muthutantrige on Medium]]></description>
        <link>https://medium.com/@supun.muthutantrige?source=rss-2d38e52e3f23------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*FuXpfHQPevYU6ocdXpkalw.jpeg</url>
            <title>Stories by Supun Muthutantrige on Medium</title>
            <link>https://medium.com/@supun.muthutantrige?source=rss-2d38e52e3f23------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 06:20:17 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@supun.muthutantrige/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[Building an Offline-First Web App with create-react-app]]></title>
            <link>https://medium.com/bitsrc/building-an-offline-first-web-app-with-react-and-firebase-d3bdcda8f1d8?source=rss-2d38e52e3f23------2</link>
            <guid isPermaLink="false">https://medium.com/p/d3bdcda8f1d8</guid>
            <category><![CDATA[firebase]]></category>
            <category><![CDATA[offline-first]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[progressive-web-app]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Supun Muthutantrige]]></dc:creator>
            <pubDate>Wed, 14 Oct 2020 18:51:43 GMT</pubDate>
            <atom:updated>2020-10-14T20:00:46.921Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gxD-qWltc03abmOuL3mMWQ.jpeg" /></figure><p>Progressive Web Apps (PWA) has become the new norm in building web apps. In contrast to traditional web apps, PWA provides a unique set of features for the mobile web, providing a naive-like experience. One of the core features of PWA is offline-first capability.</p><p>As the name suggests, web apps require proper network connectivity to function correctly. For mobile devices, internet connection isn’t always stable. Sudden loss of network connection, more often than not, would corner users into a frustration halt.</p><p>With offline-first, developers can design web apps with unique user flows and commit specific actions once the connection is established. This way, the user experience would be much more appealing and less frustrating.</p><blockquote>How frustrating it would be if a user had to rewrite a thousand words long blog article, just because there was a connectivity issue.</blockquote><p>We could think of similar scenarios where the offline-first feature could become vital for your users, depending on your application domain.</p><p>This article will showcase a simple yet powerful use case of transforming a React web app to offline-first, using Google Firebase for the application backend and Hosting.</p><h3>Overview</h3><h4>Progressive Web App</h4><p>As you are already aware, PWA combines a collection of technologies to build better mobile web applications. Let’s have a look at the main requirements to develop a PWA.</p><p>To create a PWA, you need to fulfill the following.</p><ul><li><strong>HTTPS</strong> — The app should be served over a secure network.</li><li><strong>Service Worker</strong> — A script that handles network calls and asset caching.</li><li><strong>A Manifest file</strong> — A JSON file with design details.</li></ul><p>Here, the Service Worker specification is the key to making a web app offline-first and progressive. It provides content and asset caching ability in a web browser. This caching mechanism allows the app to function offline.</p><h4>Firebase</h4><p>Firebase is a comprehensive mobile and web app development platform that allows building production-ready apps in no time. Firebase Hosting provides the free hosting capability for web apps developed using all three major frontend frameworks and libraries (React, Angular and Vue). We could also host multiple sites in a single Firebase project. It allows us to deploy non-offline-first and offline-first versions of the same React app.</p><h3>Building the App</h3><p>The best way to understand an offline-first web app is to implement and experience the difference. So let’s build an offline-first web app using React.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wCZyZvJkfdVqIoPoqUDbzw.gif" /></figure><p>Our sample app consists of the following main features,</p><ol><li>List of todo tasks.</li><li>Add new tasks.</li><li>Complete and delete the individual tasks.</li></ol><p>The todo list is rendered using an API call. It is to see how external connectivity would affect the overall app behavior when the network connection is lost.</p><h4>Prerequisites</h4><blockquote>Before getting started, make sure the latest versions of Node and Firebase CLI is installed.</blockquote><h4>1. Creating a Simple React Todo App</h4><p>Use the Create React App to create a simple React application boilerplate. Once done, it will generate the following folder structure,</p><pre>my-app<br>├── README.md<br>├── node_modules<br>├── package.json<br>├── .gitignore<br>├── public<br>│   ├── favicon.ico<br>│   ├── index.html<br>│   ├── logo192.png<br>│   ├── logo512.png<br>│   ├── manifest.json<br>│   └── robots.txt<br>└── src<br>    ├── App.css<br>    ├── App.js<br>    ├── App.test.js<br>    ├── index.css<br>    ├── index.js<br>    ├── logo.svg<br>    └── serviceWorker.js</pre><p>If you look at the folder structure, you can see the serviceWorker.js file in the generated file list. Here, the Service Worker provides the asset caching capability allowing web apps to be offline-first.</p><p>Enabling/Disabling Service Worker is done inside the index.js file (<a href="https://github.com/smut90/offline-first-react-app/blob/before_offline/src/index.js">full implementation</a>). Switching serviceWorker.unregister() to serviceWorker.register() will opt you into using the Service Worker.</p><blockquote>It’s always a good practice to share your reusable components<strong> </strong>using <a href="https://bit.dev/"><strong>Bit</strong></a> (<a href="https://github.com/teambit/bit">Github</a>). This way, you can maximize code reuse, collaborate with your team on independent components, and build apps that scale.</blockquote><blockquote>I shared my <a href="https://bit.dev/eden/offline-todo-app/todo/">Todo</a> component. You can test it for yourself and even install it in your project.</blockquote><figure><a href="https://bit.dev/eden/offline-todo-app/todo"><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QGrLKlR7c_IRXlCcYmADiw.png" /></a><figcaption>My <a href="https://bit.dev/eden/offline-todo-app/todo">Todo component</a> shared on <a href="https://bit.dev/">Bit.dev</a></figcaption></figure><h4>2. Deploy to Firebase Hosting</h4><p>Once the implementation is done, let’s deploy our web app in Firebase hosting. First, let’s build a production version of the React app, which we plan to deploy.</p><pre>yarn build</pre><p>Initialize Firebase and follow the steps to configure hosting and other settings.</p><pre>firebase init</pre><p>Then, deploy the production build.</p><pre>firebase deploy --only hosting</pre><p>The deployed web app can be found here (<a href="https://offline-first-react-app.firebaseapp.com/">link</a>).</p><h4>3. Change the App to Allow Offline-first</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*P_SEfG3-DznkNNZDfRE5pQ.gif" /><figcaption>Without offline-support</figcaption></figure><p>The above version doesn’t support the offline-first feature. Hence, when network connectivity is lost, the web app is not functional.</p><p>Now, let’s make the app offline-first by opting in to use the Service Worker. Change serviceWorker.unregister() to serviceWorker.register() in index.js (<a href="https://github.com/smut90/offline-first-react-app/blob/after_offline/src/index.js">source</a>).</p><p>Repeat the commands given in <strong>Step 2</strong> again to build and deploy the changes to Firebase hosting.</p><p>After deploying the offline-capable web app, let’s analyze its behavior in comparison to the previous.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OGVKrrdUXK-OaRa4noTy8w.gif" /><figcaption>With offline-support</figcaption></figure><p>You can directly experience that the app works as if the connection is available. The only difference the user could notice is that the saved list is not rendered as before. You see this error because the API call is failing due to the connectivity issue. But the application is still usable, and the user experience would be much more positive.</p><p>If you like to compare these applications, you can find the hosted version of the offline enabled and disabled applications in the links below.</p><ul><li>Offline-first enabled web app (<a href="https://offline-enabled.firebaseapp.com/">link</a>)</li><li>Offline-first disabled web app (<a href="https://offline-disabled.firebaseapp.com/">link</a>)</li></ul><h3>Source Code</h3><p>If you like to try out on your own, you can find the complete source code <a href="https://github.com/smut90/offline-first-react-app/tree/before_offline">here</a>. The project consists of two main branches before_offline and after_offline . The branch before_offline contains the implementation for the offline feature disabled app version and after_offline branch includes the source code for the offline feature enabled version.</p><p>The credit also goes to the example React Todo App (<a href="https://github.com/samgamage/todo-react">ref</a>), which I used as the base to create a version for this article.</p><h3>Summary</h3><p>Overall, I believe you get the essence of making an offline-first web app and how to create one using React and Firebase.</p><p>As you have seen, building an offline-first web application isn’t complex anymore. The well-defined patterns and support from PWA features allow any web developer to create these apps. Besides, using Firebase makes it even simpler where you don’t need to worry about the heavy lifting of hosting and managing the application and its storage.</p><p>Finally, if you have any questions regarding the example I built, please ask in the comments below. Cheers!</p><h3>Related Stories</h3><ul><li><a href="https://blog.bitsrc.io/what-is-a-pwa-and-why-should-you-care-388afb6c0bad">What is a PWA and why should you care?</a></li><li><a href="https://blog.bitsrc.io/5-reasons-to-choose-pwa-for-your-web-and-mobile-apps-515c6d0e784d">5 Reasons to Choose PWA for Your Web and Mobile Apps</a></li><li><a href="https://blog.bitsrc.io/how-to-easily-share-react-components-between-projects-3dd42149c09">How to Share React UI Components between Projects and Apps</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d3bdcda8f1d8" width="1" height="1" alt=""><hr><p><a href="https://medium.com/bitsrc/building-an-offline-first-web-app-with-react-and-firebase-d3bdcda8f1d8">Building an Offline-First Web App with create-react-app</a> was originally published in <a href="https://medium.com/bitsrc">Bits and Pieces</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to get screwed with Firebase]]></title>
            <link>https://medium.com/@supun.muthutantrige/how-to-get-screwed-with-firebase-34f591f5b98b?source=rss-2d38e52e3f23------2</link>
            <guid isPermaLink="false">https://medium.com/p/34f591f5b98b</guid>
            <category><![CDATA[firebase]]></category>
            <category><![CDATA[firestore]]></category>
            <category><![CDATA[google]]></category>
            <category><![CDATA[google-cloud-platform]]></category>
            <category><![CDATA[optimization]]></category>
            <dc:creator><![CDATA[Supun Muthutantrige]]></dc:creator>
            <pubDate>Sun, 06 Sep 2020 14:04:15 GMT</pubDate>
            <atom:updated>2020-09-06T14:04:15.325Z</atom:updated>
            <content:encoded><![CDATA[<p>Must know cost optimizations before start using Firebase</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*moaUXZaOzm3843jUiaHsAA.jpeg" /></figure><p>Firebase is a comprehensive mobile and web app development platform that allows building production-ready apps in no time. Since Firebase is backed by Google infrastructure the possibilities are endless.</p><p>As the saying “Great power comes with great responsibility”, Firebase is a powerful platform that has made several tools readily available to create large scale production-grade apps, thus, it’s our responsibility to understand which products we need and what best ways to use them. If not, pretty quickly we will be spending a significant amount without the expected ROI.</p><p>This article is about making you aware of the tricky parts and the best parts if you are expecting to use the platform.</p><h3>Things that could go wrong</h3><h4>Not knowing how the cost incurs</h4><p>Firebase costing can be tricky if not analyzed and used properly (link — <a href="https://firebase.google.com/pricing">pricing plan</a>). Before going live, it’s necessary to do a proper cost estimation and a usage prediction.</p><h4>Database design</h4><p>Firestore NoSql database is really powerful in many ways but has its limitations. You can structure your data to write everything in the same document or divide the data into multiple documents. The benefit of having everything in a single document is, it will reduce the read cost, but on the other hand, since the payload is large this would increase the network bandwidth cost and would freeze the Firestore web UI. Similarly, when everything is in one place, you may not be able to get the maximum use of Firestore builtin functionalities (searching, pagination, etc.).</p><h4>Unforeseen loops</h4><p>One of the most powerful features of Firebase is the Firebase trigger functions. This includes both Database and Storage triggers. Trigger functions can be categorized as, <strong>onCreate</strong>, <strong>onUpdate</strong>, <strong>onDelete</strong>, and <strong>onWrite</strong>. As I mentioned above, Firebase incurs a cost for every Firestore document read, write operation. Hence when designing trigger functions, you need to be careful not to generate read, write loops. This includes not knowing the appropriate trigger function to use. Let’s say you have written a trigger function (trigger A) to get triggered when a document (doc A) of a specific collection gets updated. If the underlying trigger flow in any way updates a document in the same collection (update doc A &gt; invoke trigger A &gt; update doc B &gt; invoke trigger B &gt; update doc A), this could generate an update loop, and pretty soon a significant cost will be incurred.</p><h4>Serverless Functions</h4><p>Firebase cloud functions (Google Serverless functions) can be categorized into multiple function types. HTTP functions, scheduler functions, and trigger functions are widely adopted depending on numerous use cases. I mentioned the importance of proper usage of trigger functions above. When it comes to Firebase HTTP functions and scheduler functions, it is important to be aware of the limitations when planning your system design. Firebase serverless HTTP functions <strong>aren’t good for CPU intensive work</strong>. Similarly, scheduler functions can only run for a maximum of <strong>9minutes</strong>. So if your design has heavy processing and long runnings jobs, these functions aren’t the ideal to be used.</p><h3>Power of Firebase (best things about the stack)</h3><h4>Triggers</h4><p>Triggers work as listeners which allows designing our system in different ways. We could assign complex behaviors to the system upon inserting, updating, or removing specific documents. We could connect underlying triggers to do things such as invoking 3rd party API calls, Firestore document manipulations, sending InApp notifications, etc.</p><h4>Notifications</h4><p>Firebase provides a rich set of features for mobile development. One such feature is the Notifications. Firebase SDK allows easy configuration for sending notifications from your code as well as Firebase UI itself has given the ability to send notifications. This is convenient when it comes to testing notifications in your app.</p><h4>Hosting</h4><p>Firebase hosting allows an environment for hosting your web app. Further, by default, it provides a secure URL to access your site, and it’s easy to configure a custom domain.</p><h4>User Management</h4><p>With Firebase Authentication, you could design your web, mobile apps to allow user signup/sign in with almost all major sign-in providers varying from simple Email/password, phone, Google, Facebook to Apple and anonymous logins.</p><h3>Making the best use of the free tier</h3><h4>Firestore Database</h4><p>Firebase realtime database, as well as NoSql database (Firestore), can be used for free. By making the best use of the free tier, we could design our structures, play around, and see the real potential it has before start spending. Firestore has powerful built-in features such as document searching, pagination, and the best thing is the data syncing between your mobile device and the database.</p><h4>Security rules to secure data</h4><p>Once we start storing domain-specific and sensitive data, it’s important to secure them. Firebase provides a data protection mechanism called security rules. With security rules, we could define various rules to read, write, update, and delete operations. With different data protection regulations coming into the picture, we must take necessary measures to protect customer data.</p><h4>User Management</h4><p>Our mobile or web apps can be easily configured to use Firebase authentication. With Firebase authentication, we could simplify user signup/sign-in flows, passwordless signup with email links, secure password store, forget password flow, and connecting 3rd party identity providers for systems with complex backends.</p><h4>Storage</h4><p>Under the Firebase free quota, we could store static assets in Firebase storage. For a basic web or mobile app version, this is more than enough to get things going.</p><blockquote>Cloud functions — Earlier Firebase let cloud functions (serverless functions) to be deployed without enabling billing, but with recent changes this is no longer available.</blockquote><p>Firebase is one of the most dominant platforms out there to build production-grade mobile and web apps. Therefore knowing how to use it will allow creating amazing products.</p><p>I hope this gives you some pointers into what to look for before start using the platform.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=34f591f5b98b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mind, the most powerful place in our universe]]></title>
            <link>https://medium.com/@supun.muthutantrige/mind-the-most-powerful-place-in-our-universe-5ea310aa58ba?source=rss-2d38e52e3f23------2</link>
            <guid isPermaLink="false">https://medium.com/p/5ea310aa58ba</guid>
            <category><![CDATA[behavior]]></category>
            <category><![CDATA[universe]]></category>
            <category><![CDATA[mindfulness]]></category>
            <category><![CDATA[humans]]></category>
            <category><![CDATA[emotions]]></category>
            <dc:creator><![CDATA[Supun Muthutantrige]]></dc:creator>
            <pubDate>Fri, 08 May 2020 19:14:17 GMT</pubDate>
            <atom:updated>2020-05-09T09:14:01.723Z</atom:updated>
            <content:encoded><![CDATA[<p><em>demystifying the greatest misconception</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/860/1*VogdAbHwPj3t0pVGLT2oKQ.jpeg" /></figure><h3>Mind over Matter</h3><p>Humans are the most complicated species to be found in our known universe. Scientists are yet to uncover the tremendous potential the human brain possesses.<br>Humans are capable of many things, and the capabilities differ from person to person. This makes us wonder, “why am I like everyone else?”, or “Why am I different from others?”</p><h4>1. Why we do what we do</h4><p>Without the brain we can’t see, hear, smell, taste, or even feel the touch. But is that all?<br>Think about a situation where you encounter a stranger, who comes shouting at you, that makes you uncomfortable, embarrassed, and makes you even feel like lashing out at him. That night you could only think about what happened, even thinking of finding the person and handing him over to the police, basically to see him begging your forgiveness.</p><p>The emotion roller-coaster you went through include different levels of negative feelings such as embarrassment, anger, stress, frustration, lack of sleep, revenge, etc.</p><p>The next day, on the same route, a few blocks before where you met the stranger on the previous day, you meet an old friend. After listening to your story, your friend mentions that the stranger you met is mentally unstable and known to barge into others. After hearing this, the frustration, anger, stress, and other negative emotions that bothered you thus far seems to go away. Even after confronting the same person for the 2nd time and hearing the exact unpleasant words, it doesn’t bother you anymore as it did.</p><p>So what caused this change? Scientists can reason out the different hormones which get released and the biological, physical impact those could have in our body when responding to fight or flight situations. But what they fail to reason out is, given a similar overwhelming situation (same unpleasant words, same physical movements from the stranger), why there were two different responses? This change relates to the knowledge of why the stranger did what he did, this awareness had a direct impact on the emotional, biological, and physical changes.</p><p><strong>So the awareness of why we do what we do could change our perception of understanding everything.</strong></p><h4>2. Mind your brain</h4><p>The original question, is there something more powerful than our brain? Considering the above scenario, we could think that there is something other than our brain which impacts our emotions, physical and biological changes. It’s called our mind, our subconsciousness, the state which understands and become aware of our surroundings and everything above.</p><p>One could argue, everything, each feeling, emotion, or action, is caused by a chemical change triggered in our brain. In other words, there is a biological explanation of whatever emotion we feel or might confront in the future. If that’s true, understanding every little detail about our brain should unlock the greatest mystery of human behavior, which would explain why we do what we do.</p><h4>3. Do we see what we look</h4><p>Think about your daily commute, how many vehicles, buildings, boards, people you pass by each day. Your eyes were not closed, the sight was there, the brain processed the signals as usual. But can you recall all of the number plates or at least one of them you saw? or the color of the shirt worn by the person standing in front of the tall building next to the old factory house? There were objects and your sight was normal. Your eyes were able to capture these objects and send signals to your brain. So, why didn’t you notice, although physical and biological factors of sight were fulfilled?</p><p>The main factor is our mind or consciousness. When we look at something, for us to notice, we need to think. If no specific thoughts were formed, we wouldn’t see what we looked at.</p><p>We all have that memory where we had to attend a boring lecture. We sit there, doing our own thing, pretending to listen but wondering in our thoughts. At the end of the lecture, we have no clue what it was all about. How could that possibly be? Every element which required the lecturer’s voice reaching our ears, and from there, to our brain was not obstructed. Brain processed everything we heard, but the one thing that is as important as the organ itself wasn’t aligned, because we didn’t listen, but only heard.</p><p><strong>Thus, our mind is the most crucial thing that is required for us to see what we look at and understand what we hear</strong>. In other words, there should be thoughts that associate with each of our physical activities to reach a state of awareness or understanding.</p><p>Although there is our physical brain, it is our mind that lets us reach a level of awareness. In other words, understanding why we do what we do require one’s mind.</p><blockquote><strong>Understanding the mind will help us understand why we do what we do, which would help demystify human behavior.</strong></blockquote><h4>4. The connection between our mind and brain/body</h4><p>If our brain and mind are two different things, how do our thoughts change when we feel hungry? why someone with mental instability can’t think properly? It feels like proper brain functioning is the only factor that helps organize our thoughts. Well, yes and no.</p><h4>The story of the blind man and the lame man</h4><p>To describe the connection between our mind and brain we could use one of our childhood stories. The story of the blind man and the lame man. Think of our brain as the blind man and our mind as the lame man. For both individuals to work, the support of each other is mandatory. Although our mind and brain are two different entities, our mind needs our brain to operate properly, else it could impact our thoughts.</p><p>When we are struggling with our thoughts, physical changes become apparent. A happy thought could make us feel lighter, energetic, and a tragic thought could temporarily paralyze our physical body.</p><p>There are scenarios such as, after hearing a piece of good news even amid a hungry crisis, someone could completely forget about the hunger they just had. Here, our thoughts have managed to change the way our body responds.</p><p>Multiple studies have shown that with proper practice, especially with things like meditation, we could gain control of our thoughts. When we know how to control our thoughts, we have better authority over how our body would react to certain events.</p><blockquote>What we think, we become — Lord Buddha</blockquote><h3>Understanding the universe</h3><p>In the previous section “Mind over matter” we understood,</p><ul><li>Realizing why we do what we do, helps understand human behavior</li><li>Understanding our mind helps understand why we do what we do</li><li>Understanding our mind involves understanding the difference between our mind and our brain</li></ul><p>Let’s dig deeper into understanding the mind.</p><p>Previously we understood that looking and seeing, hearing, and be attentive are separate things. The brain helps us look and hear, but it’s our mind that makes us see and listen. It’s the same for the other 3 senses (smell, taste, and touch) as well.</p><p>We are what we see, hear, smell, taste, and feel. The universe around us depends on what the 5 organs capture and the thoughts our mind helps organize.</p><p>As explained earlier (see section: <strong>3. Do we see what we look)</strong>, we may not notice everything we look while commuting since we didn’t think and decided to remember. It’s not that we didn’t look, but we didn’t think which drove us not to notice every image we saw. Since this occurs so fast (speed of our thoughts are far greater than the speed of light), looking and noticing (remembering) seems inseparable, but if we try to understand this sensation, we would realize that we could decide what we see although our eyes capture a particular scene.</p><p>To further simplify, think about how hearing works. Similar to looking at something and recognizing it, when we hear something, it involves our mind to listen.</p><blockquote>You could be getting a mouthful from your wife or husband, but you could decide not to listen to a single word they utter.</blockquote><p>There is a famous saying <strong>Go in one ear and out the other</strong>, and it is one of the best ways to understand, that, we have full authority over our thoughts.</p><p>Since we have full control over our thoughts, we can decide what to see, listen, smell, taste, and feel, with the involvement of our mind and thoughts. Through practice, we could further improve to gain more control over our thoughts.</p><p><strong>Since we could gain control over our thoughts, we could decide how we want things to be seen, listened to, smelled, tasted, and felt.</strong></p><h4>A different perception</h4><h4>Purpose of our daily routine, what makes us wake up every morning and work so hard?</h4><p>Humans have able to achieve amazing growth in the spectrum of science and technology with major scientific breakthroughs that expand theories across the quantum realm to massive galaxies, measuring the collision of massive black holes that occurred billions of years ago, even before life formed on earth. Further, we are in the process of figuring out the colonization of Mars, teleportation, and time travel.</p><p>Yes, we are an advanced and intelligent group of species that accomplished so much growth in the physical world. But when it comes to understanding the capacity of our brain and the power of our mind, science is still a long way away.</p><p>The problem with the unparalleled growth in the physical world is, it tends to lure humans into believing happiness, satisfaction relies on the next materialize thing they achieve. With this thought, we keep ourselves busy, thinking the next thing we achieve, the next thing we buy, the next destination we travel to would make us happy. What science has failed to show us is, fewer attachments we have, more satisfied we would be.</p><p>You must be wondering, that is such a lame excuse most people give to avoid hard work and doing the best someone could do to achieve more. Let’s think about some of the most successful people you think, in your field, and find out whether they are satisfied. If someone is satisfied, see what has made them satisfied, and if not, again find out even after achieving everything you assumed that would make you satisfied once you reach that level of success, why that hasn’t made them satisfied.</p><p>You could take some time off from your busy schedule and think, what would make me satisfied? What is the purpose of me working so hard day in day out? If you don’t have an answer yet, you should seriously give it a good thought and find some. If you have an answer, further analyze and see whether it would make you satisfied in all possible circumstances?</p><h4>Definition of satisfaction</h4><p>The fundamental assumption of satisfaction or being satisfied is, it is a state that could be reached, and once done, it wouldn’t change further in any way. Either you are satisfied or still haven’t reached there. Once you reached the level of satisfaction, it won’t change or go away.</p><p>One exercise to figure out, what would make you satisfy is to think of something you have or would expect to possess, which you assume would make you satisfied. It could be a material possession (house, factory, fortune 500 company, etc) or living, breathing being such as kids, wife, husband, partner, family, country, etc.</p><p>Now think, if the thing you believed, changed, or lost in any way, would that reshape your state of satisfaction? You could lose your house, factory, or the company you worked so hard to build, or you could lose someone you love. Would you still be able to be satisfied? or in contrast, if you get to know, that you are about to die, how easy would it be to leave behind things that made you satisfied?</p><p>On a much deeper level, we understand that things we believe would keep us happy and satisfied could change in an instant. Mental connections we create make our happiness and satisfaction tightly coupled to the existence and healthiness of such possessions. More connections we have, harder it would get, as there are too many variables that need to be well taken care of, but could go wrong at any point. If there are 10 things to keep you satisfied at all times, loosing at least one could make you unhappy, which doesn’t align with the ultimate definition of satisfaction. Thus, by now you should realize, satisfaction is hard to come by when there are stronger mental attachments|bonds|cravings|connections on material or human possessions.</p><h4>What we think will make us satisfied vs what actually would make us satisfied?</h4><p>Think about the time we dreamt of purchasing the next iPhone, MacBook Pro, Louis Vuitton handbag, Rolex watch, Chanel Grand Extrait perfume, or I8 Roadster? Did we ever stop there? Didn’t that make us even more eager to buy the next item in line? At what point would we stop or satisfied enough, that wouldn’t require the need to own anymore? If someone can say that, owing “this” and “this only” would make them satisfied for life, we all could work our asses off to try and own the same for ourselves and see whether it does. But the thing anyone claims should comply with the original definition of satisfaction, else, it is not worth our money and effort in our journey to find eternal satisfaction through material possessions.</p><p>You could keep on searching and even try and own such claims and understand for yourself that there isn’t a single most valuable item that would make us satisfied.</p><h4>So, what would make us satisfied?</h4><p>We are used to the perception of, work hard, earn as much as possible to own stuff that others could only dream of having. We work today with the hope of living tomorrow. So we are neither satisfied today nor would be tomorrow.</p><p>When there are fewer things to worry, less burden on us, which leads to less burden on our mind, therefore it all comes down to our thoughts. To keep our thoughts less poisonous, we should know, <strong>what to think and how to think</strong>.</p><p>As mentioned earlier, we are what we see, listen, smell, taste, and feel. When visual information, sound vibrations, odor, flavor, or touch reaches our brain through the respective organs, we could decide to think about it or just ignore it.</p><p>Naturally, what happens is, if the underlying sensation captured by the respective organ is different or significant, it tends to generate thoughts in our mind. In other words, when the associated sensation is slightly out of the ordinary, we tend to pay more attention hence think about it. If we don’t think (<em>see section: </em><strong><em>understanding the universe</em></strong>), there is a higher chance, that it would not imprint a memory resulting in a long-lasting image.</p><blockquote>We should realize that our mind is the most powerful and valuable asset which defines us. Thus, we should do whatever possible to keep it healthy and full of positive vibes.</blockquote><p>We could filter and decide what our thoughts should be. When we look at something bad (in any form, live or something shared via the internet), the best thing is to avoid thinking. We should shift our focus or think of something else if thoughts kept coming. The trick is, not to cling on to negative thoughts. The same applies to what we hear, smell, taste, and feel. If we keep feeding negative thoughts, our physique, and the behavior will start reflecting the negative outcome. Constantly feeding positive thoughts will have a positive impact on us.</p><p>What about when we directly encounter an overwhelming situation. Ignoring something that is not directly thrown at us is slightly less challenging. The difficult part would be to control our thoughts and ignore negative emotions when we are on the receiving end. That’s where understanding a situation comes in to play (<em>see section: </em><strong><em>Why we do what we do</em></strong>). If someone scolds us, embarrass us, or leave us for someone they feel better, or even physically abuse us, first we need to understand the reason or motive behind such actions. Talk to yourself and try to figure out the reason. It could be one of the following,</p><ol><li><strong>You are responsible for creating an environment which led to the situation — </strong>Such as making fun of someone, saying stuff which could tarnish personal reputation as such. Here you have to understand the pain you have caused due to your actions. So rather than feeding negative thoughts, you have to move on by realizing you are not all about evil and you will not hurt anyone hereafter. That way, you could think of the good you would do in the future, rather than the bad you did without realizing it.</li><li><strong>The person who abused you or embarrassed you has an unfortunate side nobody has seen — </strong>Similar to a scenario mentioned earlier (<em>see section: </em><strong><em>the stranger in Why we do what we do</em></strong>), there is a reason behind every action. The reason could be something to do with an unpleasant experience from the past, undergoing a tough situation at present, or having a mental sickness of some sort, which led to react in such a manner. After understanding other persons’ situation, rather than feeling bad or low about yourself, be kind, and be patient. You could ignore harsh words thrown at you by not listening or, avoid any physical confrontations by taking necessary precautions without getting angry. Always remember, feeding negative thoughts is as bad as (sometimes far poisons than) physical damages. You could always be proud of how you handled a tough situation by doing the right thing.</li></ol><p><strong>What about choosing someone else over you</strong> — One of the hardest things to get your head around is when someone close to you, choose someone over you. This could be the love of your life, your best friend, or anyone close to you. If you analyze the situation thoroughly, the root cause could align with the above points (1 or 2). Additional reasons could be, other people not realizing your value, selfishness, etc.</p><p>What you have to realize is, you cannot control everything or force people to stay in your life. Whatever the reasons are, maintaining peace of mind should matter the most. Whenever you get a thought about choosing someone else over you, shift your focus, think something else, try not to cling on to negative thoughts which would make you feel sad. If you don’t let worrying thoughts get into your mind, you wouldn’t be sad. As you get them, subside such thoughts by repeatedly, shifting focus, thinking of something else, until you completely overcome feeding negative thoughts. The more you feed, the stronger it will become, and the less you feed, the less disheartened you would become.</p><blockquote>When you keep on subsiding<strong> </strong>negative, hurtful thoughts, at one point it will completely go away.</blockquote><p><strong>Practicing to subside negative, hurtful thoughts as you get them is the trick to maintain peace of mind. When you keep repeating, thoughts which haunted your mind would eventually get neutralized.</strong></p><p>Knowing the importance of your mind and to keep it healthy, practicing what and how to think, would help maintain peace of mind. Peace of mind is the key to satisfaction. Acceptance, understanding, and realization of any given circumstance will help think right. Practice will make you perfect, hence practicing the art of letting go of negative thoughts will open up a world of positivity. This way, you will not run behind owning material possessions. You will not compare your life against someone else. You embrace change, nothing worries you, you realize that your mind matters the most.</p><p>Less material or human possessions mean less space for negative thoughts, less negative thoughts mean, more often than not you will have peace of mind. When there is peace of mind, you have reached a level of satisfaction. Hence, peace of mind leads to satisfaction.</p><p>Someone with as little material and human possessions, but, less worried about his present or future, is more satisfied compared to someone owing and living a luxurious life but worried about maintaining, safeguarding, and earning more.</p><p>Even people living a dream life could be satisfied if they know the art of maintaining peace of mind and aren’t worried about losing or letting go of material and human possessions at any time.</p><blockquote>Thus, satisfaction is all about maintaining the peace of mind, irrespective of your social status, wealth, race, caste, religion, etc.</blockquote><h4>Summary</h4><ul><li>Satisfaction is about peace of mind.</li><li>Peace of mind can be achieved via the ability to control any situation.</li><li>Controlling a situation includes having authority over our thoughts.</li></ul><p>Since this article has become lengthy, Let’s continue understanding the mysteries of our mind in another article.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5ea310aa58ba" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Write to Earn with medium from anywhere]]></title>
            <link>https://medium.com/@supun.muthutantrige/write-to-earn-with-medium-from-anywhere-1e7ddae2d242?source=rss-2d38e52e3f23------2</link>
            <guid isPermaLink="false">https://medium.com/p/1e7ddae2d242</guid>
            <category><![CDATA[stripe]]></category>
            <category><![CDATA[medium-partner-program]]></category>
            <category><![CDATA[publishing]]></category>
            <category><![CDATA[payments]]></category>
            <category><![CDATA[payment-gateway]]></category>
            <dc:creator><![CDATA[Supun Muthutantrige]]></dc:creator>
            <pubDate>Sun, 19 Apr 2020 15:41:16 GMT</pubDate>
            <atom:updated>2020-04-19T16:48:09.332Z</atom:updated>
            <content:encoded><![CDATA[<p>Link a stripe account even from a <strong>non stripe</strong> supported country</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*m6pXBFDNitef-VSsgbWC2g.png" /></figure><p>To earn for the great content you publish on medium, you should be part of the <strong>Medium Partner Program</strong>. To be part of Medium Partner Program, you need to link a <strong>Stripe account</strong>.</p><p>Things to look for</p><pre>- Create a bank account in a Stripe supported country<br>- Integrate stripe payments with Medium Partner Program<br>- Make your articles ready to accept payments<br>- Integrate with your local bank account</pre><blockquote>Stripe is an Online payment processing gateway for online businesses — <a href="https://stripe.com/">source</a></blockquote><p><strong>As of now, Stripe only supports very few countries and if you are a publisher outside these countries but still want to earn for the great content you write, this is the right place to get started.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/552/1*nbJL3YgP3y8wJCSeDPwPZw.png" /><figcaption>Stripe supported countries as of 19 Apr, 2020</figcaption></figure><p>It’s clear that we need to link a stripe account even from a non stripe supported country to be part of Medium Partner Program. Problem is how?</p><h3>Create a bank account in a Stripe supported country</h3><p>You must be thinking, wait a minute! that’s not possible, how can I create a bank account in a foreign/stripe supported country? But there is a way to achieve this.</p><h4>TransferWise</h4><p>You can create an account on TransferWise (use this link to get started — <a href="https://transferwise.com/invite/u/supunm7">link</a>) which could be used as a foreign bank account. Let’s create a transferwise account.</p><p>Once you signup for the first time, you’ll be redirected to a setup screen.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zKmy20aMVfPHKBqt4nQKwg.png" /></figure><p>click <strong>Continue</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1cR5ogANI1nv_Of0KRVA-w.png" /></figure><p>Select <strong>Personal</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fwWF7iVvh-6-G_DZ7sM7ew.png" /></figure><p>Fill in your details providing information based on your <strong>current residence. </strong>Although you need a foreign account, this step is to provide information on your current residence (you don’t need to provide details of a stripe supported country), this information will be used to verify your account.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bdSNR-_omb-g6_gQi5B1ew.png" /></figure><p>Since our intention is not to send money, once you reach this point you could simply close the setup page, by clicking the (x) close button.</p><p>Once done, you’ll be navigated to TranserWise main page.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Pzdo1fDWOy1sxIWO-_EXfg.png" /></figure><p>In order to get bank details, there are few more things to be done.</p><p>Add some money to your transferwise account. Minimum amount is EUR 20.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ul92Mx5GzWNX8W-E2hyeHA.png" /></figure><p>You could use any credit or debit card to add money to your transferwise account.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zOwdH8jHDm8cpAjvW4ztmg.png" /></figure><p>Once the amount is added, next step is to <strong>verify your identity</strong>. Here you need to provide verification documents and I used my passport. You could use either your <strong>passport</strong> or <strong>drivers</strong> <strong>license</strong>.</p><blockquote>Note: Please make sure to add clear high-quality images of the document, else it will delay the verification process.</blockquote><p>If all the document you upload are well within the guidelines, the confirmation will be received within 1–3 working days.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IOret_Jk6U9eTi7d-9eGXA.png" /></figure><p>Once you receive the confirmation, you could see your bank details as above. Now I have a legit bank account in <strong>Belgium</strong> although I’m from <strong>Sri Lanka</strong> ;)</p><p><strong>“We managed to overcome one of the biggest obstacles, legally owning a bank account in a foreign country where stripe is supported”.</strong></p><p>Now that we have a legit foreign bank account in a stripe supported country, let’s continue with the rest.</p><h3>Integrate stripe payments with Medium Partner Program</h3><p>To enable <strong>medium partner program,</strong> click on the profile icon on the top right corner and select medium partner program from the drop-down.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dqzbqXRMovlUAwZ7xggxaA.png" /></figure><p>Press <strong>Continue to payment setup</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QCWacoDah_kxMfM89YcfuA.png" /></figure><p>Next, press <strong>Set up payments on Stripe</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Vv4T_Zga_1M05yb-HQiTdA.png" /></figure><p>Once you get to this step, select the country where your bank account got created in Transferwise. Add a phone number (a phone number that you currently use) which you could receive a text message to activate the account. Then press <strong>Next</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/992/1*mMCoBoXgGbp0PEQ8FFZyjQ.png" /></figure><p>Enter the verification code received to your phone.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3hBnaLfUi8Yce4t0togORw.png" /></figure><p>Add your personal details, make sure to add your <strong>current residence</strong> and <strong>not the bank address in your transferwire account</strong>.</p><blockquote><strong>Tip</strong>: The postal code required as part of Home address is within <strong>4 digit</strong> range. If your city has more than 4, adding only the first 4 digits would get the job done.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/792/1*cMHJkpZ6D-5C7DkMSoTOww.png" /></figure><p>Add your website url, if you currently have one or</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*B2ETi0bmZPMttqeKJ2Ax9Q.png" /></figure><p>choose <strong>add a product description</strong> option instead. Press <strong>Next.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2jLNfswVBvpSEL8R1hbwXA.png" /></figure><p>Once you get to this step, you need to mention your transferwise account details. Mainly the <strong>Currency, Country </strong>and<strong> IBAN number</strong>. These values could be found in your transferwise account details page.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IOret_Jk6U9eTi7d-9eGXA.png" /></figure><p>You have now successfully integrated a stripe payment account. Next is to verify your medium partner account. Similar to the verification process in transferwise, medium also requires you to submit few identification documents.</p><p>Finally you need to update the taxpayer information based on the country you reside. Completing taxpayer information is mandatory before payouts. Hence don’t forget to complete, else it could lead to various restrictions.</p><h3>Make your articles ready to accept payments</h3><ul><li>for already published articles</li></ul><p>Press Edit article, then go to Manage distribution setting</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/405/1*SLN_GWZyyLLTCVGdsaQGyg.png" /></figure><p>Next tick <strong>Make my story eligible to earn..</strong> and press <strong>Save</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/440/1*lf7Ycg4qwOe0GY-6lL_7QA.png" /></figure><ul><li>for new articles</li></ul><p>After completing an article, you can select it to be eligible when publishing.</p><h3>Integrate with your local bank account</h3><p>One last thing before we wind up. To receive payments to your local bank account, you should be able to connect a local bank account with your transferwise account.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VxQVXgSwhtfcbf9_LCuiwQ.png" /></figure><p>Navigate to <strong>Recipients</strong> tab and press <strong>Add your bank account</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/564/1*UMNMKcs8g65pZnZUDA-fqQ.png" /></figure><p>Select a currency type and add your local bank details.</p><p>And with that you could publish your amazing content on medium and earn from anywhere in the world.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1e7ddae2d242" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A practical guideline to Firestore]]></title>
            <link>https://medium.com/@supun.muthutantrige/a-practical-guideline-to-firestore-50281732bcbc?source=rss-2d38e52e3f23------2</link>
            <guid isPermaLink="false">https://medium.com/p/50281732bcbc</guid>
            <category><![CDATA[cloud-firestore]]></category>
            <category><![CDATA[firebase]]></category>
            <category><![CDATA[nosql]]></category>
            <category><![CDATA[practical-guides]]></category>
            <category><![CDATA[google]]></category>
            <dc:creator><![CDATA[Supun Muthutantrige]]></dc:creator>
            <pubDate>Sat, 18 Apr 2020 05:16:52 GMT</pubDate>
            <atom:updated>2020-04-18T05:21:18.958Z</atom:updated>
            <content:encoded><![CDATA[<h3>A practical guide to Firestore</h3><p>Google Firebase NoSql database</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WMrLw9ZHuo6zXMzINtgLQA.png" /></figure><p>As part of the google Firebase article series, we will be exploring one of the most important products Firebase has to offer. <strong>The Firebase cloud Firestore</strong>. It is a NoSql database, different from its real-time database.</p><p>You could find plenty of articles on what is Firestore, differences and what not, so skipping all that and diving right into the practical aspect of things.</p><p>Things to look for</p><pre>- Overview To Firestore, getting to know the way around<br>- Add data manually<br>  - Firestore Collections<br>  - Add simple data types to Firestore document<br>  - Add an array to Firestore document<br>  - Add an Object/map to Firestore document<br>  - Add an Object/map array to Firestore document</pre><pre>- Add data using a script<br>- Creating the Framework<br>  - Acquiring service account for Firebase project<br>  - Finalizing the script</pre><h3>Overview To Firestore, getting to know the way around</h3><p>Once you navigate to the Firebase console (check out the overview article to get thus far — <a href="https://medium.com/@supun.muthutantrige/google-firebase-5d6f58ceca9">platform overview</a>), on the left hand side menu, you could see a <strong>Database</strong> tab. Once pressed, you’ll see a setup screen like the following.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*d95o19k9KK2vYPEjC4gk2g.png" /><figcaption>Cloud firestore — Setup screen</figcaption></figure><p>Click <strong>Create database</strong>, which will open up a popup menu.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZuSvhoMyUOLSzrRtAAIpqQ.png" /><figcaption>configuring firestore mode</figcaption></figure><p>In the 1st step, select the mode you wish to continue, select the <strong>production mode</strong> as we want our database to be production ready.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5qmGMoblm6g2uyEDu3G-7g.png" /><figcaption>configuring firestore location</figcaption></figure><p>Next step is to select the correct <strong>location</strong> for your database. As I mentioned in my preview article — (<a href="https://medium.com/@supun.muthutantrige/google-firebase-5d6f58ceca9">platform overview</a>), selecting the location for each product and the entire Firebase project is as important as it gets. Correct location will determine whether you spend more/less and how efficient querying is.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hYOof_YfkTlcO8Ge1ATJDw.png" /><figcaption>Firestore database screen</figcaption></figure><p>Once setting up is done, you’ll end up in a screen similar to be above.</p><h3>Add data manually</h3><p>Once the Firestore NoSql database is setup, you can start adding your data content. The core concept in Firestore is collections and documents.</p><h4>Firestore Collections</h4><p>A collection is nothing but a set of documents. In SQL (relational database) terms, a <strong>collection</strong> is similar to a <strong>database table</strong> and a <strong>document</strong> could be a <strong>row</strong> in the table.</p><p>Let’s create a collection called <strong>cities</strong>. The cities collection will have a JSON structure similar to the following. Understanding the JSON structure first, will make things easier to get your head around with the concept of collections and documents.</p><p>In the following JSON structure, there is an array of objects. Each object represents a document in Firestore. The array itself is the collection.</p><pre>{<br>  &quot;cities&quot;: [<br>    {<br>      &quot;id&quot;: &quot;SF&quot;,<br>      &quot;name&quot;: &quot;San Francisco&quot;,<br>      &quot;state&quot;: &quot;CA&quot;,<br>      &quot;country&quot;: &quot;USA&quot;,<br>      &quot;population&quot;: 860000,<br>      &quot;regions&quot;: [<br>        &quot;west_coast&quot;,<br>        &quot;norcal&quot;<br>      ],<br>      &quot;top_university&quot;: {<br>        &quot;name&quot;: &quot;Stanford&quot;,<br>        &quot;graduation_rate&quot;: &quot;94%&quot;,<br>        &quot;location&quot;: {<br>          &quot;lat&quot;: &quot;37.427828&quot;,<br>          &quot;long&quot;: &quot;-122.171302&quot;<br>        },<br>        &quot;subjects&quot;: [<br>          &quot;CS&quot;,<br>          &quot;Maths&quot;<br>        ]<br>      },<br>      &quot;universities&quot;: [<br>        {<br>          &quot;name&quot;: &quot;Stanford&quot;,<br>          &quot;subjects&quot;: [<br>            &quot;CS&quot;,<br>            &quot;Maths&quot;<br>          ]<br>        },<br>        {<br>          &quot;name&quot;: &quot;Berkeley&quot;,<br>          &quot;subjects&quot;: [<br>            &quot;Econ&quot;,<br>            &quot;Accounting&quot;<br>          ]<br>        }<br>      ]<br>    }<br>  ]<br>}</pre><p>Following illustration describes this concept further. Each document has a corresponding document id, in SQL terms, it is similar to having a unique primary key for each row record.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/613/1*3EmehcxbOdL8h4LeqVZnpA.png" /></figure><p>The array in our above JSON structure could be a map/object too.</p><pre>{<br>  &quot;cities&quot;: {<br>    &quot;SF&quot;: {<br>      &quot;name&quot;: &quot;San Francisco&quot;,<br>      &quot;state&quot;: &quot;CA&quot;,<br>      &quot;country&quot;: &quot;USA&quot;,<br>      &quot;population&quot;: 860000,<br>      &quot;regions&quot;: [<br>        &quot;west_coast&quot;,<br>        &quot;norcal&quot;<br>      ],<br>      &quot;top_university&quot;: {<br>        &quot;name&quot;: &quot;Stanford&quot;,<br>        &quot;graduation_rate&quot;: &quot;94%&quot;,<br>        &quot;location&quot;: {<br>          &quot;lat&quot;: &quot;37.427828&quot;,<br>          &quot;long&quot;: &quot;-122.171302&quot;<br>        },<br>        &quot;subjects&quot;: [<br>          &quot;CS&quot;,<br>          &quot;Maths&quot;<br>        ]<br>      },<br>      &quot;universities&quot;: [<br>        {<br>          &quot;name&quot;: &quot;Stanford&quot;,<br>          &quot;subjects&quot;: [<br>            &quot;CS&quot;,<br>            &quot;Maths&quot;<br>          ]<br>        },<br>        {<br>          &quot;name&quot;: &quot;Berkeley&quot;,<br>          &quot;subjects&quot;: [<br>            &quot;Econ&quot;,<br>            &quot;Accounting&quot;<br>          ]<br>        }<br>      ]<br>    }<br>  }<br>}</pre><p>The idea is to have a set of objects, where each object corresponds to a particular document in our firestore collection.</p><p>So with the understanding of the type of structure we are going to represent, Let’s create our collection in the Firebase console.</p><p>Click <strong>+ Start collection</strong> and type a collection name, cities in this case.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5qCNpVambgGj4Q9O7XnUtw.png" /></figure><p>Press next, and in this step you have to select a key for your document.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FlP-42CG9AL9utElnpKIgw.png" /></figure><p>Here, if you press <strong>AUTO-ID</strong>, it will generate a unique random id for your document. But in our use case, we will go ahead and provide an id.</p><h4>Add simple data types to Firestore document</h4><p>Since we have given an id to our document, let’s add the most simple data types to the city document. Add the following data portion from the JSON object, to the <strong>Firestore</strong> <strong>document</strong>.</p><pre>{<br>      &quot;id&quot;: &quot;SF&quot;,<br>      &quot;name&quot;: &quot;San Francisco&quot;,<br>      &quot;state&quot;: &quot;CA&quot;,<br>      &quot;country&quot;: &quot;USA&quot;,<br>      &quot;population&quot;: 860000,<br>}</pre><p>once inserted, it will look something like,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dSH4IfoHk0g0ZLQPs4HEoQ.png" /></figure><h4>Add an array to Firestore document</h4><p>next, let’s add more complex data types, starting from an array structure. We need to add the following JSON portion</p><pre>&quot;regions&quot;: [<br>        &quot;west_coast&quot;,<br>        &quot;norcal&quot;<br>],</pre><p>once done, the output view would be,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/621/1*ehkMh8QQbJdZ4NnDn3iEsw.png" /></figure><h4>Add an Object/map to Firestore document</h4><p>Let’s add the following map/object data structure.</p><pre>&quot;top_university&quot;: {<br>        &quot;name&quot;: &quot;Stanford&quot;,<br>        &quot;graduation_rate&quot;: &quot;94%&quot;,<br>        &quot;location&quot;: {<br>          &quot;lat&quot;: &quot;37.427828&quot;,<br>          &quot;long&quot;: &quot;-122.171302&quot;<br>        },<br>        &quot;subjects&quot;: [<br>          &quot;CS&quot;,<br>          &quot;Maths&quot;<br>        ]<br>},</pre><p>the relevant Firestore document portion would look like the following once the above structure is inserted.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/675/1*qjo8vQOkl-vZwZoI614xxw.png" /></figure><p>We did complete adding an array and a map/object complex data types to our Firestore document. Finally, let’s add an array of objects.</p><h4>Add an Object/map array to Firestore document</h4><p>Here we’ll be adding the following json data portion,</p><pre>&quot;universities&quot;: [<br>        {<br>          &quot;name&quot;: &quot;Stanford&quot;,<br>          &quot;subjects&quot;: [<br>            &quot;CS&quot;,<br>            &quot;Maths&quot;<br>          ]<br>        },<br>        {<br>          &quot;name&quot;: &quot;Berkeley&quot;,<br>          &quot;subjects&quot;: [<br>            &quot;Econ&quot;,<br>            &quot;Accounting&quot;<br>          ]<br>        }<br>      ]<br>}</pre><p>Once inserted, our Firestore document would have the following content,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/548/1*c0__zN8zGtN2tHgsHRXDXQ.png" /></figure><p>At the end, this is how the entire thing (collection and documents) would look like.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*E0QEk2yVesSFSIWtfAGtHQ.png" /></figure><p>Try adding few more documents on your own to get familiarized with data types and the structure itself.</p><h3>Add data using a script</h3><p>Imagine you have to add 5, 10, or even 50 documents to the cities collection. Doing the same thing would be a nightmare. The document structure we have used in much simpler. As it gets complex, entering data manually as we did before, would be impossible. Hence we need to come up with an automated approach. Coming up with a JSON payload with 5, 10, or 50 entries, is much simpler compared to adding all that to a Firestore collection manually.</p><p>Let’s use the same JSON structure, and create a script to add the data in the JSON structure to the cities Firestore collection.</p><pre>[cities.json]</pre><pre>{<br>  &quot;cities&quot;: {<br>    &quot;SF&quot;: {<br>      &quot;name&quot;: &quot;San Francisco&quot;,<br>      &quot;state&quot;: &quot;CA&quot;,<br>      &quot;country&quot;: &quot;USA&quot;,<br>      &quot;population&quot;: 860000,<br>      &quot;regions&quot;: [<br>        &quot;west_coast&quot;,<br>        &quot;norcal&quot;<br>      ],<br>      &quot;top_university&quot;: {<br>        &quot;name&quot;: &quot;Stanford&quot;,<br>        &quot;graduation_rate&quot;: &quot;94%&quot;,<br>        &quot;location&quot;: {<br>          &quot;lat&quot;: &quot;37.427828&quot;,<br>          &quot;long&quot;: &quot;-122.171302&quot;<br>        },<br>        &quot;subjects&quot;: [<br>          &quot;CS&quot;,<br>          &quot;Maths&quot;<br>        ]<br>      },<br>      &quot;universities&quot;: [<br>        {<br>          &quot;name&quot;: &quot;Stanford&quot;,<br>          &quot;subjects&quot;: [<br>            &quot;CS&quot;,<br>            &quot;Maths&quot;<br>          ]<br>        },<br>        {<br>          &quot;name&quot;: &quot;Berkeley&quot;,<br>          &quot;subjects&quot;: [<br>            &quot;Econ&quot;,<br>            &quot;Accounting&quot;<br>          ]<br>        }<br>      ]<br>    }<br>  }<br>}</pre><p>I’ll be using the Firebase SDK for node.js to automate adding the above JSON payload to our Firebase collection.</p><h3>Creating the Framework</h3><p>We are creating a JS file which could be run on nodejs. Initialize a package.json file which would be required to install all dependencies.</p><p>Run the following command.</p><pre>npm init</pre><p>this will create a package.json file. Now create a js file, let’s call it firebase.js. Your directory should contain the following two files.</p><pre>dir<br>  |<br>  -- firebase.js<br>  -- package.json</pre><p>Install the firebase admin sdk dependency.</p><pre>npm install firebase-admin</pre><pre>or </pre><pre>yarn add firebase-admin</pre><p>You need permission to access Firestore or any other Firebase product for the script you write. In order for Firebase admin sdk to access Firestore, it requires a permission file known as a Service Account.</p><h4>Acquiring a service account for your Firebase project</h4><p>As depicted in the below image, press the small icon next to the <strong>Project Overview </strong>title, which would open a menu. Click <strong>Project settings</strong> tab.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/445/1*-pPDPD1WCyY_k3DZ9ntuBA.png" /></figure><p>You will be navigated to the <strong>Settings</strong> screen with multiple tabs. Go to the <strong>Service accounts</strong> tab, which would open up a page similar to the following.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Rj_6mJ1tHqUdS612GJ55iw.png" /></figure><p>As mentioned in the above illustration, press <strong>Generate new private key.</strong> Here you can also see the code snippet to initialize the admin sdk based on your preferred language.</p><p>Pressing <strong>Generate new private key</strong> button would open up a modal. Press <strong>Generate key </strong>and this would download a .json file which would be the project service account file. The name of the file would be different and for ease rename it to <strong>serviceAccount.json</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/974/1*tNlm99y9TAWhAowzAw7e2g.png" /></figure><p>Now we have all the files required to start creating our script.</p><p>Copy and paste the serviceAccount.json file and our cities.json collection file to the same directory where main script resides.</p><p>Now the directory should have 4 files.</p><pre>dir<br>  |<br>  -- firebase.js<br>  -- package.json<br>  -- cities.json<br>  -- serviceAccount.json</pre><h4>Finalizing the script</h4><p>Let’s start changing the firebase.js file.</p><p>Import the required files</p><pre>[firebase.js]</pre><pre>const admin = require(&#39;firebase-admin&#39;);<br>const serviceAccount = require(&#39;./serviceAccount&#39;);<br><br>const citiesCollection = require(&#39;./cities&#39;);</pre><p>Initialize Firebase admin sdk</p><pre>[firebase.js]</pre><pre>const admin = require(&#39;firebase-admin&#39;);<br>const serviceAccount = require(&#39;./serviceAccount&#39;);<br><br>const citiesCollection = require(&#39;./cities&#39;);<br><br>admin.initializeApp({<br>   credential: admin.credential.cert(serviceAccount),<br>   databaseURL: &#39;YOUR_FIRESTORE_URL&#39;<br>});</pre><p>The <strong>databaseURL</strong> can be found in the <strong>Service accounts </strong>tab.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Rj_6mJ1tHqUdS612GJ55iw.png" /></figure><p>Copy the databaseURL and replace it with YOUR_FIRESTORE_URL. You might have noticed how we have parsed the serviceAccount credentials when initializing the admin sdk.</p><p>Let’s write a simple function to see whether we have initialized everything properly and have access to the Firesote database. Will write a read function.</p><pre>[firebase.js]</pre><pre>const admin = require(&#39;firebase-admin&#39;);</pre><pre>...<br>const db = admin.firestore();<br><br>const fetchCities = () =&gt; {<br><br>   db.collection(&#39;cities&#39;).doc(&#39;SF&#39;).get()<br>      .then(docRef =&gt; {<br>         const city = docRef.data();<br>         console.log(&#39;CITY: &#39;, city);<br>      }).catch(e =&gt; {<br>         console.error(&#39;something went wrong&#39;, e)<br>      });<br>};</pre><p><strong>fetchCities</strong> function is pretty much self-explanatory. First we have defined admin.firestore() as db. Then query the cities collection using <strong>db.collection(‘cities’) </strong>and since we know the document id, query document directly via <strong>db.collection(‘cities’).doc(‘SF’). </strong>Use get() to return the document. Since it returns a <strong>promise</strong> use <strong>then</strong> to get the result once resolved. Finally log the result to see the city we queried.</p><p>Complete code looks like,</p><pre>[firebase.js]</pre><pre>const admin = require(&#39;firebase-admin&#39;);<br>const serviceAccount = require(&#39;./serviceAccount&#39;);<br><br>const citiesCollection = require(&#39;./cities&#39;);<br><br>admin.initializeApp({<br>   credential: admin.credential.cert(serviceAccount),<br>   databaseURL: &#39;YOUR_FIRESTORE_URL&#39;<br>});<br><br>const db = admin.firestore();<br><br>const fetchCities = () =&gt; {<br><br>   db.collection(&#39;cities&#39;).doc(&#39;SF&#39;).get()<br>      .then(docRef =&gt; {<br>         const city = docRef.data();<br>         console.log(&#39;CITY: &#39;, city);<br>      }).catch(e =&gt; {<br>         console.error(&#39;something went wrong&#39;, e)<br>      });<br>};<br><br>fetchCities();</pre><p>run the script</p><pre>node firebase.js</pre><p>and you will see the output of the document we manually added earlier.</p><p>Now let’s change the above code to read from the JSON and insert into the collection. I changed the cities JSON to have one more record.</p><pre>[cities.json]</pre><pre>{<br>  &quot;cities&quot;: {<br>    &quot;SF&quot;: {<br>      &quot;name&quot;: &quot;San Francisco&quot;,<br>      &quot;state&quot;: &quot;CA&quot;,<br>      &quot;country&quot;: &quot;USA&quot;,<br>      &quot;population&quot;: 860000,<br>      &quot;regions&quot;: [<br>        &quot;west_coast&quot;,<br>        &quot;norcal&quot;<br>      ],<br>      &quot;top_university&quot;: {<br>        &quot;name&quot;: &quot;Stanford&quot;,<br>        &quot;graduation_rate&quot;: &quot;94%&quot;,<br>        &quot;location&quot;: {<br>          &quot;lat&quot;: &quot;37.427828&quot;,<br>          &quot;long&quot;: &quot;-122.171302&quot;<br>        },<br>        &quot;subjects&quot;: [<br>          &quot;CS&quot;,<br>          &quot;Maths&quot;<br>        ]<br>      },<br>      &quot;universities&quot;: [<br>        {<br>          &quot;name&quot;: &quot;Stanford&quot;,<br>          &quot;subjects&quot;: [<br>            &quot;CS&quot;,<br>            &quot;Maths&quot;<br>          ]<br>        },<br>        {<br>          &quot;name&quot;: &quot;Berkeley&quot;,<br>          &quot;subjects&quot;: [<br>            &quot;Econ&quot;,<br>            &quot;Accounting&quot;<br>          ]<br>        }<br>      ]<br>    },<br>    &quot;LA&quot;: {<br>      &quot;name&quot;: &quot;Los Angeles&quot;,<br>      &quot;state&quot;: &quot;CA&quot;,<br>      &quot;country&quot;: &quot;USA&quot;,<br>      &quot;population&quot;: 3900000,<br>      &quot;regions&quot;: [<br>        &quot;west_coast&quot;,<br>        &quot;socal&quot;<br>      ],<br>      &quot;top_university&quot;: {<br>        &quot;name&quot;: &quot;Stanford&quot;,<br>        &quot;graduation_rate&quot;: &quot;94%&quot;,<br>        &quot;location&quot;: {<br>          &quot;lat&quot;: &quot;37.427828&quot;,<br>          &quot;long&quot;: &quot;-122.171302&quot;<br>        },<br>        &quot;subjects&quot;: [<br>          &quot;CS&quot;,<br>          &quot;Maths&quot;<br>        ]<br>      },<br>      &quot;universities&quot;: [<br>        {<br>          &quot;name&quot;: &quot;Stanford&quot;,<br>          &quot;subjects&quot;: [<br>            &quot;CS&quot;,<br>            &quot;Maths&quot;<br>          ]<br>        },<br>        {<br>          &quot;name&quot;: &quot;Berkeley&quot;,<br>          &quot;subjects&quot;: [<br>            &quot;Econ&quot;,<br>            &quot;Accounting&quot;<br>          ]<br>        }<br>      ]<br>    }<br>  }<br>}</pre><p>Add the code snippet to insert data to the cities collection</p><pre>...<br>const addCities = () =&gt; {<br><br>   for(const cityKey in citiesCollection.cities) {<br>      db.collection(&#39;cities&#39;).doc(cityKey)<br>         .set(citiesCollection.cities[cityKey])<br>         .then(() =&gt; {<br>            console.log(&#39;successfully inserted the document&#39;);<br>            return null;<br>         }).catch(e =&gt; {<br>             console.error(&#39;something went wrong&#39;, e)<br>         });<br>   }<br>};<br>...</pre><p>As you can see, we are iterating the cities JSON file and inserting one city at a time. Instead of <strong>get</strong> method here we have used the <strong>set</strong> method to insert data into the collection.</p><p>Let’s invoke the function</p><pre>const addCities = () =&gt; {<br><br>   for(const cityKey in citiesCollection.cities) {<br>      db.collection(&#39;cities&#39;).doc(cityKey)<br>         .set(citiesCollection.cities[cityKey])<br>         .then(() =&gt; {<br>            console.log(&#39;successfully inserted the document&#39;);<br>            return null;<br>         }).catch(e =&gt; {<br>         console.error(&#39;something went wrong&#39;, e)<br>      });<br>   }<br>};</pre><pre>addCities();</pre><p>and run the script</p><pre>node firebase.js</pre><p>Now you could see the output in the console</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/591/1*uHer98ATx0CCkBl4aBnO5A.png" /><figcaption>console output</figcaption></figure><p>A new document can be seen in the collection.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7uxySdRkx8cwxhQz6FAxSg.png" /></figure><p>As you might notice, the simple script we wrote was able to insert data into our collection. Now you can add any amount of objects to the JSON file and run the script to insert those data to Firestore as new city documents.</p><p>The entire code is as follows</p><pre>[firebase.js]</pre><pre>const admin = require(&#39;firebase-admin&#39;);<br>const serviceAccount = require(&#39;./serviceAccount&#39;);<br><br>const citiesCollection = require(&#39;./cities&#39;);<br><br>admin.initializeApp({<br>   credential: admin.credential.cert(serviceAccount),<br>   databaseURL: &#39;YOUR_FIRESTORE_URL&#39;<br>});<br><br>const db = admin.firestore();<br><br>const fetchCities = () =&gt; {<br><br>   db.collection(&#39;cities&#39;).doc(&#39;SF&#39;).get()<br>      .then(docRef =&gt; {<br>         const city = docRef.data();<br>         console.log(&#39;CITY: &#39;, city);<br>      }).catch(e =&gt; {<br>         console.error(&#39;something went wrong&#39;, e)<br>      });<br>};<br><br>const addCities = () =&gt; {<br><br>   for(const cityKey in citiesCollection.cities) {<br>      db.collection(&#39;cities&#39;).doc(cityKey)<br>         .set(citiesCollection.cities[cityKey])<br>         .then(() =&gt; {<br>            console.log(&#39;successfully inserted the document&#39;);<br>            return null;<br>         }).catch(e =&gt; {<br>         console.error(&#39;something went wrong&#39;, e)<br>      });<br>   }<br>};<br><br>addCities();</pre><p>You could keep or remove the fetchCities() code portion from the code.</p><p>So that’s the end of this article, hope you learned a thing or two related to Firebase cloud Firestore.</p><p>checkout my personal blog to view more articles on different topics — <a href="https://icodeforpizza.tech/home">icodeforpizza</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=50281732bcbc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Google Firebase]]></title>
            <link>https://medium.com/@supun.muthutantrige/google-firebase-5d6f58ceca9?source=rss-2d38e52e3f23------2</link>
            <guid isPermaLink="false">https://medium.com/p/5d6f58ceca9</guid>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[web-app-development]]></category>
            <category><![CDATA[firebase]]></category>
            <dc:creator><![CDATA[Supun Muthutantrige]]></dc:creator>
            <pubDate>Tue, 14 Apr 2020 14:33:22 GMT</pubDate>
            <atom:updated>2020-04-18T04:47:32.010Z</atom:updated>
            <content:encoded><![CDATA[<p>Platform overview</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*B0Av_NnFrCKsyC7gN94ytg.png" /></figure><p>Firebase platform provides everything required to build complete, end to end, web and mobile products. The platform consists of,</p><ul><li>NoSql database — <strong>Firestore</strong></li><li>Serverless backend — <strong>Functions</strong></li><li>Storage — <strong>Firebase</strong> <strong>Cloud Storage</strong></li><li>Hosting — <strong>Firebase Hosting</strong></li><li>User Management — <strong>Firebase Auth</strong></li></ul><p>and many more — <a href="https://firebase.google.com/products">source</a>. But with the above mentioned products, you could pretty much build your <strong>production ready</strong> web or mobile app in no time. And the best part, <strong>you could achieve all that without paying anything</strong>, yes you heard right…. without needing to use your credit card at all to see a version of your app in production. Saying that, after your app reaches a certain level, or for certain requirements, you need to use their monthly or blazer (pay as you go) plans to cater to the demand.</p><p>The best way to learn about firebase and the amazing products it offer, is to actually build a production ready app while using different products the app might require.</p><p>First thing first, let’s create a project in firebase, Go to firebase console — <a href="https://console.firebase.google.com/">source</a>. Follow the step by step guide to create your first project.</p><blockquote>TIP</blockquote><blockquote>During project creation, lookout for the step where you have to mention the project location (by default it’s mentioned as US). Select a proper location based on where most of your clients reside and where you are planning to offer your services from.</blockquote><blockquote>read more on project locations — <a href="https://firebase.google.com/docs/projects/locations">source</a></blockquote><p>Once you are done, you’ll see the main console page.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HaH0Invzw3iyr5_9gkd9hw.png" /><figcaption>firebase console</figcaption></figure><p>Expand the Develop tab (left side menu) to see the above mentioned products.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/260/1*5CJEZbqkKz2ShwwbhjMhmg.png" /><figcaption>main product tab</figcaption></figure><p>In upcoming articles, let’s explore each product while building a production ready web app.</p><p>check my personal blog to view more — <a href="https://icodeforpizza.tech/home">icodeforpizza</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5d6f58ceca9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Let’s Go, Everything you need to know about creating a RESTful Api in Go — Part V]]></title>
            <link>https://medium.com/@supun.muthutantrige/lets-go-everything-you-need-to-know-about-creating-a-restful-api-in-go-part-v-f2d862b48843?source=rss-2d38e52e3f23------2</link>
            <guid isPermaLink="false">https://medium.com/p/f2d862b48843</guid>
            <category><![CDATA[3rd-party]]></category>
            <category><![CDATA[api]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[rest]]></category>
            <category><![CDATA[json]]></category>
            <dc:creator><![CDATA[Supun Muthutantrige]]></dc:creator>
            <pubDate>Sun, 12 May 2019 14:47:36 GMT</pubDate>
            <atom:updated>2020-04-12T03:48:29.805Z</atom:updated>
            <content:encoded><![CDATA[<h3>Let’s Go, Everything you need to know about creating a RESTful Api in Go — Part V</h3><p>Detailed overview on consuming an external REST API’s</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/750/1*ZAoonexgiIjkttFFVJLjlQ.jpeg" /></figure><p><strong>PART V</strong></p><p>Most of the API’s that are there requires consuming other external APIs within the application. Depending on the complexity, an application may consume multiple external services as required. This article is about learning how to make our go application consume external API endpoints which could be a GET, POST, PUT, PATCH or DELETE.</p><p>First will discuss the service layer, then integrate the service layer with the application control layer and finally trigger our application endpoints through POSTMAN to see our implementation in action.</p><p>Let’s create the service layer. Will create a separate package to host service implementations.</p><pre>[Folder structure]</pre><pre>go/<br>  |_ bin<br>  |_ pkg<br>  |_ src<br>       |_ app <br>            |_ app.go<br>       |_ <strong>service <br>            |_ employeeService.go</strong></pre><p>What’s bold above is the new package for our application. Here, employeeService is responsible for client side implementation of the external API we are going to consume. For ease, I’ll be using an already available dummy API which can be found in <a href="http://dummy.restapiexample.com/">here</a>. I’ll be describing about integrating Get all employee data and create a new employee REST API endpoints.</p><pre>[employeeService.go]</pre><pre>package service</pre><pre>import (<br>   &quot;bytes&quot;<br>   &quot;encoding/json&quot;<br>   &quot;io&quot;<br>   &quot;io/ioutil&quot;<br>   &quot;log&quot;<br>   &quot;net/http&quot;<br>)</pre><pre>type Employees []Employee</pre><pre>//Employee response object<br>//{<br>//  &quot;id&quot;: &quot;719&quot;,<br>//  &quot;employee_name&quot;: &quot;test&quot;,<br>//  &quot;employee_salary&quot;: &quot;123&quot;,<br>//  &quot;employee_age&quot;: &quot;23&quot;,<br>//  &quot;profile_image&quot;: &quot;&quot;,<br>//}<br>type Employee struct {<br>   Id     string `json:&quot;id&quot;`<br>   Name   string `json:&quot;employee_name&quot;`<br>   Salary string `json:&quot;employee_salary&quot;`<br>   Age    string `json:&quot;employee_age&quot;`<br>   Image  string `json:&quot;profile_image&quot;`<br>}</pre><pre>// simple GET implementation<br>func DoSimpleGet() Employees {<br>   log.Print(&quot;Start fetching data from service&quot;)<br>   response, err :=<br>   http.Get(&quot;<a href="http://dummy.restapiexample.com/api/v1/employees">http://dummy.restapiexample.com/api/v1/employees</a>&quot;)</pre><pre>   if err != nil {<br>     log.Panic(err.Error())<br>   }</pre><pre>   defer response.Body.Close()</pre><pre>   responseData, err := ioutil.ReadAll(response.Body)<br>   if err != nil {<br>    log.Fatal(err)<br>   }</pre><pre>   var res Employees<br>   json.Unmarshal(responseData, &amp;res)</pre><pre>   log.Print(&quot;Data fetched from service: &quot;, string(res))<br>   log.Print(&quot;Leaving fetch data from service&quot;)</pre><pre>   return res<br>}</pre><p>Function DoSimpleGet() implementation provides the details on integrating the GET endpoint. We’ve used the internal http package to consume external services. Function http.GET(url string) requires passing the url parameter. Then we validate the output for any errors, next we should defer response.Body.Close() which will close the response body once all the other tasks are done. Line, ioutil.ReadAll(response.Body) reads the returned values in response.Body till the EOF and returns a []byte. Now we have a []byte which needs to map to a certain struct. We have created a struct called Employees which is another struct comprised of a list of Employee structs. Line, json.Unmarshal(responseData, &amp;res) takes the previously returned byte array and the address location of Employees struct, then unmarshal data which will end up populating the Employees struct from the json response returned in the Get endpoint. Finally we return the populated Employees struct.</p><p>Similarly, the function with the post request implementation is as follows,</p><pre>[employeeService.go]<br>...</pre><pre>// simple POST request<br>func DoSimplePost() CreateEmployee {<br>   log.Print(&quot;Initiate post request to service&quot;)</pre><pre>   jsonData := map[string]string{&quot;name&quot;: &quot;name1115&quot;, &quot;salary&quot;:<br>               &quot;123&quot;, &quot;age&quot;: &quot;23&quot;}<br>   jsonValue, _ := json.Marshal(jsonData)</pre><pre>   response, err := http.Post(<br>                    &quot;<a href="http://dummy.restapiexample.com/api/v1/create">http://dummy.restapiexample.com/api/v1/create</a>&quot;,<br>                    &quot;application/json&quot;,<br>                    bytes.NewBuffer(jsonValue))</pre><pre>   if err != nil {<br>     log.Panic(err.Error())<br>   }</pre><pre>   data, err := ioutil.ReadAll(response.Body)<br>   if err != nil {<br>     log.Fatal(err)<br>   }</pre><pre>   var responseObject CreateEmployee<br>   json.Unmarshal(data, &amp;responseObject)</pre><pre>   log.Print(&quot;Data created from service: &quot;, responseObject)</pre><pre>   return responseObject<br>}</pre><p>The difference in post request is the payload and header values we send. Here, we’ve hard coded the request payload (body). Json payload is generated via a string key, value map, which is then marshalled using json.Marshal(). Compared to get method, http.Post() requires passing contentyType and body parameters along with the url. Other parts of the method are more or less the same as in the get method, where once the post request is sent, it accepts the response, unmarshal it and populate the createEmployee struct.</p><p>When looking at both get and post methods, it is clear that there are some common expressions used. Such as, post method contains two extra parameters compared to get and other error handling and unmarshalling can be considered common to both approaches.</p><p>We can extract the common parts and restructure above code as follows,</p><pre>[employeeService.go]</pre><pre>package service</pre><pre>import (<br>   &quot;bytes&quot;<br>   &quot;encoding/json&quot;<br>   &quot;io&quot;<br>   &quot;io/ioutil&quot;<br>   &quot;log&quot;<br>   &quot;net/http&quot;<br>)</pre><pre>type Employees []Employee</pre><pre>//Create Employee response object<br>//{<br>//  &quot;id&quot;: &quot;719&quot;,<br>//  &quot;name&quot;: &quot;test&quot;,<br>//  &quot;salary&quot;: &quot;123&quot;,<br>//  &quot;age&quot;: &quot;23&quot;,<br>//}<br>type CreateEmployee struct {<br>   Id     string `json:&quot;id&quot;`<br>   Name   string `json:&quot;name&quot;`<br>   Salary string `json:&quot;salary&quot;`<br>   Age    string `json:&quot;age&quot;`<br>}</pre><pre>//Employee response object<br>//{<br>//  &quot;id&quot;: &quot;719&quot;,<br>//  &quot;employee_name&quot;: &quot;test&quot;,<br>//  &quot;employee_salary&quot;: &quot;123&quot;,<br>//  &quot;employee_age&quot;: &quot;23&quot;, <br>//  &quot;profile_image&quot;: &quot;&quot;,<br>//}<br>type Employee struct {<br>   Id     string `json:&quot;id&quot;`<br>   Name   string `json:&quot;employee_name&quot;`<br>   Salary string `json:&quot;employee_salary&quot;`<br>   Age    string `json:&quot;employee_age&quot;`<br>   Image  string `json:&quot;profile_image&quot;`<br>}</pre><pre>// get request<br>func DoGet() Employees {<br>   log.Print(&quot;Start fetching data from service&quot;)</pre><pre>   response := <strong>doApiRequest</strong>(<br>                 &quot;GET&quot;,<br>                 &quot;<a href="http://dummy.restapiexample.com/api/v1/employees">http://dummy.restapiexample.com/api/v1/employees</a>&quot;,<br>                  nil<br>               )</pre><pre>   var responseObject Employees<br>   json.Unmarshal(response, &amp;responseObject)</pre><pre>   log.Print(&quot;Data fetched from service: &quot;, responseObject)</pre><pre>   return responseObject<br>}</pre><pre>// post request<br>func DoPost() CreateEmployee {<br>   log.Print(&quot;Start create request&quot;)</pre><pre>   jsonData := map[string]string{&quot;name&quot;: &quot;test10&quot;, &quot;salary&quot;: &quot;123&quot;,<br>                                 &quot;age&quot;: &quot;23&quot;}<br>   jsonValue, _ := json.Marshal(jsonData)</pre><pre>   response := <strong>doApiRequest</strong>(<br>                    &quot;POST&quot;,<br>                    &quot;<a href="http://dummy.restapiexample.com/api/v1/create">http://dummy.restapiexample.com/api/v1/create</a>&quot;,<br>                    bytes.NewBuffer(jsonValue)<br>               )</pre><pre>   var responseObject CreateEmployee<br>   json.Unmarshal(response, &amp;responseObject)</pre><pre>   log.Print(&quot;Data received from post request: &quot;, responseObject)</pre><pre>   return responseObject<br>}</pre><pre>// common method<br>func <strong>doApiRequest</strong>(method string, url string, body io.Reader) []byte {<br>   client := &amp;http.Client{}<br>   req, err := http.NewRequest(method, url, body)<br>   if err != nil {<br>     log.Panic(err.Error())<br>   }</pre><pre>   req.Header.Add(&quot;Accept&quot;, &quot;application/json&quot;)<br>   req.Header.Add(&quot;Content-Type&quot;, &quot;application/json&quot;)</pre><pre>   response, err := client.Do(req)</pre><pre>   if err != nil {<br>     log.Panic(err.Error())<br>   }</pre><pre>   defer response.Body.Close()</pre><pre>   responseData, err := ioutil.ReadAll(response.Body)<br>   if err != nil {<br>     log.Fatal(err)<br>   }</pre><pre>   log.Print(&quot;Return service response: &quot;, string(responseData))<br>   return responseData<br>}</pre><p>I have restructured the previous code to create a common method which can be used whether it is a Get, Post, Put, Patch or Delete. The common method doApiRequest uses a http.Client{} which takes a http.NewRequest where we can pass the method as a string. For ourget method NewRequest contains the method name &quot;Get&quot;, url and the body parameter as nil (since GET doesn’t contain a request body in this case). In comparison, the post method would contain the name as &quot;Post&quot;, url and the body which would be passed in. Next, our common method assigns the header values. Here, you can specify any header values required by the external service. A good practice is to pass the header values necessary per each http method, which is hard coded in this instance. Once the request is ready, the service invocation happens by executing, client.Do(request). The rest of the method is to get the response, convert it to a byte array to return to the source method.</p><p>I have changed previously used two methods DoSimpleGet and DoSimplePost as DoGet and DoPost which uses the common doApiRequest method internally. The primary objective of both DoGet and DoPost methods are to prepare the data which is required by the common method as well as handle its own responsibility. Further, these two methods will be exposed to the controller layer.</p><p>Now we have completed our service layer implementation, let’s create two new endpoints from the controller layer, which should use above created service layer methods to invoke the external APIs.</p><pre>[app.go]</pre><pre>package main</pre><pre>import (<br>   &quot;encoding/json&quot;<br>   &quot;log&quot;<br>   &quot;net/http&quot;<br>   <strong>&quot;service&quot;</strong></pre><pre>   &quot;github.com/gorilla/mux&quot;<br>)</pre><pre>func main() {<br>   r := mux.NewRouter()</pre><pre>   <strong>r.HandleFunc(&quot;/employee&quot;, fetchEmployeeHandler).Methods(&quot;GET&quot;)</strong></pre><pre><strong>   r.HandleFunc(&quot;/employee&quot;, createEmployeeHandler).Methods(&quot;POST&quot;)</strong></pre><pre>   ...</pre><pre>   log.Fatal(http.ListenAndServe(&quot;:8080&quot;, r))<br>}</pre><pre>func <strong>fetchEmployeeHandler</strong>(w http.ResponseWriter, r *http.Request) {<br>   log.Print(&quot;Request received to fetch list of employees&quot;)</pre><pre>   //fetch list of employees<br>   listOfEmployees := <strong>service.DoGet()</strong></pre><pre>   w.Header().Add(&quot;Content-Type&quot;, &quot;application/json&quot;)<br>   w.WriteHeader(http.StatusOK)<br>   json.NewEncoder(w).Encode(listOfEmployees)<br>}</pre><pre>func <strong>createEmployeeHandler</strong>(w http.ResponseWriter, r *http.Request) {<br>   log.Print(&quot;Request received to create an employee&quot;)</pre><pre>   //create employee<br>   employee := <strong>service.DoPost()</strong></pre><pre>   w.Header().Add(&quot;Content-Type&quot;, &quot;application/json&quot;)<br>   w.WriteHeader(http.StatusCreated)<br>   json.NewEncoder(w).Encode(employee)<br>}</pre><pre>...</pre><p>Two handler methods fetchEmployeeHandler and createEmployeeHandler are used herein, which are exposed via new Getand Post REST API endpoints of our application. The fetchEmployeeHandler method is responsible for invoking previously implemented DoGet method which will return a list of Employees from the external service. Similarly, createEmployeeHandler method use DoPost service method to invoke the post request which will create a new employee using the external API.</p><p>Let’s trigger our endpoints using Postman and see the results.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dRKoykQJA8eSNwpDLzCSdQ.png" /><figcaption>response from GET method invocation</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*i4iS-3noelg6d_yTEJIETQ.png" /><figcaption>response from POST method invocation</figcaption></figure><p>As you can see we get the responses from our application as intended which consumes the external APIs within the application.</p><p>It’s the end of another article. Up until now we have completed most of the things that you would require when creating a Go REST API. Thus far we’ve learnt,</p><ul><li>How to expose a simple API</li><li>How to integrate swagger documentation</li><li>How to connect to a database</li><li>How to consume a 3rd party REST API’s within our go application.</li></ul><p>For now that’s it. See you soon with another article.</p><p>check my personal blog to view more — <a href="https://icodeforpizza.tech/home">icodeforpizza</a></p><p>Prev Section — <a href="https://medium.com/@supun.muthutantrige/lets-go-everything-you-need-to-know-about-creating-a-restful-api-in-go-part-iv-67aa6153eb58">Part IV</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f2d862b48843" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Go Concurrency, things to know]]></title>
            <link>https://medium.com/@supun.muthutantrige/go-concurrency-things-to-know-f785dc5a48b4?source=rss-2d38e52e3f23------2</link>
            <guid isPermaLink="false">https://medium.com/p/f785dc5a48b4</guid>
            <category><![CDATA[channel]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[performance]]></category>
            <category><![CDATA[goroutines]]></category>
            <category><![CDATA[concurrency]]></category>
            <dc:creator><![CDATA[Supun Muthutantrige]]></dc:creator>
            <pubDate>Sun, 05 May 2019 19:02:53 GMT</pubDate>
            <atom:updated>2019-05-05T19:02:53.815Z</atom:updated>
            <content:encoded><![CDATA[<p>Everything you need to know about go concurrency.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*HsEZkQWCpudkcF9G7io4yA.gif" /></figure><h3>Concurrency vs Parallelism</h3><p><strong>Concurrency</strong></p><p>Concurrency is about dealing with lots of things at once. It’s more about the <strong>structure</strong> of the program and can be described as a collection of independently executing things (tasks, functions) or the existence of independent tasks at the same time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*4Gc0INbpWTkP-NIm5w5k5Q.gif" /><figcaption>concurrency — multiple things at once</figcaption></figure><p><strong>Parallelism</strong></p><p>Parallelism is about doing lots of things at once. It’s about the <strong>execution</strong> of the program. Can be described as the simultaneous execution of multiple things (tasks, functions).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*Ki4YBL7a9O32HD4hHrLjog.gif" /><figcaption>Parallelism — simultaneous execution</figcaption></figure><p>Parallelism can be achieved by properly designing for concurrency. A good explanation of the difference can be found here — <a href="https://blog.golang.org/concurrency-is-not-parallelism">source</a>.</p><p>Go can be used to achieve concurrency in a much simpler and cleaner way because of the rich language specifics it contains. This article is about the basic things to know when writing concurrent code and detailed explanation on ways of achieving it.</p><h3>Goroutines</h3><p>Is considered as lightweight threads. Creating a single threads consumes around 1MB worth of stack memory where as a single goroutine takes only around 2KB of stack memory for starters and grow and shrink as required. This makes creating thousands of goroutines much more memory and time efficient compared to hundreds of threads.</p><p>There can be a program with a single OS thread with thousands of goroutines. Even if a single goroutine is blocked due to a waiting call, go run time will spin up another OS thread and move the other 999 goroutines to unblock them from continue executing.</p><p>To create a goroutine just add go keyword in front of a function. This will create a new goroutine which will run concurrently to the main goroutine.</p><pre>package main</pre><pre>import (<br>   &quot;fmt&quot;<br>)</pre><pre>func hello() {<br>   fmt.Println(&quot;start hello goroutine&quot;)<br>   fmt.Println(&quot;Hello world from hello function...!!&quot;)<br>   fmt.Println(&quot;end hello goroutine&quot;)<br>}</pre><pre>func main() {<br>   fmt.Println(&quot;start main goroutine&quot;)<br>   <strong>go</strong> hello()<br>   fmt.Println(&quot;end main goroutine&quot;)<br>}</pre><p>Here, we have made the hello() function run in a separate goroutine by using the go keyword. What we need to understand is, even without specifying a go keyword, main program execution uses a goroutine behind the scene which is know as the main goroutine. Let’s look at the output of the above program execution,</p><pre>start main goroutine<br>end main goroutine<br><br>Program exited.</pre><p>As you can see, the program has not executed the hello() method, rather the main goroutine has completed its execution. In the main execution flow, once the main goroutine reach line go hello(), without waiting till hello goroutine returns, main goroutine immediately go to the next line and ends its execution.</p><pre>package main</pre><pre>import (<br>   &quot;fmt&quot; <br>   &quot;time&quot;<br>)</pre><pre>func hello() {<br>   fmt.Println(&quot;start hello goroutine&quot;)<br>   fmt.Println(&quot;Hello world from hello function...!!&quot;)<br>   fmt.Println(&quot;end hello goroutine&quot;)<br>}</pre><pre>func main() {<br>   fmt.Println(&quot;start main goroutine&quot;)<br>   go hello() <br>   <strong>time.Sleep(1 * time.Second)</strong><br>   fmt.Println(&quot;end main goroutine&quot;)<br>}</pre><p>Here, we are pausing the main goroutine for 1 second by using sleep() method. This gives time for the hello goroutine to finish its execution and return.</p><pre>[output after pausing the main execution for 1s]</pre><pre>start main goroutine<br>start hello goroutine<br>Hello world from hello function...!!<br>end hello goroutine<br>end main goroutine<br><br>Program exited.</pre><p>Will further analyze the execution flow,</p><pre>package main</pre><pre>import (<br>   &quot;fmt&quot; <br>   &quot;time&quot;<br>)</pre><pre>func hello() {<br>   fmt.Println(&quot;start hello goroutine&quot;)<br>   fmt.Println(&quot;Hello world from hello function...!!&quot;) <br>   <strong>time.Sleep(2 * time.Second)</strong><br>   fmt.Println(&quot;end hello goroutine&quot;)<br>}</pre><pre>func main() {<br>   fmt.Println(&quot;start main goroutine&quot;)<br>   go hello() <br>   time.Sleep(1 * time.Second)<br>   fmt.Println(&quot;end main goroutine&quot;)<br>}</pre><p>Here, we pause the hello goroutine for 2s just before it finishes its execution.</p><pre>start main goroutine<br>start hello goroutine<br>Hello world from hello function...!!<br>end main goroutine<br><br>Program exited.</pre><p>Since it takes 2s to complete the execution of hello goroutine, only first two statements get executed. The main goroutine unpause after 1s and complete before hello goroutine gets a chance to complete its execution. That’s why the line end hello goroutine is not printed.</p><p>Looking at the above goroutine behavior, it should be clear that using time.Sleep based pausing doesn’t going to help handling multiple and complex goroutine executions. This is where channels can be used by goroutines to communicate and signal the completeness of its execution.</p><h3>Channels</h3><p>Channels are what goroutines used to communicate with each other. Channel has a type T which both goroutines can understand, we can think of it as the language (boolean, string, int and etc.) goroutines communicate with one another and once the type is defined (boolean, string, int and etc.) no other language (for a boolean channel cannot send string and vice versa) can be used to communicate via the channel.</p><pre>[channel of type T]<br>chan T </pre><p>Declaring a channel using chan T creates a nil channel which needs to be initialized using make.</p><pre>package main</pre><pre>import &quot;fmt&quot;</pre><pre>func main() {<br>   var a chan int<br>   <br>   if a == nil {<br>      fmt.Println(&quot;Before initialization, channel a is nil&quot;)<br>   }</pre><pre>   a = <strong>make(chan int)</strong><br>   if a != nil {<br>     fmt.Printf(&quot;After make, channel is not nil and type is: %T&quot;, a)<br>   }<br>}</pre><pre>//output<br>Before initialization, channel a is nil<br>After make, channel a is not nil and type is: chan int</pre><p>Above example depicts the type of the channel before initialization using make and after.</p><p><strong>Write to a channel and read from a channel</strong></p><p>Writing (sending) or reading (receiving) data from a channel can be easily done via following ways,</p><pre>*our channel is a</pre><pre>//Sending (writing) to a channel<br><strong>a</strong> &lt;- 5</pre><pre>//Receiving (reading) from a channel<br>data := &lt;- <strong>a</strong></pre><p>If the arrow is pointing towards the channel a &lt;- it means data is send to the channel, on the other hand if the arrow points outward from the channel &lt;- a it means data is read from the channel and we can assign a variable to get the value received from the channel data := &lt;- a.</p><p>Let’s assign a channel to communicate between our main goroutine and hello goroutine and see how we can complete the executions without using time based pausing.</p><pre>package main</pre><pre>import (<br>  &quot;fmt&quot;<br>)</pre><pre>func hello(<strong>done chan bool</strong>) {<br>   fmt.Println(&quot;start hello goroutine&quot;)<br>   fmt.Println(&quot;Hello world from hello function...!!&quot;)<br>   fmt.Println(&quot;end hello goroutine&quot;) <br>   <strong>done &lt;- true<br></strong>}</pre><pre>func main() {<br>   <strong>done := make(chan bool)</strong><br>   fmt.Println(&quot;start main goroutine&quot;)<br>   go hello(<strong>done</strong>)<br>   <strong>&lt;-done</strong><br>   fmt.Println(&quot;end main goroutine&quot;)<br>}</pre><p>In the main function, we declare and initialize a boolean channel done := make(chan bool). Next, we pass the channel to the hello goroutine and inside hello goroutine, we send (write) to the channel once goroutine execution is done. The main goroutine blocks until data (true of false) is available in the channel and as soon as the channel receives (read) a boolean value, main goroutine unpauses and continue its execution.</p><p>The final output is as follows,</p><pre>start main goroutine<br>start hello goroutine<br>Hello world from hello function...!!<br>end hello goroutine<br>end main goroutine</pre><p>Assume that our hello goroutine takes few seconds to complete its execution,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/593/1*bpRCJ26XMeq8EJna_H03Fg.gif" /></figure><p>To improvise hello and main goroutines take time to complete, we have added Sleep for 2s and 0.5s respectively. Based on the output, you can see as soon as hello goroutine completes its execution, main goroutine takes control, continue its execution (pause for 0.5s) and exit.</p><p>Let’s come up with a real user case where an incoming API request might need to go through several validations. First will execute all validations sequentially and then check how go concurrency can be used to optimize our program. Will assume there are 5 validations in the path and each validation takes 1s to complete (some might require to call external services, database queries and what not).</p><pre>[sequential execution]</pre><pre>package main</pre><pre>import (<br>   &quot;fmt&quot;<br>   &quot;time&quot;<br>)</pre><pre>func main() {<br>   start := time.Now()<br>   fmt.Println(&quot;start main goroutine&quot;)<br>   <strong>validate()</strong><br>   fmt.Println(&quot;end main goroutine&quot;)<br>   elapsed := time.Since(start)<br>   fmt.Printf(&quot;program took %s&quot;, elapsed)<br>}</pre><pre>func validate(){<br>   fmt.Println(&quot;start validations&quot;)<br>   //pretending that there are 5 validations<br>   for i := 1; i &lt;= 5; i++ {<br>      validation(i)<br>   }<br>   fmt.Println(&quot;end validations&quot;)<br>}</pre><pre>func validation(i int){<br>   fmt.Println(&quot;start validation:&quot;, i)<br>   time.Sleep(1 * time.Second)<br>   fmt.Println(&quot;end validation:&quot;, i)<br>}</pre><pre>//output<br>start main goroutine<br>start validations<br>start validation: 1<br>end validation: 1<br>start validation: 2<br>end validation: 2<br>start validation: 3<br>end validation: 3<br>start validation: 4<br>end validation: 4<br>start validation: 5<br>end validation: 5<br>end validations<br>end main goroutine<br>program took 5s</pre><p>Will look how we can improve the above by letting each validation done via a separate goroutine. Above code will be written in a different way to contain a separate function for each validation and a channel for each goroutine.</p><pre>[concurrent execution]</pre><pre>package main</pre><pre>import (<br>   &quot;fmt&quot;<br>   &quot;time&quot;<br>)</pre><pre>func main() {<br>   start := time.Now()<br>   fmt.Println(&quot;start main goroutine&quot;)<br>   validate()<br>   fmt.Println(&quot;end main goroutine&quot;)<br>   elapsed := time.Since(start)<br>   fmt.Printf(&quot;program took %s&quot;, elapsed)<br>}</pre><pre>func validate(){<br>   fmt.Println(&quot;start validations&quot;) <br>   //initializing channels<br>   a := make(chan bool)<br>   b := make(chan bool)<br>   c := make(chan bool)<br>   d := make(chan bool)<br>   e := make(chan bool)<br> <br>   //pretending that there are 5 validations<br>   go validation1(a)<br>   go validation2(b)<br>   go validation3(c)<br>   go validation4(d)<br>   go validation5(e)<br> <br>   //receiving from each channel<br>   &lt;-a<br>   &lt;-b<br>   &lt;-c<br>   &lt;-d<br>   &lt;-e<br>   fmt.Println(&quot;end validations&quot;)<br>}</pre><pre>func validation1(a chan bool){<br>   fmt.Println(&quot;start validation: 1&quot;)<br>   time.Sleep(1 * time.Second)<br>   fmt.Println(&quot;end validation: 1&quot;)<br>   a &lt;- true<br>}</pre><pre>func validation2(b chan bool){<br>   fmt.Println(&quot;start validation: 2&quot;)<br>   time.Sleep(1 * time.Second)<br>   fmt.Println(&quot;end validation: 2&quot;)<br>   b &lt;- true<br>}</pre><pre>func validation3(c chan bool){<br>   fmt.Println(&quot;start validation: 3&quot;)<br>   time.Sleep(1 * time.Second)<br>   fmt.Println(&quot;end validation: 3&quot;)<br>   c &lt;- true<br>}</pre><pre>func validation4(d chan bool){<br>   fmt.Println(&quot;start validation: 4&quot;)<br>   time.Sleep(1 * time.Second)<br>   fmt.Println(&quot;end validation: 4&quot;)<br>   d &lt;- true<br>}</pre><pre>func validation5(e chan bool){<br>   fmt.Println(&quot;start validation: 5&quot;)<br>   time.Sleep(1 * time.Second)<br>   fmt.Println(&quot;end validation: 5&quot;)<br>   e &lt;- true<br>}</pre><p>Each validation is done via a separate goroutine. We initialize channels in the validate function and then pass each channel to its appropriate goroutine. Once data has received from all channels (each goroutine completes writing to relevant channel), main goroutine will continue execution and exit.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/593/1*Q2UyAxQwWXimdzpxOXhUlw.gif" /><figcaption>output of concurrent execution</figcaption></figure><p>As you can see, having separate goroutine for each validator has reduced the overall execution time from 5s to 1s.</p><p><strong>Buffered channels</strong></p><p>Channels that we have discussed thus far are <strong>unbuffered</strong>, means channel can only handle a single value (only a single type can be written to a channel). An unbuffered channel is blocked from the sender if no goroutine has read the data, and blocked from the reader if no goroutine has written to the channel (no data to read from).</p><p>An buffered channel on the other hand can contain defined number of values of the provided type, a buffer with 5 bool slots or a buffer with 10 int slots like wise.</p><p>Buffered channel is created by sending an additional size parameter,</p><pre>ch := make(chan type, capacity)</pre><pre>//example<br>done := make(chan bool, 5)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/802/1*gVTNBQh3dJlWM7xkcmBhZQ.png" /><figcaption>channel is not full, producer can send data to the channel</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/809/1*LhM_Ne7Sh2o1QGwsJ1rQMw.png" /><figcaption>channel is full, producer is blocked till a consumer reads data from the channel</figcaption></figure><p>Above illustration depicts how a sender goroutine (producer) can get blocked, when no goroutine (consumer) has read data from the channel. Here the capacity of the channel is 5 and the length has changed from 4 to 5. The length should be below 5 for the producer to unblock and continue to write.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/678/1*YsIXsMilbibAylRqSOcYxg.png" /><figcaption>channel is not empty, consumer can receive data from the channel</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/693/1*UYpAogDKj0EKiNXQsg92UQ.png" /><figcaption>channel is empty, consumer is blocked till a producer sends data to the channel</figcaption></figure><p>As shown above, a receiver goroutine (consumer) can get blocked if no goroutine has (producer) written data to the channel.</p><h3>Worker Pool</h3><p>If you are from a Java background you might have heard about thread pools, executor services and etc. Worker pool is a collection of threads, in go it’s goroutines, which waits for tasks to be assigned and once done return back to the pool and wait. Having a worker pool reduces the resource creation time and make use of already available resources (reuse).</p><p>In go, buffered channels can be used to create worker pools. Worker pool can be achieved by implementing following things (<a href="https://golangbot.com/buffered-channels-worker-pools/">source</a>).</p><ul><li>Creation of a pool of goroutines which listen on an input buffered channel waiting for jobs to be assigned.</li><li>Assign jobs to input buffered channel.</li><li>Maintain a separate output buffered channel for job completed tasks.</li><li>Read from output buffered channel.</li></ul><p>Go doesn’t provide a out of the box worker pool implementation (similar to executor service in Java), we have to create one from scratch or use a third party library.</p><p><strong>Wait Group</strong></p><p>A wait group waits for a collection of goroutines to finish assigned jobs. The goroutine which initiate the wait group will be blocked until all goroutines finish executing.</p><p>Let’s add a wait group for our previously used example, we will be doing few modifications by removing channel based signaling and use wait group to block main goroutine.</p><pre>package main</pre><pre>import (<br>   &quot;fmt&quot;<br>   &quot;time&quot;<br>   <strong>&quot;sync&quot;</strong><br>)</pre><pre>func main() {<br>   start := time.Now()<br> <br>   fmt.Println(&quot;start main goroutine&quot;)<br>   validate()<br>   fmt.Println(&quot;end main goroutine&quot;)<br> <br>   elapsed := time.Since(start)<br>   fmt.Printf(&quot;program took %s&quot;, elapsed)<br>}</pre><pre>func validate(){<br>   fmt.Println(&quot;start validations&quot;)<br> <br>   <strong>tasks := 5<br>   var wg sync.WaitGroup<br>   wg.Add(tasks)</strong><br> <br>   //pretending that there are 5 validations<br>   go validation1(<strong>&amp;wg</strong>)<br>   go validation2(<strong>&amp;wg</strong>)<br>   go validation3(<strong>&amp;wg</strong>)<br>   go validation4(<strong>&amp;wg</strong>)<br>   go validation5(<strong>&amp;wg</strong>)<br> <br>   <strong>wg.Wait()</strong><br>   fmt.Println(&quot;end validations&quot;)<br>}</pre><pre>func validation1(<strong>wg *sync.WaitGroup</strong>){<br>   fmt.Println(&quot;start validation: 1&quot;)<br>   time.Sleep(1 * time.Second)<br>   fmt.Println(&quot;end validation: 1&quot;)<br>   <strong>wg.Done()</strong><br>}</pre><pre>func validation2(<strong>wg *sync.WaitGroup</strong>){<br>   fmt.Println(&quot;start validation: 2&quot;)<br>   time.Sleep(1 * time.Second)<br>   fmt.Println(&quot;end validation: 2&quot;)<br>   <strong>wg.Done()</strong><br>}</pre><pre>func validation3(<strong>wg *sync.WaitGroup</strong>){<br>   fmt.Println(&quot;start validation: 3&quot;)<br>   time.Sleep(1 * time.Second)<br>   fmt.Println(&quot;end validation: 3&quot;)<br>   <strong>wg.Done()</strong><br>}</pre><pre>func validation4(<strong>wg *sync.WaitGroup</strong>){<br>   fmt.Println(&quot;start validation: 4&quot;)<br>   time.Sleep(1 * time.Second)<br>   fmt.Println(&quot;end validation: 4&quot;)<br>   <strong>wg.Done()</strong><br>}</pre><pre>func validation5(<strong>wg *sync.WaitGroup</strong>){<br>   fmt.Println(&quot;start validation: 5&quot;)<br>   time.Sleep(1 * time.Second)<br>   fmt.Println(&quot;end validation: 5&quot;)<br>   <strong>wg.Done()</strong><br>}</pre><p>I have highlighted the changes made to the code. WaitGroup contains a common counter which is decremented by each goroutine. First we create a waitGroup struct var wg sync.WaitGroup which by default assigns 0 as the starting value of the counter. We need to specify the max value the counter should have using wg.Add(value) which will then be decreased by each goroutine using wg.Done(). It is important to pass the pointer of the waitGroup struct we created in the main goroutine since all goroutines will decrease the common counter value. Finally wg.Wait() will get unblocked and continue its execution once the common counter reach 0 again.</p><p>Output of the above code is as follows, which is similar to what we have achieved using channel communication.</p><pre>start main goroutine<br>start validations<br>start validation: 5<br>start validation: 1<br>start validation: 2<br>start validation: 3<br>start validation: 4<br>end validation: 1<br>end validation: 5<br>end validation: 4<br>end validation: 3<br>end validation: 2<br>end validations<br>end main goroutine<br>program took 1s</pre><p>It’s the end of another article, will discuss more details from a separate article as this has become bit lengthy. Have a great day :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f785dc5a48b4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Let’s Go, Everything you need to know about creating a RESTful Api in Go — Part IV]]></title>
            <link>https://medium.com/@supun.muthutantrige/lets-go-everything-you-need-to-know-about-creating-a-restful-api-in-go-part-iv-67aa6153eb58?source=rss-2d38e52e3f23------2</link>
            <guid isPermaLink="false">https://medium.com/p/67aa6153eb58</guid>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[go]]></category>
            <category><![CDATA[postgres]]></category>
            <category><![CDATA[database]]></category>
            <category><![CDATA[rest-api]]></category>
            <dc:creator><![CDATA[Supun Muthutantrige]]></dc:creator>
            <pubDate>Wed, 01 May 2019 16:18:31 GMT</pubDate>
            <atom:updated>2020-04-12T03:47:46.697Z</atom:updated>
            <content:encoded><![CDATA[<h3>Let’s Go, Everything you need to know about creating a RESTful Api in Go — Part IV</h3><p>Detailed overview on integrating a PostgresSQL database.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sxWxM3Kat3KG-MW3oyklFg.jpeg" /></figure><p><strong>PART IV</strong></p><p>Now we have implemented the RESTful API interface in previous articles, it’s time to dive in and understand the entire life cycle of a go application. Whether it is a REST API written in java, C++ or nodejs, there is a higher chance that you would require a database integration to store information at some point. This article is about integrating a PostgresSQL database with our go application.</p><p>For starters let’s assume that there is a PostgresSQL database in our local machine. Here, let’s consider the database asgo_dband the table account.</p><p>Let’s create our database and account table</p><pre>//create database<br>postgres=# CREATE DATABASE go_db;</pre><pre>//use database<br>postgres=# \c go_db;</pre><pre>//create table<br>go_db=# CREATE TABLE account ( <br>   id         int8,<br>   user_name  CHARACTER VARYING(24), <br>   first_name CHARACTER VARYING(24), <br>   last_name  CHARACTER VARYING(24)<br>);</pre><pre>//populate account table with data<br>go_db=# INSERT INTO account VALUES (1, &#39;james123&#39;, &#39;james&#39;, &#39;root&#39;);</pre><pre>//verify data<br>go_db=# SELECT * FROM account; </pre><pre>//will return<br>id  | user_name | first_name | last_name <br>----+-----------+------------+-----------<br>  1 | james123  | james      | root</pre><p>Now that we have a database, a table and set of records, let’s see how we can use go and previously exposed APIs to integrate with the data source layer.</p><p><strong>Sql package</strong></p><p>Package database/sql provides a generic interface to work with SQL and SQL-like databases. It is required to use this package in conjunction with the database driver. For this tutorial purpose, will be using a PostgresSQL database driver, since we will be connecting to a PostgresSQL database. Read more on sql package — <a href="https://golang.org/pkg/database/sql/">source</a>.</p><p><strong>PostgresSQL database driver</strong></p><p>For Postgres will be using a package known as pq. Before importing the package, we should install it and import the dependency.</p><pre>go get github.com/lib/pq</pre><p>Once installed, driver package can be imported along with the sql package.</p><pre>import (<br>   &quot;database/sql&quot;<br>   _ &quot;github.com/lib/pq&quot;<br>)</pre><p>Normally it is not advisable to use the driver package with the sql package to avoid tight coupling with driver implementation. If we are to change the driver somewhere down the line, it will be difficult if we have used direct driver related implementations inside our code base. In this case we are loading the driver anonymously by aliasing its package qualifier to _ and this way we avoid tight coupling our code base with the driver package.</p><p><strong>DB struct</strong></p><p>With our driver in place, we are ready to connect to the database. But first it is important to know sql package basics.</p><p>Accessing database in go is done via a DB struct. This struct is used to create connections, handle connection pool configurations, prepare statements, execute queries, fetch results and handle transactions.</p><p>There are multiple important tasks take place behind the scene.</p><ul><li>The struct uses the driver to establish a connection to the underlying database.</li><li>Manage pool of connections.</li><li>Manage concurrent access to the underlying database.</li></ul><pre>type DB struct {</pre><pre>   waitDuration int64</pre><pre>   connector driver.Connector</pre><pre>   numClosed uint64</pre><pre>   mu           sync.Mutex<br>   freeConn     []*driverConn<br>   connRequests map[uint64]chan connRequest<br>   nextRequest  uint64 <br>   numOpen      int <br>   <br>   openerCh          chan struct{}<br>   resetterCh        chan *driverConn<br>   closed            bool<br>   dep               map[finalCloser]depSet<br>   lastPut           map[*driverConn]string <br>   maxIdle           int                    <br>   maxOpen           int                    <br>   maxLifetime       time.Duration          <br>   cleanerCh         chan struct{}<br>   waitCount         int64 <br>   maxIdleClosed     int64 <br>   maxLifetimeClosed int64 </pre><pre>   stop func() <br>}</pre><ul><li><strong>waitDuration</strong>: Total time waited for new connections.</li><li><strong>connector</strong>: A Connector can be passed to sql.OpenDB, to allow drivers to implement their own sql.DB constructors.</li><li><strong>numClosed</strong>: atomic counter for total number of closed connections.</li><li><strong>mu</strong>: This struct represents a mutual exclusion lock.</li><li><strong>freeConn</strong>: This struct wraps a driver.Conn with a mutex.</li><li><strong>connRequests</strong>: connRequest map where single connRequest represents one request for a new connection. When no idle connections available, DB.conn will create a new connRequest.</li><li><strong>nextRequest</strong>: Next key to use in connRequests map</li><li><strong>numOpen</strong>: number of opened and pending open connections</li><li><strong>openerCh</strong>: Used to signal the need for new connections.</li><li><strong>dep</strong>: A map where the key is <strong>finalCloser </strong>and the value <strong>depSet</strong>.</li><li><strong>lastPut</strong>: stacktrace of last conn’s put, for debugging.</li><li><strong>maxIdle</strong>: zero means defaultMaxIdleConns; negative means 0.</li><li><strong>maxOpen</strong>: &lt;= 0 means unlimited.</li><li><strong>maxLifetime</strong>: maximum amount of time a connection may be reused.</li><li><strong>waitCount</strong>: Total number of connections waited for</li><li><strong>maxIdleClosed</strong>: Total number of connections closed due to idle</li><li><strong>maxLifetimeClosed</strong>: Total number of connections closed due to max free limit</li></ul><p><strong>About sql.Open</strong></p><p>This function is responsible for opening a database using a database driver name and provided data source information. Down the line, this function might just validate it arguments without actually creating a connection to the database. Therefore db.Ping() is required for further verification. This function should be called only once and rarely required to be close.</p><pre>func Open(driverName, dataSourceName string) (*DB, error)</pre><p>Let’s use the above function to open a database in our code base.</p><pre>//datasource<br>connStr := &quot;dbname=orders user=postgres password=password host=localhost port=5432 sslmode=disable&quot;</pre><pre>//passing arguments to Open function.<br>db, err := sql.Open(&quot;postgres&quot;, connStr)</pre><p>Since we are using a PostgresSQL database and a Postgres database driver, the driver name should be postgres. Data source string is defined as a separate string connStr and passed in to the function. It includes the connection parameters such as database name:dbname, database user: user, database password: password, database host: host, database port: port (default port is 5432) and sslmode: sslmode, more info on connection parameters — <a href="https://godoc.org/github.com/lib/pq">source</a></p><pre>//function<br>func Open(driverName, dataSourceName string) (*DB, error)</pre><pre>//equivalent usage in our code base<br>db, err := sql.Open(&quot;postgres&quot;, connStr)</pre><p>As you can see, the function returns an error and a DB struct. It is required to check and handle errors returned from any sql package related operations, thus we should do the same for this one as well.</p><pre>connStr := &quot;dbname=orders user=postgres password=password host=localhost port=5432 sslmode=disable&quot;</pre><pre>db, err := sql.Open(&quot;postgres&quot;, connStr)<br>if err != nil {<br>   log.Fatal(err)<br>}<br>defer db.Close()</pre><p>If there is an error, we log it and if sql.DB shouldn’t have a lifetime beyond the scope we should defer db.Close() the connection.</p><p><strong>Refresher: defer</strong></p><p>A defer statement delays the execution of a function until other functions complete its executions. Once all the surrounding functions return, defer functions will execute. The following scenario will describe the function behavior.</p><pre>//function<br>func main() {<br>   defer fmt.Println(&quot;end 3&quot;)<br>   defer fmt.Println(&quot;end 2&quot;)</pre><pre>   fmt.Println(&quot;hello&quot;)<br>   for i := 0; i &lt; 10; i++ {<br>      fmt.Print(i, &quot; &quot;)<br>   }<br>   fmt.Println(&quot;world&quot;)</pre><pre>   defer fmt.Println(&quot;end 1&quot;)<br>}</pre><pre>//output<br>hello<br>0 1 2 3 4 5 6 7 8 9 world<br>end 1<br>end 2 <br>end 3</pre><pre>//function stack for defer statements, just an illustration.<br>| defer &quot;end 1&quot;|<br>| defer &quot;end 2&quot;|<br>| defer &quot;end 3&quot;|<br>----------------</pre><p>defer statements are evaluated immediately hence will stacked up first than the other functions. Even if there are multiple defer statements, the last statement will be in the top of the stack (last in first out).</p><p>So what defer db.Close() does is, once all the other functions are done executing, close the database connection. And even if there are multiple defer statements after this, should add the close statement as the first defer statement of the lot, since closing should happen at the end.</p><p>Although here we close the connection, it is not advisable to open() and close() database connections frequently. only one sql.DB struct should be created for each datastore separately and should keep it open and pass around into short-lived function as an argument. sql.DB should be treated as a long-lived object else poor usage of reusable connections could lead to running out of available network resources.</p><p>Now we have open a connection to the database, let’s see how we can query and perform crud operations.</p><p><strong>About db.Query()</strong></p><p>Function query() should be used for scenarios which required to return a set of rows (SELECT), even if the result set is empty. On the other hand if no row set is required to return from the underlying operation (INSERT, DELETE) exec() should be used instead of query().</p><p>Earlier we populate account table, now let’s use query() to fetch the results.</p><pre>connStr := &quot;dbname=go_db user=postgres password=password host=localhost port=5432 sslmode=disable&quot;</pre><pre>db, err := sql.Open(&quot;postgres&quot;, connStr)<br>if err != nil {<br>   log.Fatal(err)<br>}</pre><pre>var (<br>   id        int<br>   userName  string<br>)</pre><pre>rows, err := db.Query(&quot;select id, user_name from account&quot;)</pre><pre>if err != nil {<br>   log.Fatal(err)<br>}</pre><pre>defer rows.Close()</pre><pre>for rows.Next() {<br>   err := rows.Scan(&amp;id, &amp;userName)<br>   if err != nil {<br>      log.Fatal(err)<br>   }</pre><pre>   log.Println(id, userName)<br>}</pre><pre>//output<br>2019/04/20 20:18:40 1 james123</pre><p>Here, we are using the query() to send the query to the database. This is what query function looks like,</p><pre>func (db *DB) Query(query string, args ...interface{}) (*Rows, error)</pre><p>Query executes a query that return rows, typically a SELECT. The args are for any placeholder parameters in the query. We should check errors for any sql package function as mentioned earlier in this article. Thus, should do the same for query() as well. Statement defer rows.Close() is important, it closes the Rows, preventing further enumeration.</p><p><strong>About rows.Next() &amp; rows.Scan()</strong></p><pre>func (rs *Rows) Next() bool</pre><p>Function next() provides a way to iterate over the rows in the result set. If there is no next result row or an error, next() will return false.</p><p>Next provide a way to iterate over each row, scan() is used to iterate over each column in the current row and get column fields specified in the parameters. In the query() we’ve asked to fetch two fields in the SELECT statement, id and userName. These two fields ( &amp;id, &amp;userName points to the locations of the variables) need to be specified in the scan function as parameters.</p><pre>func (rs *Rows) Scan(dest ...interface{}) error</pre><p>This is the way to access a result set in go. No way to get a row as a map since everything is strongly typed. Scan require variables with the correct type and pass pointers to the function as parameters as mentioned above.</p><h3>CRUD operations</h3><p>Will use our account table to perform db crud operations. Earlier section described Read via SELECT using query, in this section will see how to perform rest of the Create, Update and Delete operations.</p><p>Although we used query to fetch data for a SELECT statement, it is recommended to use exec for INSERT, UPDATE and DELETE statements which doesn’t require returning rows.</p><p><strong>Create</strong></p><p>Let’s insert data into our account table.</p><pre>insertStmt, err := db.Prepare(&quot;<strong>INSERT INTO account(id, user_name,<br>                   first_name, last_name) VALUES($1, $2, $3, $4)</strong>&quot;)<br>if err != nil {<br> log.Fatal(err)<br>}</pre><pre>res, err := insertStmt.Exec(2, &quot;jon1234&quot;, &quot;jon&quot;, &quot;snow&quot;)<br>if err != nil {<br> log.Fatal(err)<br>}</pre><pre>rowCnt, err := res.RowsAffected()<br>if err != nil {<br> log.Fatal(err)<br>}</pre><pre>log.Printf(&quot;Successfully added an account, affected count = %d\n&quot;, rowCnt)</pre><p>Here, db.Prepare() prepares the INSERT statement and we pass the values as arguments using $1, $2, $3, $4. This parameter arguments are specific to PostgresSQL driver. Next, insertStmt.Exec() executes the prepared statement by passing arguments of the record which needs to be inserted. RowsAffected() returns the number of rows been inserted. As you can see we have handled all the errors as mentioned earlier.</p><p>This will insert an account into our database. Let’s look at how to update an existing record in the database.</p><p><strong>Update</strong></p><p>Let’s update an existing record in our account table,</p><pre>updateStmt, err := db.Prepare(&quot;<strong>UPDATE account SET user_name = $1<br>                   WHERE id = $2</strong>&quot;)<br>if err != nil {<br> log.Fatal(err)<br>}</pre><pre>updateRes, err := updateStmt.Exec(&quot;jonSnow&quot;, 2)<br>if err != nil {<br> log.Fatal(err)<br>}</pre><pre>updateRowCnt, err := updateRes.RowsAffected()<br>if err != nil {<br> log.Fatal(err)<br>}</pre><pre>log.Printf(&quot;Successfully updated an account, affected count = %d\n&quot;, updateRowCnt)</pre><p>Similar to INSERT, we use the same structure but prepare statement query and the parameter passed in exec is the only difference.</p><p><strong>Delete</strong></p><p>After successfully inserting and updating, it’s time to remove a record in the database. For DELETE also we can use a similar approach as INSERT and UPDATE. Will be using a prepare statement and pass relevant arguments via exec function.</p><p>So it is the end of another article. We have integrated a database with our REST API endpoints. Now we know how to connect to a database in go and work with data.</p><p>Next will see how to integrate a third party REST API with our go application.</p><p>check my personal blog to view more — <a href="https://icodeforpizza.tech/home">icodeforpizza</a></p><p>Prev Section — <a href="https://medium.com/@supun.muthutantrige/lets-go-everything-you-need-to-know-about-creating-a-restful-api-in-go-part-iv-52666c5221d4">Part III</a></p><p>Next Section — <a href="https://medium.com/@supun.muthutantrige/lets-go-everything-you-need-to-know-about-creating-a-restful-api-in-go-part-v-f2d862b48843">Part V</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=67aa6153eb58" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Let’s Go, Everything you need to know about creating a RESTful Api in Go — Part IV]]></title>
            <link>https://medium.com/@supun.muthutantrige/lets-go-everything-you-need-to-know-about-creating-a-restful-api-in-go-part-iv-52666c5221d4?source=rss-2d38e52e3f23------2</link>
            <guid isPermaLink="false">https://medium.com/p/52666c5221d4</guid>
            <category><![CDATA[api-documentation]]></category>
            <category><![CDATA[rest-api]]></category>
            <category><![CDATA[swagger]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[go]]></category>
            <dc:creator><![CDATA[Supun Muthutantrige]]></dc:creator>
            <pubDate>Sun, 21 Apr 2019 16:55:20 GMT</pubDate>
            <atom:updated>2020-04-14T16:24:42.065Z</atom:updated>
            <content:encoded><![CDATA[<h3>Let’s Go, Everything you need to know about creating a RESTful Api in Go — Part III</h3><p>Detailed overview on integrating swagger</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/830/1*-QtVuIToVApd0J0MkNlEVw.png" /></figure><p><strong>PART III</strong></p><h3>What is Swagger</h3><p>Have you ever come across a situation where you have implemented set of apis to be used by other components but find it difficult to explain. Things such as what’s the URI, what’s the request payload looks like, what are the HTTP status codes to be expected and so on. Other engineers might also asked you to send curl commands or Postman collections to get an idea about the Apis.</p><p>Swagger provides a better way to overcome some of the main challengers when it comes to develop APIs. It provides a set of tools to make the best use of APIs. One way to deal with the above mentioned limitation in APIs is to provide an API documentation where anyone can get the full picture of how to use it, or in best case scenario, the ability to interact with the API spec. Thus API consumers know what to expect and how to work with it.</p><p>Swagger provides multiple options when dealing with APIs. But what we want is to be able to provide an API documentation. That is to provide an API spec for our previously implemented go RESTful APIs.</p><p>What we have is a set of APIs written in go,</p><pre><strong>[app.go]</strong></pre><pre>package main<br>...</pre><pre>func main() {<br>   r := mux.NewRouter()<br>   r.HandleFunc(&quot;/accounts&quot;, createAccountHandler).Methods(&quot;POST&quot;)<br>   r.HandleFunc(&quot;/accounts/{id}&quot;, getAccountHandler).Methods(&quot;GET&quot;)<br>   r.HandleFunc(&quot;/accounts/{id}&quot;,deleteAccountHandler)<br>    .Methods(&quot;DELETE)<br>   log.Fatal(http.ListenAndServe(&quot;:8080&quot;, r))<br>}<br>...</pre><p>We want it to be accessible to any consumer, by making it look something like this,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/631/1*NWXTTGFiF25YtSfcJ2PMUA.png" /></figure><p>Steps to follow in order to create a swagger documentation for our go REST APIs is as follows,</p><p><strong>Steps</strong></p><ol><li>Add swagger annotations to our go rest api endpoints</li><li>Generate swagger doc — swagger.json</li><li>visualize swagger doc (swagger.json) using SwaggerUI</li></ol><p>Prerequisites</p><p>We should have a tool to complete Steps 1 and 2, which is to generate a swagger.json files from a predefined set of annotations written to describe our api endpoints. Developers coming from Spring, Spring Boot background, should be familiar with annotations such as @ApiOperation, @ApiResponses and etc. Similarly, there should be a tool in golang which supports similar sort of api annotations, once executed, generates a swagger.json file which then can be visualized via SwaggerUI.</p><h3><strong>Go-Swagger</strong></h3><p>A golang implementation of Swagger 2.0, which provides several swagger specific features in go. It includes generating go servers and clients from swagger spce and what matters to us, is the ability to generate a swagger specification from go annotated code.</p><pre><strong>[Steps]</strong></pre><pre>go-swagger --------------&gt; swagger.json --------------&gt; SwaggerUI<br>             (generate)                   (visualize)</pre><p><strong>install go swagger</strong></p><p>There are many ways to install go-swagger (<a href="https://goswagger.io/install.html">source</a>), but herein used the following approach.</p><pre>go get -u github.com/go-swagger/go-swagger/cmd/swagger</pre><p>This will add the swagger dependency to bin folder.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/187/1*HKVg5ezHrM5Y1f2TN50lxg.png" /><figcaption>go-swagger dependency</figcaption></figure><p>Check whether go-swagger works by running the following command</p><pre>swagger generate spec -o ./swagger.json</pre><p><strong>Note:</strong> make sure that swagger executable could be accessible when executing the above statement.</p><pre>Ex: if your current location is outsider bin folder,</pre><pre>go<br>  /bin <br>     |-- swagger<br>  /pkg<br>  /src</pre><p>execute the above as</p><pre>$ bin/swagger generate spec -o ./swagger.json</pre><p>Above will generate a swagger.json file, but since we didn’t add any go specific annotations to our code, it will only include something similar to,</p><pre><strong>[swagger.json]</strong></pre><pre>{<br>   &quot;swagger&quot;: &quot;2.0&quot;,<br>   &quot;paths&quot;: {}<br>}</pre><pre><strong>[File Path]</strong><br>go<br>  /bin <br>     |-- swagger<br>  /pkg<br>  /src<br>  |--swagger.json</pre><p>With swagger.json file been created, we know that go-swagger works as intended. Now It’s time to add annotations to our go REST endpoints.</p><h3>1. Add swagger annotations to rest api endpoints</h3><p>From the previous article (<a href="https://medium.com/@supun.muthutantrige/lets-go-create-an-awesome-rest-api-in-go-part-iii-d9c43e797abc">PART III</a>), we’ve completed our REST endpoints. The full source code is as follows,</p><pre><strong>[app.go]</strong></pre><pre>package main</pre><pre>import (<br>   &quot;encoding/json&quot;<br>   &quot;log&quot;<br>   &quot;net/http&quot;</pre><pre>   &quot;github.com/gorilla/mux&quot;<br>)</pre><pre>//Account Json request payload is as follows,<br>//{<br>//  &quot;id&quot;: &quot;1&quot;,<br>//  &quot;first_name&quot;: &quot;james&quot;,<br>//  &quot;last_name&quot;:  &quot;bolt&quot;,<br>//  &quot;user_name&quot;:  &quot;james1234&quot;<br>//}<br>type Account struct {<br>   ID        string `json:&quot;id&quot;`<br>   FirstName string `json:&quot;first_name&quot;`<br>   LastName  string `json:&quot;last_name&quot;`<br>   UserName  string `json:&quot;user_name&quot;`<br>}</pre><pre>var accountMap map[string]Account</pre><pre>func init() {<br>   accountMap = make(map[string]Account)<br>}</pre><pre>func main() {<br>   r := mux.NewRouter()<br>   r.HandleFunc(&quot;/accounts&quot;, createAccountHandler).Methods(&quot;POST&quot;)<br>   r.HandleFunc(&quot;/accounts/{id}&quot;, getAccountHandler).Methods(&quot;GET&quot;)<br>   r.HandleFunc(&quot;/accounts/{id}&quot;,deleteAccountHandler)<br>    .Methods(&quot;DELETE)<br>   log.Fatal(http.ListenAndServe(&quot;:8080&quot;, r))<br>}</pre><pre>func createAccountHandler(w http.ResponseWriter, r *http.Request) {<br>   log.Print(&quot;Request received to create an Account&quot;)<br>   <br>   var account Account<br>   json.NewDecoder(r.Body).Decode(&amp;account)<br>   id := account.ID<br>   accountMap[id] = account</pre><pre>   log.Print(&quot;Successfully created the Account &quot;, account)<br>   w.Header().Add(&quot;Content-Type&quot;, &quot;application/json&quot;)<br>   w.WriteHeader(http.StatusCreated)<br>   json.NewEncoder(w).Encode(account)<br>}</pre><pre>func getAccountHandler(w http.ResponseWriter, r *http.Request) {<br>   params := mux.Vars(r)<br>   id := params[&quot;id&quot;]</pre><pre>   log.Print(&quot;Request received to get an account by account id: &quot;<br>      ,id)</pre><pre>   account, key := accountMap[id]<br>   w.Header().Add(&quot;Content-Type&quot;, &quot;application/json&quot;)</pre><pre>   if key {<br>     log.Print(&quot;Successfully retrieved the account &quot;, account, &quot; for<br>         account id: &quot;, id)<br>     w.WriteHeader(http.StatusOK)<br>     json.NewEncoder(w).Encode(account)</pre><pre>   } else {<br>     log.Print(&quot;Requested account is not found for account id: &quot;,id)<br>     w.WriteHeader(http.StatusNotFound)<br>     json.NewEncoder(w)</pre><pre>   }<br>}</pre><pre>func deleteAccountHandler(w http.ResponseWriter, r *http.Request) {<br>   log.Print(&quot;Request received to delete an Account by account id&quot;)<br>   //add your own flavor to this function :)<br>}</pre><p>Will start adding go-swagger specific annotations to the above code, which will then be used to generate the swagger.json api spec.</p><p>If you want a detailed overview of go-swagger provided annotations, refer the guide (<a href="https://goswagger.io/use/spec.html">source</a>). First will start adding annotations to get the API spec meta information.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/631/1*u43nxq7yA0Gb9FCr1RTCgw.png" /></figure><p>Add go-swagger meta annotations to our go source file.</p><pre><strong>[app.go]</strong></pre><pre>// Package classification Account API.<br>//<br>// this is to show how to write RESTful APIs in golang.<br>// that is to provide a detailed overview of the language specs<br>//<br>// Terms Of Service:<br>//<br>//     Schemes: http, https<br>//     Host: localhost:8080<br>//     Version: 1.0.0<br>//     Contact: Supun Muthutantri&lt;mydocs@example.com&gt;<br>//<br>//     Consumes:<br>//     - application/json<br>//<br>//     Produces:<br>//     - application/json<br>//<br>//     Security:<br>//     - api_key:<br>//<br>//     SecurityDefinitions:<br>//     api_key:<br>//          type: apiKey<br>//          name: KEY<br>//          in: header<br>//<br>// swagger:meta<br>package main</pre><pre>import (<br>   &quot;encoding/json&quot;<br>   &quot;log&quot;<br>   &quot;net/http&quot;</pre><pre>   &quot;github.com/gorilla/mux&quot;<br>)<br>...</pre><h3>2. Generate swagger doc</h3><p>Execute the following command to generate the swagger.json file.</p><pre>$ bin/swagger generate spec -o ./swagger.json</pre><p>The generated swagger.json file for the annotations we specified is as follows,</p><pre><strong>[swagger.json]</strong></pre><pre>consumes:<br>  - application/json<br>produces:<br>  - application/json<br>schemes:<br>  - http<br>  - https<br>swagger: &#39;2.0&#39;<br>info:<br>  description: |-<br>    the purpose of this application is to show how to write RESTful APIs in golang.<br>    that is to provide a detailed overview of the language specs<br>  title: Account API.<br>  contact:<br>    name: Supun Muthutantri<br>    email: <a href="/service/mailto:mydocs@example.com">mydocs@example.com</a><br>  version: 1.0.0<br>host: localhost:8080<br>paths: {}<br>securityDefinitions:<br>  api_key:<br>    type: apiKey<br>    name: KEY<br>    in: header<br>security:<br>  - api_key: []</pre><h3>3. visualize swagger doc</h3><p>Swagger.io has an online editor for us to visualize swagger specifications. You just have to provide a json or yaml file similar to what was generated in step 2.</p><p>Copy the above specification in swagger.json and paste it in the <a href="https://editor.swagger.io/?_ga=2.192925166.578040948.1555674931-278806537.1555674931">editor</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JXxq76ggXMFvb9dIwumoXg.png" /><figcaption>swagger online editor</figcaption></figure><p>You can use this editor to visualize the generated API spec and improve it until you get the final version.</p><h3>4. Iterate steps 1, 2 and 3 till you get the full API spec</h3><p>Will continue adding annotations to our go REST endpoints. Let’s add go-swagger annotations to the GET endpoint.</p><pre><strong>[app.go]</strong></pre><pre>...</pre><pre>func main() {</pre><pre>   ... </pre><pre>   // swagger:operation GET /accounts/{id} accounts getAccount<br>   // ---<br>   // summary: Return an Account provided by the id.<br>   // description: If the account is found, account will be returned<br>   else Error Not Found (404) will be returned.<br>   // parameters:<br>   // - name: id<br>   //   in: path<br>   //   description: id of the account<br>   //   type: string<br>   //   required: true<br>   // responses:<br>   //   &quot;200&quot;:<br>   //     &quot;$ref&quot;: &quot;#/responses/accountRes&quot;<br>   //   &quot;400&quot;:<br>   //     &quot;$ref&quot;: &quot;#/responses/badReq&quot;<br>   //   &quot;404&quot;:<br>   //     &quot;$ref&quot;: &quot;#/responses/notFoundReq&quot;<br>   r.HandleFunc(&quot;/accounts/{id}&quot;, getAccountHandler).Methods(&quot;GET&quot;)</pre><pre>   ...</pre><pre>}</pre><pre>...</pre><p>As you can see, we have added annotations above GET handler function which looks like comments. Whether the endpoint it GET, POST or DELETE the structure remains more or less similar.</p><p>Things to note</p><ul><li><strong>swagger:operation → </strong>Links a path to the method (<a href="https://goswagger.io/use/spec/operation.html">source</a>)</li></ul><pre>swagger:operation [method] [path pattern] [?tag1 tag2 tag3] [operation id]</pre><ul><li><strong>parameters →</strong>URL parameters, in our case it’s the description of {id} in /accounts/{id}</li><li><strong>responses</strong> → Description of endpoint<strong> </strong>responses, it mentions the status codes, error messages and response payloads.</li><li><strong>$ref</strong> → Relates to <strong>responses</strong>, links to the annotated structs.</li></ul><p>$ref should contain all the response structs annotated in a similar way. Here Response codes for 200, 400 and 404 should contain separate annotated structs for <strong>accountRes</strong>, <strong>badReq</strong> and <strong>notFoundReq</strong>.</p><pre><strong>[Preparing accountRes</strong><strong>]</strong></pre><pre><strong>[Annotated Account struct]</strong><br>// Account request model<br>type Account struct {<br>   // Id of the account<br>   ID string `json:&quot;id&quot;`<br>   // First Name of the account holder<br>   FirstName string `json:&quot;first_name&quot;`<br>   // Last Name of the account holder<br>   LastName string `json:&quot;last_name&quot;`<br>   // User Name of the account holder<br>   UserName string `json:&quot;user_name&quot;`<br>}</pre><pre><strong>[Annotated accountRes response struct]</strong><br>// Account response payload<br>// swagger:response accountRes<br>type swaggAccountRes struct {<br>   // in:body<br>   Body Account<br>}</pre><p>As you can see, in order to define the swagger annotations for response codes and response payloads we have created a separate struct <strong>swaggAccountRes</strong>. Read more on <a href="https://goswagger.io/use/spec/response.html">swagger:response</a>.</p><p>Complete annotations for our GET endpoint is as follows,</p><pre><strong>[app.go]</strong></pre><pre>...</pre><pre>// Account request model<br>type <strong>Account</strong> struct {<br>   // Id of the account<br>   ID string `json:&quot;id&quot;`<br>   // First Name of the account holder<br>   FirstName string `json:&quot;first_name&quot;`<br>   // Last Name of the account holder<br>   LastName string `json:&quot;last_name&quot;`<br>   // User Name of the account holder<br>   UserName string `json:&quot;user_name&quot;`<br>}</pre><pre>// Account response payload<br>// swagger:response <strong>accountRes</strong><br>type swaggAccountRes struct {<br>   // in:body<br>   Body <strong>Account</strong><br>}</pre><pre>// Error Bad Request<br>// swagger:response <strong>badReq</strong><br>type swaggReqBadRequest struct {<br>   // in:body<br>   Body struct {<br>      // HTTP status code 400 -  Bad Request<br>      Code int `json:&quot;code&quot;`<br>   }<br>}</pre><pre>// Error Not Found<br>// swagger:response <strong>notFoundReq</strong><br>type swaggReqNotFound struct {<br>   // in:body<br>   Body struct {<br>      // HTTP status code 404 -  Not Found<br>      Code int `json:&quot;code&quot;`<br>   }<br>}</pre><pre>...</pre><pre>func main() {</pre><pre>...</pre><pre>// swagger:operation GET /accounts/{id} accounts getAccount<br>   // ---<br>   // summary: Return an Account provided by the id.<br>   // description: If the account is found, account will be returned<br>   else Error Not Found (404) will be returned.<br>   // parameters:<br>   // - name: id<br>   //   in: path<br>   //   description: id of the account<br>   //   type: string<br>   //   required: true<br>   // responses:<br>   //   &quot;200&quot;:<br>   //     &quot;$ref&quot;: &quot;#/responses/<strong>accountRes</strong>&quot;<br>   //   &quot;400&quot;:<br>   //     &quot;$ref&quot;: &quot;#/responses/<strong>badReq</strong>&quot;<br>   //   &quot;404&quot;:<br>   //     &quot;$ref&quot;: &quot;#/responses/<strong>notFoundReq</strong>&quot;<br>   r.HandleFunc(&quot;/accounts/{id}&quot;, getAccountHandler).Methods(&quot;GET&quot;)</pre><pre>...</pre><pre>}</pre><pre>...</pre><p>For ease of referencing I have bold the reference structs in the above code snippet. Similarly, you can add annotations to POST and DELETE endpoints as well.</p><p>Once completed the go endpoints with the annotations will look as follows,</p><pre><strong>[app.go]</strong></pre><pre>...</pre><pre>// Account request model<br>type <strong>Account</strong> struct {<br>   // Id of the account<br>   ID string `json:&quot;id&quot;`<br>   // First Name of the account holder<br>   FirstName string `json:&quot;first_name&quot;`<br>   // Last Name of the account holder<br>   LastName string `json:&quot;last_name&quot;`<br>   // User Name of the account holder<br>   UserName string `json:&quot;user_name&quot;`<br>}</pre><pre>// Account response payload<br>// swagger:response <strong>accountRes</strong><br>type swaggAccountRes struct {<br>   // in:body<br>   Body <strong>Account</strong><br>}</pre><pre>// Success response<br>// swagger:response <strong>okResp</strong><br>type swaggRespOk struct {<br>   // in:body<br>   Body struct {<br>      // HTTP status code 200 - OK<br>      Code int `json:&quot;code&quot;`<br>   }<br>}</pre><pre>// Error Bad Request<br>// swagger:response <strong>badReq</strong><br>type swaggReqBadRequest struct {<br>   // in:body<br>   Body struct {<br>      // HTTP status code 400 -  Bad Request<br>      Code int `json:&quot;code&quot;`<br>   }<br>}</pre><pre>// Error Not Found<br>// swagger:response <strong>notFoundReq</strong><br>type swaggReqNotFound struct {<br>   // in:body<br>   Body struct {<br>      // HTTP status code 404 -  Not Found<br>      Code int `json:&quot;code&quot;`<br>   }<br>}</pre><pre>...</pre><pre>func main() {<br>   r := mux.NewRouter()</pre><pre>   // swagger:operation POST /accounts/ accounts createAccount<br>   // ---<br>   // summary: Creates a new account.<br>   // description: If account creation is success, account will be<br>   returned with Created (201).<br>   // parameters:<br>   // - name: account<br>   //   description: account to add to the list of accounts<br>   //   in: body<br>   //   required: true<br>   //   schema:<br>   //     &quot;$ref&quot;: &quot;#/definitions/<strong>Account</strong>&quot;<br>   // responses:<br>   //   &quot;200&quot;:<br>   //     &quot;$ref&quot;: &quot;#/responses/<strong>okResp</strong>&quot;<br>   //   &quot;400&quot;:<br>   //     &quot;$ref&quot;: &quot;#/responses/<strong>badReq</strong>&quot;<br>   r.HandleFunc(&quot;/accounts&quot;, createAccountHandler).Methods(&quot;POST&quot;)</pre><pre>   // swagger:operation GET /accounts/{id} accounts getAccount<br>   // ---<br>   // summary: Return an Account provided by the id.<br>   // description: If the account is found, account will be returned<br>   else Error Not Found (404) will be returned.<br>   // parameters:<br>   // - name: id<br>   //   in: path<br>   //   description: id of the account<br>   //   type: string<br>   //   required: true<br>   // responses:<br>   //   &quot;200&quot;:<br>   //     &quot;$ref&quot;: &quot;#/responses/<strong>accountRes</strong>&quot;<br>   //   &quot;400&quot;:<br>   //     &quot;$ref&quot;: &quot;#/responses/<strong>badReq</strong>&quot;<br>   //   &quot;404&quot;:<br>   //     &quot;$ref&quot;: &quot;#/responses/<strong>notFoundReq</strong>&quot;<br>   r.HandleFunc(&quot;/accounts/{id}&quot;, getAccountHandler).Methods(&quot;GET&quot;)</pre><pre>   // swagger:operation DELETE /accounts/{id} accounts deleteAccount<br>   // ---<br>   // summary: Deletes requested account by account id.<br>   // description: Depending on the account id, HTTP Status Not<br>   Found (404) or HTTP Status OK (200) may be returned.<br>   // parameters:<br>   // - name: id<br>   //   in: path<br>   //   description: account id<br>   //   type: string<br>   //   required: true<br>   // responses:<br>   //   &quot;200&quot;:<br>   //     &quot;$ref&quot;: &quot;#/responses/<strong>okResp</strong>&quot;<br>   //   &quot;400&quot;:<br>   //     &quot;$ref&quot;: &quot;#/responses/<strong>badReq</strong>&quot;<br>   //   &quot;404&quot;:<br>   //     &quot;$ref&quot;: &quot;#/responses/<strong>notFoundReq</strong>&quot;<br>   r.HandleFunc(&quot;/accounts/{id}&quot;,<br>     deleteAccountHandler).Methods(&quot;DELETE&quot;)<br>}<br>...</pre><p>Now execute swagger generation command.</p><pre>$ bin/swagger generate spec -o ./swagger.json</pre><p>Which will generate the following swagger.json file.</p><pre><strong>[swagger.json]</strong></pre><pre>consumes:<br>  - application/json<br>produces:<br>  - application/json<br>schemes:<br>  - http<br>  - https<br>swagger: &#39;2.0&#39;<br>info:<br>  description: |-<br>    the purpose of this application is to show how to write RESTful APIs in golang<br>    that is to provide a detailed overview of the language specs<br>  title: Account API.<br>  contact:<br>    name: Supun Muthutantri<br>    email: <a href="/service/mailto:mydocs@example.com">mydocs@example.com</a><br>  version: 1.0.0<br>host: localhost:8080<br>paths:<br>  /accounts/:<br>    post:<br>      description: &#39;If account creation is success, account will be returned with Created (201).&#39;<br>      tags:<br>        - accounts<br>      summary: Creates a new account.<br>      operationId: createAccount<br>      parameters:<br>        - description: account to add to the list of accounts<br>          name: account<br>          in: body<br>          required: true<br>          schema:<br>            $ref: &#39;#/definitions/Account&#39;<br>      responses:<br>        &#39;200&#39;:<br>          $ref: &#39;#/responses/okResp&#39;<br>        &#39;400&#39;:<br>          $ref: &#39;#/responses/badReq&#39;<br>  &#39;/accounts/{id}&#39;:<br>    get:<br>      description: &#39;If the account is found, account will be returned else Error Not Found (404) will be returned.&#39;<br>      tags:<br>        - accounts<br>      summary: Return an Account provided by the id.<br>      operationId: getAccount<br>      parameters:<br>        - type: string<br>          description: id of the account<br>          name: id<br>          in: path<br>          required: true<br>      responses:<br>        &#39;200&#39;:<br>          $ref: &#39;#/responses/accountRes&#39;<br>        &#39;400&#39;:<br>          $ref: &#39;#/responses/badReq&#39;<br>        &#39;404&#39;:<br>          $ref: &#39;#/responses/notFoundReq&#39;<br>    delete:<br>      description: &#39;Depending on the account id, HTTP Status Not Found (404) or HTTP Status OK (200) may be returned.&#39;<br>      tags:<br>        - accounts<br>      summary: Deletes requested account by account id.<br>      operationId: deleteAccount<br>      parameters:<br>        - type: string<br>          description: account id<br>          name: id<br>          in: path<br>          required: true<br>      responses:<br>        &#39;200&#39;:<br>          $ref: &#39;#/responses/okResp&#39;<br>        &#39;400&#39;:<br>          $ref: &#39;#/responses/badReq&#39;<br>        &#39;404&#39;:<br>          $ref: &#39;#/responses/notFoundReq&#39;<br>definitions:<br>  Account:<br>    description: Account request model<br>    type: object<br>    properties:<br>      first_name:<br>        description: First Name of the account holder<br>        type: string<br>        x-go-name: FirstName<br>      id:<br>        description: Id of the account<br>        type: string<br>        x-go-name: ID<br>      last_name:<br>        description: Last Name of the account holder<br>        type: string<br>        x-go-name: LastName<br>      user_name:<br>        description: User Name of the account holder<br>        type: string<br>        x-go-name: UserName<br>    x-go-package: app<br>responses:<br>  accountRes:<br>    description: Account response payload<br>    schema:<br>      $ref: &#39;#/definitions/Account&#39;<br>  badReq:<br>    description: Error Bad Request<br>    schema:<br>      type: object<br>      properties:<br>        code:<br>          description: HTTP status code 400 -  Bad Request<br>          type: integer<br>          format: int64<br>          x-go-name: Code<br>  forbiddenReq:<br>    description: Error Forbidden<br>    schema:<br>      type: object<br>      properties:<br>        code:<br>          description: HTTP status code 403 -  Forbidden<br>          type: integer<br>          format: int64<br>          x-go-name: Code<br>  notFoundReq:<br>    description: Error Not Found<br>    schema:<br>      type: object<br>      properties:<br>        code:<br>          description: HTTP status code 404 -  Not Found<br>          type: integer<br>          format: int64<br>          x-go-name: Code<br>  okResp:<br>    description: Success response<br>    schema:<br>      type: object<br>      properties:<br>        code:<br>          description: HTTP status code 200 - OK<br>          type: integer<br>          format: int64<br>          x-go-name: Code<br>securityDefinitions:<br>  api_key:<br>    type: apiKey<br>    name: KEY<br>    in: header<br>security:<br>  - api_key: []</pre><p>You can use the generated swagger.json file to visualize the API spec using Swagger editor.</p><p><strong>Interact with SwaggerUI and execute api’s via swaggerUI</strong></p><p>Up until now we have been able to generate the swagger.json and visualize using swagger editor. In order to be able to serve the swagger spec within our application, will use swaggerUI.</p><p><strong>SwaggerUI</strong></p><blockquote>“Swagger UI allows anyone — be it your development team or your end consumers — to visualize and interact with the API’s resources without having any of the implementation logic in place. It’s automatically generated from your OpenAPI (formerly known as Swagger) Specification, with the visual documentation making it easy for back end implementation and client side consumption” - (<a href="https://swagger.io/tools/swagger-ui/">source</a>)</blockquote><p>With our swagger.json in place will use swaggerUI to make our API spec available via the same go server. Will see how we can setup swaggerUI inside our code base to serve generated swagger.json file.</p><ol><li>Download and integrate SwaggerUI to our code base</li></ol><ul><li>Go to swagger-ui github page (<a href="https://github.com/swagger-api/swagger-ui">link</a>), and clone the repo</li></ul><pre>git clone https://github.com/swagger-api/swagger-ui.git</pre><ul><li>Copy the <strong>dist</strong> folder inside swagger-ui directory and paste it inside our go source folder src directory and rename it to <strong>swaggerui</strong></li></ul><pre><strong>[go source folder]</strong><br>go<br>  /bin<br>  /pkg<br>  /src<br>    |--swaggerui (dist dir renamed to swaggerui)</pre><ul><li>Copy previously generated swagger.json file in to swaggerui folder and change “swagger url” in index.html file inside swaggerui pointing to the swagger.json file.</li></ul><pre>[index.html] <br>...<br>    window.onload = function() {<br>      // Begin Swagger UI call region<br>      const ui = SwaggerUIBundle({<br>        <strong>url</strong>: &quot;<strong>./swagger.json</strong>&quot;,<br>        dom_id: &#39;#swagger-ui&#39;,<br>        deepLinking: true,<br>        presets: [<br>          SwaggerUIBundle.presets.apis,<br>          SwaggerUIStandalonePreset<br>        ],<br>        plugins: [<br>          SwaggerUIBundle.plugins.DownloadUrl<br>        ],<br>        layout: &quot;StandaloneLayout&quot;<br>      })<br>...</pre><p>2. Change our code base to access swaggerui via URI</p><pre><strong>[app.go]</strong></pre><pre>...</pre><pre>func main() {<br>   ...</pre><pre>   <strong>fs := http.FileServer(http.Dir(&quot;./swaggerui&quot;))<br>   r.PathPrefix(&quot;/swaggerui/&quot;).Handler<br>     (http.StripPrefix(&quot;/swaggerui/&quot;, fs))</strong></pre><pre>   log.Fatal(http.ListenAndServe(&quot;:8080&quot;, r))<br>}</pre><pre>...</pre><p>3. Run go application which will start the internal go server</p><pre>$ go run app.go</pre><p>4. Navigate to the browser and view swaggerui.</p><pre>http://localhost:8080/swaggerui/</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*p-y_4rlpEQEWxWRMl7QqTw.png" /></figure><p>You can trigger the endpoints via swaggerui and witness how it works.</p><p>So it is the end of another article. Next, will see how to integrate a database to our endpoints.</p><p>checkout my personal blog to view more — <a href="https://icodeforpizza.tech/home">icodeforpizza</a></p><p>checkout my latest video content blogging series for golang — <a href="https://youtu.be/V87qwH7nJKY">youtube</a></p><p>Prev Section — <a href="https://medium.com/@supun.muthutantrige/lets-go-create-an-awesome-rest-api-in-go-part-iii-d9c43e797abc">Part II</a></p><p>Next Section — <a href="https://medium.com/@supun.muthutantrige/lets-go-everything-you-need-to-know-about-creating-a-restful-api-in-go-part-iv-67aa6153eb58">Part IV</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=52666c5221d4" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>