<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: Deepak Ahuja 👨‍💻</title>
    <description>The latest articles on DEV Community by Deepak Ahuja 👨‍💻 (@dpkahuja).</description>
    <link>https://dev.to/dpkahuja</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F203744%2F7c85361d-d0ea-49e9-aa0b-74448e24f08d.jpg</url>
      <title>DEV Community: Deepak Ahuja 👨‍💻</title>
      <link>https://dev.to/dpkahuja</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/dpkahuja"/>
    <language>en</language>
    <item>
      <title>Get Control of Your Git History</title>
      <dc:creator>Deepak Ahuja 👨‍💻</dc:creator>
      <pubDate>Sun, 27 Sep 2020 13:44:29 +0000</pubDate>
      <link>https://dev.to/dpkahuja/get-control-of-your-git-history-2fad</link>
      <guid>https://dev.to/dpkahuja/get-control-of-your-git-history-2fad</guid>
      <description>&lt;p&gt;We all have been familiar with the following kind of git history:&lt;br&gt;
&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fi%2Fn0l7cylqbum39f1mdi2x.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fi%2Fn0l7cylqbum39f1mdi2x.png" alt="https://xkcd.com/1296/"&gt;&lt;/a&gt;&lt;br&gt;
The following things immediately makes it categories into the "bad" category of git history:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Bad commit messages&lt;/li&gt;
&lt;li&gt;Large commits (containing unrelated changes)&lt;/li&gt;
&lt;li&gt;Small commits (Scattered liked changes)&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;A clean readable history tells a story of how a project is built. It makes it easier to take control of each step done along the way and when needed alter it without much chaos. A cleaner history also allows us to generate change notes, automate the boring stuff and so on. Each commit should be a working copy of the project.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;If you have small related commits, we can "squash" them into one&lt;/li&gt;
&lt;li&gt;If you have a large commit we can split that commit into bunch of smaller commits that represent a logical changeset&lt;/li&gt;
&lt;li&gt;If you have a bad commit message, we can "reword" it&lt;/li&gt;
&lt;li&gt;If commits are not needed, we "drop" them&lt;/li&gt;
&lt;li&gt;If contents of a commit needs to be modified, we can "amend" it
We'll look at knowledge needed to do each of these.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Let's &lt;em&gt;git&lt;/em&gt; started:&lt;/p&gt;
&lt;h1&gt;
  
  
  Undo the commit
&lt;/h1&gt;

&lt;p&gt;The commit that you want to undo could be at either two places:&lt;/p&gt;
&lt;h2&gt;
  
  
  Commit is already pushed (and being consumed by others)
&lt;/h2&gt;

&lt;p&gt;In this case we can use the following command:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;git revert HEAD
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This will create a new commit on top of old commit, that would contain the changes opposit of last commit.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;an option --no-commit that would not auto commit, but introduce change in staging area.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h2&gt;
  
  
  Commit is not pushed (only exists in local repository)
&lt;/h2&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;git reset --hard HEAD~1 // Go back in time, throwing away changes
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Here HEAD~1 represents the target commit to goto, i.e. one step back from HEAD. The following three options are available with reset&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;--soft (removes the commit and bring it back to staging area, working directory untouched)&lt;br&gt;
--mixed (removes the commit from staging area (i.e. unstage) to working directory, the default option)&lt;br&gt;
--hard (removes the commit completely, even from working directory)&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h1&gt;
  
  
  Recover a lost commit
&lt;/h1&gt;

&lt;p&gt;With git we don't really lose a commit unless it is garbage collected. There's a magic command to see all commits ever created in history by:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;git reflog
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Basically wherever your HEAD has traveled inside of Git, you can find it inside of the reflog. The reflog is an ordered list of the commits that HEAD has pointed to: it's undo history for your repo. The reflog isn't part of the repo itself (it's stored separately to the commits themselves) and isn't included in pushes, fetches or clones; it's only local.&lt;br&gt;
So let's say you have just reset the HEAD to point to a wrong commit, did an unexpected rebase or accidentaly deleted a branch. You can recover back your work using the history given in this command.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fi%2Fcn3mbws7c4nz7brf6es7.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fi%2Fcn3mbws7c4nz7brf6es7.png" alt="Alt Text"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;We now just git checkout using the unique identifier of each commit or cherry-pick them in our current branch. If we checkout the commit we can again reset out head back to it.&lt;br&gt;
This command can be used with branches, or even using time as a filter like&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;git reflog HEAD@{1.day.ago} 
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Timed reflog
&lt;/h2&gt;

&lt;p&gt;The time filter can be passed to any git command&lt;br&gt;
The time filters supported are:&lt;br&gt;
a. 1.minute.ago&lt;br&gt;
b. 1.hour.ago&lt;br&gt;
c. 1.day.ago&lt;br&gt;
d. yesterday&lt;br&gt;
e. 1.week.ago&lt;br&gt;
f. 1.month.ago&lt;br&gt;
g. 1.year.ago&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;git diff master@{0} master@{1.day.ago}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This command will diff the current master branch against master 1 day ago. This is very useful if you want to know changes that have occurred within a time frame.&lt;/p&gt;

&lt;h1&gt;
  
  
  Change the last commit
&lt;/h1&gt;

&lt;p&gt;Either you want to change contents of last commit or just change the commit message, we can use the following git command:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;git commit --amend
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  To add a change in last commit
&lt;/h2&gt;

&lt;ol&gt;
&lt;li&gt;Make your required changes&lt;/li&gt;
&lt;li&gt;Stage your changes&lt;/li&gt;
&lt;li&gt;git commit --amend&lt;/li&gt;
&lt;/ol&gt;

&lt;h2&gt;
  
  
  To add a file not included in last commit
&lt;/h2&gt;

&lt;ol&gt;
&lt;li&gt;Stage the file&lt;/li&gt;
&lt;li&gt;git commit --amend&lt;/li&gt;
&lt;/ol&gt;

&lt;h2&gt;
  
  
  To delete a file accidently included in last commit
&lt;/h2&gt;

&lt;ol&gt;
&lt;li&gt;git reset --mixed HEAD~1&lt;/li&gt;
&lt;li&gt;git clean -fd (remove untracked files)&lt;/li&gt;
&lt;li&gt;git commit -m "new commit message"&lt;/li&gt;
&lt;/ol&gt;

&lt;h1&gt;
  
  
  Change a commit earlier in history
&lt;/h1&gt;

&lt;p&gt;To edit a commit which is older in history you can use git rebase (&lt;em&gt;only if your commits are not being consumed anyone else yet&lt;/em&gt;)&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;git rebase -i HEAD~2
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Here, HEAD~2 is the target till when you want to replay the history. You can also put the commit id just before of the one you need to change.&lt;br&gt;
Since commits are immutable, rebase would re-create the commits.&lt;br&gt;
This command would open a script in a text editor like this:&lt;br&gt;
&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fi%2Fjum2lagimxxqpvabp6ot.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fi%2Fjum2lagimxxqpvabp6ot.png" alt="git rebase -i master"&gt;&lt;/a&gt;&lt;br&gt;
The latest commit is at the bottom.&lt;br&gt;
You can change the script as per need by replacing word "pick" to action needed on the commit. Here add "edit" to the third last commit as this is the commit that i want to change&lt;br&gt;
&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fi%2Fekbp20wbhg7n7xor2x0n.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fi%2Fekbp20wbhg7n7xor2x0n.png" alt="pick to edit"&gt;&lt;/a&gt;&lt;br&gt;
Now i will save and exit the file. Git will stop at the desired commit and we can perform our changes and use the command "git commit --amend" at the place.&lt;br&gt;
&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fi%2Fgt79sa5t7zbeeoyqt4ga.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fi%2Fgt79sa5t7zbeeoyqt4ga.png" alt="git commit --amend"&gt;&lt;/a&gt;&lt;br&gt;
Once this is done, all we need to do is continue the rebase process using:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;git rebase --continue
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fi%2Fp6noazp1nttr0r1dhzmx.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fi%2Fp6noazp1nttr0r1dhzmx.png" alt="git rebase --continue"&gt;&lt;/a&gt;&lt;br&gt;
The rebase process would complete and you can see the commit history again. I changed the commit message of commit marked for edit.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;git log
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fi%2Fy4ntbiqzbt57fb5jfgao.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fi%2Fy4ntbiqzbt57fb5jfgao.png" alt="chnaged commit message"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Thus git rebase allows to replay the whole git commit history, and do separate action needed on each commits. This is also used while deleting, re-ordering or squashing few commits into one similarly.&lt;/p&gt;

&lt;h1&gt;
  
  
  Splitting the commit
&lt;/h1&gt;

&lt;p&gt;Assume you have the following git history:&lt;br&gt;
&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fi%2Fpk2daxtyyg4nm7mvdukz.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fi%2Fpk2daxtyyg4nm7mvdukz.png" alt="Alt Text"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;As you can see in the second commit from top, "cca3a22 update jquery version and TnC"&lt;br&gt;
Updating TnC and jquery version are two unrelated things that shouldn't exist together in commit. So we should split this commit into two separate commits.&lt;/p&gt;

&lt;p&gt;So grab it's commit id and start rebasing from it's parent commit:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;git rebase -i 44da2c9
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Mark your commit from "pick" to "edit"&lt;br&gt;
&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fi%2Fg5524mvhdemmmw222w2x.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fi%2Fg5524mvhdemmmw222w2x.png" alt="Alt Text"&gt;&lt;/a&gt;&lt;br&gt;
Now rebase would stop at this commit and will allow you to split the commit into separate commits.&lt;br&gt;
&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fi%2Fot6cat6ek1fncggagxzv.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fi%2Fot6cat6ek1fncggagxzv.png" alt="Alt Text"&gt;&lt;/a&gt;&lt;br&gt;
HEAD currently points to the combined commit, you can use reset command to undo the changes from this commit using either soft or mixed.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;git reset --mixed HEAD~1
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This would bring contents of the commit to working directory. Now we can commit these two things separately.&lt;br&gt;
After the two commits are done, you can continue and finish the rebase.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;git rebase --continue
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;After this, the new history would look like:&lt;br&gt;
&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fi%2Fk27xgvyod018vtxeyawt.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fi%2Fk27xgvyod018vtxeyawt.png" alt="Alt Text"&gt;&lt;/a&gt;&lt;br&gt;
As you can we have succesfully split our commit into two separate commits.&lt;/p&gt;

&lt;p&gt;Thanks for making it towards the end of the post.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fi%2F0x6w5keb0o8szanbd8um.gif" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fi%2F0x6w5keb0o8szanbd8um.gif" alt="Alt Text"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Please leave feedback if you learnt something new or share it with someone who may benefit from it. Drop me a hello on &lt;a href="https://twitter.com/dpkahuja" rel="noopener noreferrer"&gt;twitter&lt;/a&gt; or checkout my other work in the profile. :)&lt;/p&gt;

</description>
      <category>beginners</category>
      <category>tutorial</category>
      <category>git</category>
      <category>github</category>
    </item>
    <item>
      <title>A Docker Free Intro to Containers (Write Your Own Containers and Images)</title>
      <dc:creator>Deepak Ahuja 👨‍💻</dc:creator>
      <pubDate>Sun, 24 May 2020 18:56:31 +0000</pubDate>
      <link>https://dev.to/dpkahuja/a-docker-free-intro-to-containers-write-your-own-containers-and-images-3pk4</link>
      <guid>https://dev.to/dpkahuja/a-docker-free-intro-to-containers-write-your-own-containers-and-images-3pk4</guid>
      <description>&lt;p&gt;Containers are collection of Operating System technologies that allows you to run a process. Containers are themselves a very old technology, but after introduction of Docker and the software system they built to create, deploy and ship containers, it has made containers to be opted widely. We will look at atomic units needed to build a container without docker so that you can get past the definitions like "light weight VM", "something to do with docker", "poor man's virtualization". &lt;/p&gt;

&lt;p&gt;So what technologies do we need to create our own containers? &lt;/p&gt;

&lt;p&gt;Well, let's first look at what an OS does for us essentially. An OS runs processes, an entity which represents the basic unit of work to be implemented in the system. There is a &lt;strong&gt;Process Control Block&lt;/strong&gt; which is a table maintained by OS in which it identifies each process with the help of a special number known as PID (process ID). It also has status of process along with privileges, memory information, environment variables, path, child processes etc. Every process has a certain root directory in which process executes. You can actually find this information in a folder called &lt;code&gt;/proc&lt;/code&gt; in the file system or by running a command:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight shell"&gt;&lt;code&gt;ps aux
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;Here's what it looks like in my machine:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--evrbQQbI--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/i/08o9ooa8yvtwxlixm68y.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--evrbQQbI--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/i/08o9ooa8yvtwxlixm68y.png" alt="Running processes"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;There's a lot more to each of this, but we're gonna stay focused on high level overview of Linux systems.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Now if we are able to create a process and isolate it such that it run somewhere else too without installing the whole operating system, we can call it a container. To isolate this process, i.e. make it impossible for it to look outside it's own folder, we need to "jail" it. We can do it using the following command:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight shell"&gt;&lt;code&gt;&lt;span class="nb"&gt;chroot&lt;/span&gt; /path/to/new/root &lt;span class="nb"&gt;command&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;It will change the root folder for this process and it's children, hence the process will not be able to access anything outside this folder. let's follow some steps as super user:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight shell"&gt;&lt;code&gt;&lt;span class="nb"&gt;mkdir &lt;/span&gt;my-new-root
&lt;span class="nb"&gt;chroot &lt;/span&gt;my-new-root bash
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;Here we have created a new folder and then using &lt;code&gt;chroot&lt;/code&gt; command to “change the root” and run command &lt;code&gt;bash&lt;/code&gt; in it.&lt;br&gt;
You should see some error like bash is not found or command not recognized. Refer following screenshot:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--BCHylssN--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/i/mwrfccswsg4cei9giee8.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--BCHylssN--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/i/mwrfccswsg4cei9giee8.png" alt="set new root"&gt;&lt;/a&gt;&lt;br&gt;
Since command bash is running inside my-new-root and it cannot access anything outside it's new root, it is unable to find program that runs the bash shell.&lt;br&gt;
To fix this, use ‘ldd’.&lt;br&gt;
ldd prints the shared other objects required by an program to run.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight shell"&gt;&lt;code&gt; ldd /bin/bash
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;This command outputs dependencies for a certain program needed to run:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--l9Q9T0kt--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/i/ps5zsgqgjcs3bnhflof2.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--l9Q9T0kt--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/i/ps5zsgqgjcs3bnhflof2.png" alt="Output dependent libs of bash"&gt;&lt;/a&gt;&lt;br&gt;
let's copy these in their respective folders inside my-new-root.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight shell"&gt;&lt;code&gt;&lt;span class="nb"&gt;mkdir &lt;/span&gt;my-new-root/&lt;span class="o"&gt;{&lt;/span&gt;bin,lib64,lib&lt;span class="o"&gt;}&lt;/span&gt;
&lt;span class="nb"&gt;cp&lt;/span&gt; /bin/bash my-new-root/bin
&lt;span class="nb"&gt;cp&lt;/span&gt; /lib/x86_64-linux-gnu/libtinfo.so.5 /lib/x86_64-linux-gnu/libdl.so.2 /lib/x86_64-linux-gnu/libc.so.6 my-new-root/lib
&lt;span class="nb"&gt;cp&lt;/span&gt; /lib64/ld-linux-x86-64.so.2 my-new-root/lib64
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;Here we have created 3 folders in which shared libraries that are required by bash reside (under lib and lib64). Then we are copying those objects into them.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--2CbGpr-H--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/i/soaj5hxkzeyhn5cn9254.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--2CbGpr-H--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/i/soaj5hxkzeyhn5cn9254.png" alt="Copy libs"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Now if we run &lt;code&gt;chroot my-new-root bash&lt;/code&gt; it will open up a bash shell inside my-new-root. You can verify it by &lt;code&gt;pwd&lt;/code&gt; it should output &lt;code&gt;/&lt;/code&gt;&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;Why don't you try enabling &lt;code&gt;ls&lt;/code&gt; command in this too?&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Even though our new root cannot access files outside, it can see still running processes on host container. This won't work for us if we want to run multiple containers on the same host. To achieve true isolation, we also need to hide the processes from other processes. If it’s  not done then one container can kill PID of process, unmount a filesystem or change network setting for other containers. Each process lie in one of 7 namespaces defined in UNIX world. We can use a command called &lt;code&gt;unshare&lt;/code&gt; to see those:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--rLm7KpAE--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/i/lacodygfaoyuuegq1nao.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--rLm7KpAE--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/i/lacodygfaoyuuegq1nao.png" alt="Namespaces in linux"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;We can see the important 7 namespaces above. We can use unshare command to restrict those namespaces.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight shell"&gt;&lt;code&gt;unshare &lt;span class="nt"&gt;--mount&lt;/span&gt; &lt;span class="nt"&gt;--uts&lt;/span&gt; &lt;span class="nt"&gt;--ipc&lt;/span&gt; &lt;span class="nt"&gt;--net&lt;/span&gt; &lt;span class="nt"&gt;--pid&lt;/span&gt; &lt;span class="nt"&gt;--fork&lt;/span&gt; &lt;span class="nt"&gt;--user&lt;/span&gt; &lt;span class="nt"&gt;--map-root-user&lt;/span&gt; &lt;span class="nb"&gt;chroot &lt;/span&gt;my-new-root bash
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;Now our new root has restricted access to processes from any of these namespaces. They can now get duplicate PID too! That's true isolation.&lt;/p&gt;

&lt;p&gt;One last thing left, namespace don't help us limit physical resources like memory limits. For them we have &lt;code&gt;cgroups&lt;/code&gt;, which essentially is a file in which we can collect PIDs and define limits for cpu, memory or network bandwidth. The reason it is important because one container can starve the resources (like by &lt;a href="https://www.imperva.com/learn/application-security/fork-bomb/"&gt;fork bomb attack&lt;/a&gt;) of host environment for use by other containers.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;Note: Windows operating systems are not vulnerable to a traditional fork bomb attack, as they are unable to fork other processes.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Here's how we'd do it (Don't worry about commands, we're just learning things that containers are made from)&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight shell"&gt;&lt;code&gt;&lt;span class="c"&gt;# outside of unshare'd environment get the tools we'll need here&lt;/span&gt;
apt-get &lt;span class="nb"&gt;install&lt;/span&gt; &lt;span class="nt"&gt;-y&lt;/span&gt; cgroup-tools htop

&lt;span class="c"&gt;# create new cgroups&lt;/span&gt;
cgcreate &lt;span class="nt"&gt;-g&lt;/span&gt; cpu,memory,blkio,devices,freezer:/sandbox

&lt;span class="c"&gt;# add our unshare'd env to our cgroup&lt;/span&gt;
ps aux &lt;span class="c"&gt;# grab the bash PID that's right after the unshare one&lt;/span&gt;
cgclassify &lt;span class="nt"&gt;-g&lt;/span&gt; cpu,memory,blkio,devices,freezer:sandbox &amp;lt;PID&amp;gt;
&lt;span class="c"&gt;# Set a limit of 80M&lt;/span&gt;
cgset &lt;span class="nt"&gt;-r&lt;/span&gt; memory.limit_in_bytes&lt;span class="o"&gt;=&lt;/span&gt;80M sandbox
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;blockquote&gt;
&lt;p&gt;You can learn more about &lt;a href="https://www.kernel.org/doc/Documentation/cgroup-v1/cgroups.txt"&gt;cgroups here&lt;/a&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;That's it! Now we have created our own container.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Let's create images without docker&lt;/strong&gt;&lt;/p&gt;

&lt;h1&gt;
  
  
  Images
&lt;/h1&gt;

&lt;p&gt;Images are essentially the premade containers packages as a file object.&lt;br&gt;
We can use the following command to package this container as a compressed file:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight shell"&gt;&lt;code&gt;&lt;span class="nb"&gt;tar &lt;/span&gt;cvf dockercontainer.tar my-new-root
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;Now we can ship it somewhere else and we would create a folder to decompress it:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight shell"&gt;&lt;code&gt;&lt;span class="c"&gt;# make container-root directory, export contents of container into it&lt;/span&gt;
&lt;span class="nb"&gt;mkdir &lt;/span&gt;container-root
&lt;span class="nb"&gt;tar &lt;/span&gt;xf dockercontainer.tar &lt;span class="nt"&gt;-C&lt;/span&gt; container-root/

&lt;span class="c"&gt;# make a contained user, mount in name spaces&lt;/span&gt;
unshare &lt;span class="nt"&gt;--mount&lt;/span&gt; &lt;span class="nt"&gt;--uts&lt;/span&gt; &lt;span class="nt"&gt;--ipc&lt;/span&gt; &lt;span class="nt"&gt;--net&lt;/span&gt; &lt;span class="nt"&gt;--pid&lt;/span&gt; &lt;span class="nt"&gt;--fork&lt;/span&gt; &lt;span class="nt"&gt;--user&lt;/span&gt; &lt;span class="nt"&gt;--map-root-user&lt;/span&gt; &lt;span class="nb"&gt;chroot&lt;/span&gt; &lt;span class="nv"&gt;$PWD&lt;/span&gt;/container-root ash &lt;span class="c"&gt;# change root to it&lt;/span&gt;
&lt;span class="c"&gt;# mount needed things&lt;/span&gt;
&lt;span class="c"&gt;# change cgroup settings&lt;/span&gt;
&lt;span class="c"&gt;# etc&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;That's it? Means we can go around and use containers like this. Not really, docker does a lot more than this for you. It provides us an awesome registry of pre baked images, networking, import, export, running, tag, list, kill these images  etc.&lt;/p&gt;

&lt;h1&gt;
  
  
  Benefits of Docker Containers
&lt;/h1&gt;

&lt;ol&gt;
&lt;li&gt;Runtime: docker engine allows us to use different packages compiled and run same across various OS. It's runtime provides good workflow benefits too&lt;/li&gt;
&lt;li&gt;Images: Great portability, image registry, image diffs&lt;/li&gt;
&lt;li&gt;Automation: Your containers can flow through local computer to jenkins all with a file which contains config. It also enables caching and multi stage builds for containers. Hence image builds are very fast&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;An example of above process written in go programming language can be found &lt;a href="https://github.com/lizrice/containers-from-scratch/blob/master/main.go"&gt;here&lt;/a&gt; and it's accompanying &lt;a href="https://youtu.be/_TsSmSu57Zo"&gt;video&lt;/a&gt;.&lt;br&gt;
We'll look at all of this in coming posts. Thank you for making it to end of the post.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--1Eh_eqM6--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_66%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/i/st3lhj7r2g36psdgcs7l.gif" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--1Eh_eqM6--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_66%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/i/st3lhj7r2g36psdgcs7l.gif" alt="Alt Text"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Please share it if helped you learn something new. You can drop me a hello on &lt;a href="https://twitter.com/dpkahuja"&gt;twitter&lt;/a&gt;. Take care :)&lt;/p&gt;

</description>
      <category>tutorial</category>
      <category>beginners</category>
      <category>webdev</category>
      <category>docker</category>
    </item>
    <item>
      <title>Get a Taste of Microservices Architecture and Communication</title>
      <dc:creator>Deepak Ahuja 👨‍💻</dc:creator>
      <pubDate>Sun, 17 May 2020 15:36:14 +0000</pubDate>
      <link>https://dev.to/dpkahuja/get-a-taste-of-microservice-architecture-and-communication-53n3</link>
      <guid>https://dev.to/dpkahuja/get-a-taste-of-microservice-architecture-and-communication-53n3</guid>
      <description>&lt;p&gt;Building applications in Monolithic architecture includes a client making request, server (with router, authorization middle-ware, some set of features, business logic) and a database. The whole App can be put into place using these. The build artifact is a single executable hosted on a single VM with consistent a technology stack.&lt;/p&gt;

&lt;p&gt;In a Micro service, this set makes only a single feature for the app. They work independent of each other without any direct dependency on each other's database. If any of the service is down, the app still works. The services are small, autonomous, and independently deploy-able.&lt;/p&gt;

&lt;h2&gt;
  
  
  Monolithic Vs Microservice Arcitecture
&lt;/h2&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--sNY1IG-_--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/i/g2kwl87hszp7bo09akv3.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--sNY1IG-_--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/i/g2kwl87hszp7bo09akv3.png" alt="Monolithic vs Micorservices architecture"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Monolithic can work well for small applications but even a single line code change means downtime, and it cannot be easily scaled horizontally (add new services) and can only be scaled vertically (means more processing power).&lt;/p&gt;

&lt;h2&gt;
  
  
  Benefits of Microservices
&lt;/h2&gt;

&lt;ol&gt;
&lt;li&gt;Small Services
It can be owned by a team, easier to understand and rewrite.&lt;/li&gt;
&lt;li&gt;Technology Choice
Adopt new technology, use right tool, Standardize where it makes sense.&lt;/li&gt;
&lt;li&gt;Individual Deployment
It has Lower risk of app failure, no downtime, frequent updates&lt;/li&gt;
&lt;li&gt;Scaling
It can scale services easily, cost effective&lt;/li&gt;
&lt;/ol&gt;

&lt;h3&gt;
  
  
  Why do all the hard work to create many different code bases and use heterogeneous technologies to create an app?
&lt;/h3&gt;

&lt;p&gt;There are many challenges in micro services too, for example the communication with each other. The interactions are complex if not avoided can be inefficient due to web of requests b/w services.&lt;br&gt;
In micro services we follow two rules strictly:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Each service gets it's own database (if it needs one)
This is called &lt;em&gt;Database-Per-Service&lt;/em&gt; pattern, we do it because if we use only single, and that db is down, the whole app comes down, the Single Point of Failure needs to be avoided, and secondly is scalability, it is a lot easier to increase capacity and throughput of databases as per needs of each service. &lt;/li&gt;
&lt;li&gt;Services will never, ever reach into another services database
If anything ever goes wrong with database of dependent service, other service also gets lost, secondly, If schema of one database is altered, both service would need to be updated. we can also use different types of databases best suited for specific needs.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Let's try to visualize how would it work and find solutions to raised challenges,&lt;br&gt;
Here's an example of the app with these 3 features: &lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Users can sign up&lt;/li&gt;
&lt;li&gt;User can submit posts&lt;/li&gt;
&lt;li&gt;User can comment on each post
&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s---tZlSZ9c--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/i/2ehxp4olgppiwtn8n96v.png" alt="basic app example"&gt;
&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;But now if we want to add another code that can list comments for post of a particular user:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;we need user from users collection&lt;/li&gt;
&lt;li&gt;we need to find posts of that user&lt;/li&gt;
&lt;li&gt;we need to fetch comments of that post&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;In monolithic server we can reach out to each database and fetch required information. Here's how it would look:&lt;br&gt;
&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--BEZ5qqPX--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/i/d2xml8h42fy7fxjfvqak.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--BEZ5qqPX--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/i/d2xml8h42fy7fxjfvqak.png" alt="Monolithic server"&gt;&lt;/a&gt;&lt;br&gt;
But this pattern is very inefficient, we'll see in a while.&lt;br&gt;
By going by Database-Per-Service pattern in Micro services, We can add another service that can do this work for us:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--IQHH1r25--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/i/56prldnc2mnclkz3pap7.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--IQHH1r25--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/i/56prldnc2mnclkz3pap7.png" alt="Service D"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;How will it reach out to three separate databases of different services? This is not allowed in Database-Per-Service pattern. To figure this out we will understand how to establish communication between services.&lt;/p&gt;

&lt;p&gt;There are two general strategies to establish a communication strategy between services:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Synchronous Communication
Services communicate with each other using direct requests&lt;/li&gt;
&lt;li&gt;Asynchronous Communication
Services communicate with each other using events&lt;/li&gt;
&lt;/ol&gt;

&lt;blockquote&gt;
&lt;p&gt;&lt;em&gt;Note: These are not as same JavaScript's definition of these terms.&lt;/em&gt;&lt;/p&gt;
&lt;/blockquote&gt;
&lt;h3&gt;
  
  
  Example of Sync Communication:
&lt;/h3&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--SiSxvuUB--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/i/fw2s77bsu4rls50j52gb.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--SiSxvuUB--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/i/fw2s77bsu4rls50j52gb.png" alt="Sync Communication"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;One service can communicate with another service using a direct request, this may not need to be HTTP, it could be any type of request. In our case to request comments of a post of a user, The service D will make 3 different requests to each of other service.&lt;/p&gt;
&lt;h3&gt;
  
  
  Advantages:
&lt;/h3&gt;

&lt;ol&gt;
&lt;li&gt;Easy to reason about and add new service straightforward&lt;/li&gt;
&lt;li&gt;New services don't need a database&lt;/li&gt;
&lt;/ol&gt;
&lt;h3&gt;
  
  
  Disadvantages:
&lt;/h3&gt;

&lt;ol&gt;
&lt;li&gt;The entire request is only as fast as it's slowest request. For eg: if request 1 takes 10ms, request 2 takes 10ms but request 3 takes 100ms, the response would time would be more than 100ms&lt;/li&gt;
&lt;li&gt;Makes service dependent on each other, if any service goes down, the entire service goes down&lt;/li&gt;
&lt;li&gt;Difficult to track requests due to multiple nested requests.&lt;/li&gt;
&lt;/ol&gt;
&lt;h3&gt;
  
  
  Example of Async Communication:
&lt;/h3&gt;

&lt;p&gt;This type of communication would need an Event Bus which can emit and receive events, that will be connected to every service in the application. &lt;/p&gt;

&lt;p&gt;This decouples the services from each other. Instead of one-on-one communication, they talk to each other using a message broker. If other service is down, the first service can still work and second one presume itself later. There are two types of messages: &lt;strong&gt;Commands&lt;/strong&gt; ("Do this please") and &lt;strong&gt;Events&lt;/strong&gt; ("Something happened in Past").&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--jpahNY0_--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/i/omj6xale10lo2xj6an77.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--jpahNY0_--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/i/omj6xale10lo2xj6an77.png" alt="Asynchronous Communication"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Now in our case service D would first broadcast an Event (UserQuery) to every other service, those services will handle the event if they want and can again release event for result for that Event. From that User received, Service D will again send a PostsQuery, and then finally from those Posts, another event CommentsQuery to Event Bus. Now Event Bus will broadcast each event to every service until service D will receive the result.&lt;/p&gt;

&lt;p&gt;This approach is very bad and has all the downsides of synchronous communication as well it many of it's own.&lt;/p&gt;

&lt;p&gt;A better approach would be to add a database that can serve the required information. Other services will emit events and populate this database, now this database will be ready to serve the request instantaneously.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--KkPylgGl--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/i/hwf4grunsdyv7y5vns1c.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--KkPylgGl--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/i/hwf4grunsdyv7y5vns1c.png" alt="Async communication"&gt;&lt;/a&gt;&lt;/p&gt;
&lt;h3&gt;
  
  
  Advantages:
&lt;/h3&gt;

&lt;ol&gt;
&lt;li&gt;Service D has zero dependency&lt;/li&gt;
&lt;li&gt;The queries are very fast&lt;/li&gt;
&lt;/ol&gt;
&lt;h3&gt;
  
  
  Disadvantages:
&lt;/h3&gt;

&lt;ol&gt;
&lt;li&gt;Hard to understand and code&lt;/li&gt;
&lt;li&gt;Data Duplication &lt;/li&gt;
&lt;li&gt;Extra Storage cost (but cheap!)&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Thanks for making it to the end of the post, you are awesome! &lt;br&gt;
You just took the first step in seeing the application architecture from a high level perspective. There are tons of information out there to learn more on this. Don't forget to leave your thoughts. I got this information from this awesome Stephen Grider's course, Here's the non-affiliate link (&lt;a href="https://www.udemy.com/share/102VKE/"&gt;https://www.udemy.com/share/102VKE/&lt;/a&gt;).&lt;br&gt;
Please share it if you found it helpful or drop me a hello on &lt;a href="https://twitter.com/Dpkahuja"&gt;twitter&lt;/a&gt; :)&lt;/p&gt;

&lt;p&gt;-- Edit&lt;br&gt;
Follow up read -&lt;br&gt;
&lt;/p&gt;
&lt;div class="ltag__link"&gt;
  &lt;a href="/siy" class="ltag__link__link"&gt;
    &lt;div class="ltag__link__pic"&gt;
      &lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--AOSfez2Y--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://res.cloudinary.com/practicaldev/image/fetch/s--pva2USHe--/c_fill%2Cf_auto%2Cfl_progressive%2Ch_150%2Cq_auto%2Cw_150/https://dev-to-uploads.s3.amazonaws.com/uploads/user/profile_image/145374/6e93547b-45cc-430e-9659-3adea03266b5.jpeg" alt="siy image"&gt;
    &lt;/div&gt;
  &lt;/a&gt;
  &lt;a href="/siy/don-t-do-microservices-if-you-can-2h0" class="ltag__link__link"&gt;
    &lt;div class="ltag__link__content"&gt;
      &lt;h2&gt;Don't Do Microservices If You Can&lt;/h2&gt;
      &lt;h3&gt;Sergiy Yevtushenko ・ May  6 ・ 3 min read&lt;/h3&gt;
      &lt;div class="ltag__link__taglist"&gt;
        &lt;span class="ltag__link__tag"&gt;#microservices&lt;/span&gt;
        &lt;span class="ltag__link__tag"&gt;#beginners&lt;/span&gt;
        &lt;span class="ltag__link__tag"&gt;#tutorial&lt;/span&gt;
        &lt;span class="ltag__link__tag"&gt;#devops&lt;/span&gt;
      &lt;/div&gt;
    &lt;/div&gt;
  &lt;/a&gt;
&lt;/div&gt;


</description>
      <category>tutorial</category>
      <category>beginners</category>
      <category>webdev</category>
      <category>javascript</category>
    </item>
    <item>
      <title>A 10 Line React Accordion Using an HTML Tag!</title>
      <dc:creator>Deepak Ahuja 👨‍💻</dc:creator>
      <pubDate>Sun, 15 Dec 2019 09:31:18 +0000</pubDate>
      <link>https://dev.to/dpkahuja/a-10-line-react-accordion-using-an-html-tag-55i1</link>
      <guid>https://dev.to/dpkahuja/a-10-line-react-accordion-using-an-html-tag-55i1</guid>
      <description>&lt;p&gt;I recently came across a use case in which I needed an accordion component in my react application. I had a few options like using &lt;a href="https://v1.material-ui.com/demos/expansion-panels/" rel="noopener noreferrer"&gt;Material UI&lt;/a&gt;, some open source components &lt;a href="https://reactjsexample.com/tag/accordion/" rel="noopener noreferrer"&gt;this&lt;/a&gt; and &lt;a href="https://codepen.io/adamaoc/pen/wBGGQv" rel="noopener noreferrer"&gt;this&lt;/a&gt;. &lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;In my use case set of accordion options were dynamic, and they themselves carry information whether they should be open or not by default from the parent.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;I tried a few components but after a day or two, I always had to go back and remove the component or add some behavior myself. In most components, parents keep track of open sections and children themselves have to use some change handler to inform parent for changing open sections.&lt;/p&gt;

&lt;p&gt;So, I created one myself with just a few lines of code and without using any 3rd party library.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fthepracticaldev.s3.amazonaws.com%2Fi%2Fer2wyoakxvdiru6qxo9l.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fthepracticaldev.s3.amazonaws.com%2Fi%2Fer2wyoakxvdiru6qxo9l.png" alt="Accordion"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Let me introduce to you HTML's &lt;code&gt;&amp;lt;detail&amp;gt;&lt;/code&gt; tag.&lt;br&gt;
This tag carries in itself the on-demand show/hide feature which is the core of accordion. We will use a set of these to create our component and it will save us tens of lines of code to handle the opening and closing behavior ourselves. This can be used to create our interactive widget which will have an &lt;code&gt;open&lt;/code&gt; prop that decides whether to show or hide the content. All of this being a &lt;em&gt;no-JavaScript&lt;/em&gt; widget.&lt;/p&gt;

&lt;p&gt;Helper link: &lt;a href="https://www.w3schools.com/tags/tag_details.asp" rel="noopener noreferrer"&gt;detail tag&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Note: The details tag is not supported in Internet Explorer.&lt;/p&gt;

&lt;p&gt;There's one more tag that we will need i.e &lt;code&gt;&amp;lt;summary&amp;gt;&lt;/code&gt;. This tag defines a heading that can be clicked to show or hide the content section. It also comes with a built-in toggling arrow which we can customize.&lt;/p&gt;

&lt;p&gt;Here's how it looks:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fthepracticaldev.s3.amazonaws.com%2Fi%2Fev9wq8494jw4roxuxvqp.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fthepracticaldev.s3.amazonaws.com%2Fi%2Fev9wq8494jw4roxuxvqp.png" alt="details plus summary tag"&gt;&lt;/a&gt;&lt;/p&gt;
&lt;h2&gt;
  
  
  The Accordion Component
&lt;/h2&gt;


&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function Accordion({ children: options }) {
  const toOpen = options.props.open ? true : null;
  return options.map(options =&amp;gt; (
    &amp;lt;details open={toOpen}&amp;gt;{options}&amp;lt;/details&amp;gt;
  ));
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;


&lt;p&gt;Two things to note here:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Children carry property whether they want to be open or not. You can change it as peruse.&lt;/li&gt;
&lt;li&gt;In JSX, props compile to plain javascript object before they are used an attribute to plain HTML, hence we return null to disallow it from being added to HTML. A detailed explanation:&lt;/li&gt;
&lt;/ol&gt;


&lt;div class="ltag__stackexchange--container"&gt;
  &lt;div class="ltag__stackexchange--title-container"&gt;
    
      &lt;div class="ltag__stackexchange--title"&gt;
        &lt;div class="ltag__stackexchange--header"&gt;
          &lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev.to%2Fassets%2Fstackoverflow-logo-b42691ae545e4810b105ee957979a853a696085e67e43ee14c5699cf3e890fb4.svg" alt=""&gt;
          &lt;a href="https://stackoverflow.com/questions/41798027/react-inline-conditional-component-attribute/41798074#41798074" rel="noopener noreferrer"&gt;
            &lt;span class="title-flare"&gt;answer&lt;/span&gt; re: React inline conditional component attribute
          &lt;/a&gt;
        &lt;/div&gt;
        &lt;div class="ltag__stackexchange--post-metadata"&gt;
          &lt;span&gt;Jan 23 '17&lt;/span&gt;
        &lt;/div&gt;
      &lt;/div&gt;
      &lt;a class="ltag__stackexchange--score-container" href="https://stackoverflow.com/questions/41798027/react-inline-conditional-component-attribute/41798074#41798074" rel="noopener noreferrer"&gt;
        &lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev.to%2Fassets%2Fstackexchange-arrow-up-eff2e2849e67d156181d258e38802c0b57fa011f74164a7f97675ca3b6ab756b.svg" alt=""&gt;
        &lt;div class="ltag__stackexchange--score-number"&gt;
          30
        &lt;/div&gt;
        &lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev.to%2Fassets%2Fstackexchange-arrow-down-4349fac0dd932d284fab7e4dd9846f19a3710558efde0d2dfd05897f3eeb9aba.svg" alt=""&gt;
      &lt;/a&gt;
    
  &lt;/div&gt;
  &lt;div class="ltag__stackexchange--body"&gt;
    
&lt;p&gt;First of all, JSX is just a &lt;em&gt;syntactic sugar&lt;/em&gt; for &lt;a href="https://facebook.github.io/react/docs/react-api.html#createelement" rel="noreferrer noopener"&gt;&lt;code&gt;React.createElement&lt;/code&gt;&lt;/a&gt;. So, &lt;strong&gt;it may look like&lt;/strong&gt;, but, in reality, &lt;strong&gt;you don't specify &lt;code&gt;html attributes&lt;/code&gt;&lt;/strong&gt;: in fact, you are always passing &lt;code&gt;props&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;For instance, the JSX code &lt;code&gt;&amp;lt;input type="button" value="My button" /&amp;gt;&lt;/code&gt; is transpiled into &lt;code&gt;React.createElement('input',{type:'button',value:'My Button'})&lt;/code&gt;…&lt;/p&gt;
    
  &lt;/div&gt;
  &lt;div class="ltag__stackexchange--btn--container"&gt;
    &lt;a href="https://stackoverflow.com/questions/41798027/react-inline-conditional-component-attribute/41798074#41798074" class="ltag__stackexchange--btn" rel="noopener noreferrer"&gt;Open Full Answer&lt;/a&gt;
  &lt;/div&gt;
&lt;/div&gt;
 

&lt;p&gt;It will be used like this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;Accordion&amp;gt;
   ...Options
&amp;lt;/Accordion&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  The Option Component
&lt;/h2&gt;

&lt;p&gt;This will be the content of each section in the accordion. It uses summary tag to show the label (heading) of the section which is clickable. It renders children which for each section without any javascript.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function Option({ label, children }) {
  return (
    &amp;lt;React.Fragment&amp;gt;
      &amp;lt;summary&amp;gt;
        {label}
      &amp;lt;/summary&amp;gt;
      {children}
    &amp;lt;/React.Fragment&amp;gt;
  );
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;I used it like this,&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;Accordion&amp;gt;
 {this.getOptions(status)}
&amp;lt;/Accordion&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Some code to get options list:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function getOptions(status) {
 // status decides which options to return with what open flag
return [
     ...moreOptions, 
     &amp;lt;Option label="heading" open={status === "status1"}&amp;gt;
        &amp;lt;Component1
          someProp={someProp}
         /&amp;gt;
      &amp;lt;/Option&amp;gt;
    ]

}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Here's the final output with some applied CSS.&lt;/p&gt;

&lt;p&gt;&lt;iframe src="https://codesandbox.io/embed/vigorous-bohr-c97ri?runonclick=1"&gt;
&lt;/iframe&gt;
&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;Note: To disable the default icon in summary component:&lt;br&gt;
&lt;/p&gt;
&lt;/blockquote&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt; summary::-webkit-details-marker {
     display: none
 }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now feel free to play around with it. It is often advisable not to download and keep 3rd party libraries for simple use cases, It took me 5 tries to decide that I can just do it in less than 10 lines of code for which I kept adding 3rd party components. Simple functionalities can often be extracted out and used independently.&lt;/p&gt;

&lt;p&gt;Thanks for making it to the end of the post, you are awesome! &lt;br&gt;
Please share it if you found it helpful or drop me a hello on &lt;a href="https://twitter.com/Dpkahuja" rel="noopener noreferrer"&gt;twitter&lt;/a&gt; :)&lt;/p&gt;

</description>
      <category>beginners</category>
      <category>javascript</category>
      <category>react</category>
      <category>webdev</category>
    </item>
    <item>
      <title>Learn and Build Web Authentication System (Universal Principles)</title>
      <dc:creator>Deepak Ahuja 👨‍💻</dc:creator>
      <pubDate>Mon, 02 Sep 2019 08:56:28 +0000</pubDate>
      <link>https://dev.to/dpkahuja/learn-and-build-web-authentication-system-universal-principles-370e</link>
      <guid>https://dev.to/dpkahuja/learn-and-build-web-authentication-system-universal-principles-370e</guid>
      <description>&lt;h1&gt;
  
  
  What's an Authentication?
&lt;/h1&gt;

&lt;p&gt;Servers are basically &lt;em&gt;stupid&lt;/em&gt; computer programs who cannot remember who and what made a request after serving it once. The communication between clients and servers over HTTP model is &lt;a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Overview#HTTP_is_stateless_but_not_sessionless" rel="noopener noreferrer"&gt;stateless&lt;/a&gt; in the sense that server cannot confirm the identity of client (user-agent) for each request without some sort of Authentication. Also, they have been over burdened with responsibilities like not showing your personal Twitter DM(s) to someone else, remembering stuff you added to your cart on Amazon, keeping your drafts on DEV articles safe from being copied by other people, preventing you from hacking your Ex's Facebook. All of this is going to need a way to tell server who you are and what should be served to you. &lt;/p&gt;

&lt;p&gt;Authentication is more than storing an "user email". Emails and usernames are public facing digital identity you create for yourself on the web. Other people can see and use it too. So we also use passwords and tokens to protect your non-public resources.&lt;/p&gt;

&lt;h1&gt;
  
  
  Passwords
&lt;/h1&gt;

&lt;p&gt;The most basic and unsafe approach for storing passwords is just to save them as they are. Once saved, you query and match them with password provided by user. This approach is extremely bad because the passwords can be stolen over wire as well as when database is hacked. Most people use same password for multiple services, You are likely to expose all of them for all the users signed up on your website.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;"&lt;em&gt;Storing passwords in a plain text is a sin.&lt;/em&gt;" - J ✝️&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;One approach would be to &lt;strong&gt;encrypt&lt;/strong&gt; the password and then store it.&lt;br&gt;
&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fres.cloudinary.com%2Fspringboard-images%2Fimage%2Fupload%2Fq_auto%2Cf_auto%2Cfl_lossy%2Fwordpress%2F2018%2F07%2Fimage3.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fres.cloudinary.com%2Fspringboard-images%2Fimage%2Fupload%2Fq_auto%2Cf_auto%2Cfl_lossy%2Fwordpress%2F2018%2F07%2Fimage3.png" alt="encryption"&gt;&lt;/a&gt;Encryption and Descryption &lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;You chose a key with which you will mix the password to generate a random string using an algorithm.&lt;/li&gt;
&lt;li&gt;This password (gibberish text) will be stored in the database.&lt;/li&gt;
&lt;li&gt;At the time of authentication:&lt;/li&gt;
&lt;/ol&gt;

&lt;ul&gt;
&lt;li&gt;you can decrypt the password from database using the same key to generate a value and match it with password provided by user.&lt;/li&gt;
&lt;li&gt;Or you can encrypt the password at input with same key and match it with value stored in the database.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;There are many encryption algorithms which are available as &lt;a href="https://golang.org/pkg/crypto/" rel="noopener noreferrer"&gt;go&lt;/a&gt; libraries to work with. You can find same in other languages of your choice. The drawback with this approach is that if you can decrypt a password to it's original text, so can a hacker. if they are able to guess a key, every other user in your db is compromised too.&lt;/p&gt;
&lt;h1&gt;
  
  
  Hashing
&lt;/h1&gt;

&lt;p&gt;To compare password for authentication without decrypting them is made possible using a hash function. Hash function converts strings of random length to a fixed length string using some predefined algorithms. &lt;br&gt;
&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fds055uzetaobb.cloudfront.net%2Fbrioche%2Fuploads%2F3MYOioyY35-screen-shot-2016-06-25-at-32727-pm.png%3Fwidth%3D1200" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fds055uzetaobb.cloudfront.net%2Fbrioche%2Fuploads%2F3MYOioyY35-screen-shot-2016-06-25-at-32727-pm.png%3Fwidth%3D1200" alt="hashing"&gt;&lt;/a&gt;Hashing&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Text generated by hashing functions is not reversible unlike encryption.&lt;/li&gt;
&lt;li&gt;The output will be of fixed length for inputs of variable lengths.&lt;/li&gt;
&lt;li&gt;Even a small change in input text would generate a totally different &lt;em&gt;hash&lt;/em&gt;.&lt;/li&gt;
&lt;li&gt;For same input same hashes is generated. We can prevent this using salt and pepper.&lt;/li&gt;
&lt;/ol&gt;
&lt;h2&gt;
  
  
  Salt and Pepper
&lt;/h2&gt;

&lt;p&gt;We would need to add a some bytes to the password before passing in to a hashing function. As hashes cannot be decrypted, but still a person can generate a &lt;a href="https://en.wikipedia.org/wiki/Rainbow_table" rel="noopener noreferrer"&gt;rainbow table&lt;/a&gt; which is a precomputed table of commonly used passwords and their hashing functions. The hacker can match the hashes to the database hashes and will be able to tell the password. This would be prevented if a unique and random string is added to password which before saving a hash. &lt;br&gt;
 &lt;code&gt;saltedhash(password) = hash(password || salt)&lt;/code&gt;&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;The salt would be unique for each password. Hence, all the hashes would be unique.&lt;/li&gt;
&lt;li&gt;The salt is not a private entity, it can be saved along with hash as a part of hash or in a different field.&lt;/li&gt;
&lt;li&gt;If two users use the same password, when added with salts, their generated hash would be different.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;strong&gt;&lt;em&gt;Pepper&lt;/em&gt;&lt;/strong&gt; are also random strings that are added to passwords, they differ from the salt in the fact that they are not unique per user, they are same across all application. They are not stored in database necessarily. We will use them as environment variable in our application demo.&lt;/p&gt;
&lt;h1&gt;
  
  
  Hands On
&lt;/h1&gt;

&lt;ol&gt;
&lt;li&gt;Signup for an online free &lt;a href="https://www.elephantsql.com/" rel="noopener noreferrer"&gt;postgres database&lt;/a&gt; service and get &lt;code&gt;host, port, username, dbname and password&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;Fork and clone the project from github &lt;a href="https://github.com/erdahuja/blog-auth-system" rel="noopener noreferrer"&gt;here&lt;/a&gt;.&lt;/li&gt;
&lt;li&gt;Edit database credentials (or use provided).&lt;/li&gt;
&lt;li&gt;Run in the root of the project &lt;code&gt;go run main.go&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;The project consists of home, login, signup, profile and accounts page. To navigate to profile and accounts page you would need to have a token (explained shortly).&lt;/li&gt;
&lt;li&gt;On every restart of server, the database would reset. You can comment out the code &lt;code&gt;setUpDB&lt;/code&gt; for so in &lt;code&gt;main.go&lt;/code&gt; at root. 
&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fthepracticaldev.s3.amazonaws.com%2Fi%2Fzmq8tmhlvmse6wbv9gbs.png" alt="Preview"&gt;
&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;To understand application of hashing we would first need to have fields like password and a password-hash.&lt;/p&gt;
&lt;h1&gt;
  
  
  User Model
&lt;/h1&gt;

&lt;blockquote&gt;
&lt;p&gt;The gorm tag (&lt;code&gt;gorm:"-"&lt;/code&gt;) ignores the password field because we never store password in the database. We would store explicitly defined password hash.&lt;/p&gt;
&lt;/blockquote&gt;
&lt;h1&gt;
  
  
  Sign Up Process
&lt;/h1&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fthepracticaldev.s3.amazonaws.com%2Fi%2F5k9hl7icjx4vgaslvgxz.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fthepracticaldev.s3.amazonaws.com%2Fi%2F5k9hl7icjx4vgaslvgxz.png" alt="Sign up process"&gt;&lt;/a&gt;&lt;br&gt;
Use &lt;a href="https://godoc.org/golang.org/x/crypto/bcrypt#GenerateFromPassword" rel="noopener noreferrer"&gt;&lt;code&gt;bcrypt.GenerateFromPassword(password, cost)&lt;/code&gt;&lt;/a&gt; to get a hash for the password. The second argument is the cost that is how much work is needed to hash the password. It would change in future when computer gets more powerful. Right now Default Cost is 10.&lt;br&gt;
&lt;/p&gt;
&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;
&lt;br&gt;
The code snippet above uses the sign up steps. You can find full working in project repository at path &lt;code&gt;/dev-blog/services/signup.go&lt;/code&gt;.
&lt;h1&gt;
  
  
  Login Process
&lt;/h1&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fthepracticaldev.s3.amazonaws.com%2Fi%2Fb14jhy8z4vastjrcqng2.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fthepracticaldev.s3.amazonaws.com%2Fi%2Fb14jhy8z4vastjrcqng2.png" alt="Login Process"&gt;&lt;/a&gt;&lt;br&gt;
Use &lt;a href="https://godoc.org/golang.org/x/crypto/bcrypt#CompareHashAndPassword" rel="noopener noreferrer"&gt;&lt;code&gt;bcrypt.CompareHashAndPassword(password, cost)&lt;/code&gt;&lt;/a&gt; to  compare hashed password to it's plain text equivalent.&lt;/p&gt;


&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;
&lt;br&gt;
The code snippet above uses the sign up steps. You can find full working in project repository at path &lt;code&gt;/dev-blog/services/login.go&lt;/code&gt;.
&lt;h1&gt;
  
  
  Web server are stateless
&lt;/h1&gt;

&lt;p&gt;The servers handles each request independently. It does not save any data from client requests to do stuff and responds. Each request has everything it needs from server and get a response. &lt;br&gt;
How to make server remember what you did some time ago on the website?&lt;br&gt;
Frankly, we don't. we let clients tell in each request who they are and what resources they need. Login each time while browsing is a tedious task, so after login once, we sign in a &lt;a href="![Cookie](https://thepracticaldev.s3.amazonaws.com/i/p4rl31fjyk2yegfb536g.png)"&gt;&lt;strong&gt;cookie&lt;/strong&gt;&lt;/a&gt; (data stored in the computer), so each time you browse a website, the browser sends the cookie with each request to the linked website. We will use this cookie data to verify user. This authentication data stored in cookie is called a &lt;code&gt;Remember Token&lt;/code&gt;. We have added this in the user schema too earlier. &lt;/p&gt;

&lt;p&gt;Remember token is a series random bytes of a certain length.&lt;br&gt;
We create this using following snippet:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// GenerateRememberToken returns a 32 bytes random token string using
// crypto/rand packages
func GenerateRememberToken() string {
    b := make([]byte, 32) // create a placeholder of 32 bytes (big enough)
    _, err := rand.Read(b) // Fill it with random bytes
    Must(err)
    return base64.URLEncoding.EncodeToString(b) // encoded string
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;


&lt;p&gt;Add this token to field in user object (RememberToken) and save to database.&lt;/p&gt;

&lt;p&gt;The following snippet helps in setting up cookie for the website.&lt;br&gt;
&lt;/p&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;    cookie := http.Cookie{
        Name:     "remember_token",
        Value:    user.RememberToken,
        HttpOnly: true,
                Expires: time.Now().Add(24 * time.Hour),
    }
    http.SetCookie(w, &amp;amp;cookie)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;


&lt;p&gt;It is very easy to see cookie in a browser and temper it. To protect our cookie from temporary we can use some options like HttpOnly (disallow javascript to temper cookie) or &lt;strong&gt;not&lt;/strong&gt; store the remember token in plain text at all.&lt;/p&gt;

&lt;p&gt;Here's your editable cookie: &lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fthepracticaldev.s3.amazonaws.com%2Fi%2Fjfxm04nk1r11d4hi3t8e.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fthepracticaldev.s3.amazonaws.com%2Fi%2Fjfxm04nk1r11d4hi3t8e.png" alt="Cookie in browser"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;We would rather save a hash of same token and on each request compare it with token provided from cookie.&lt;br&gt;
If we use bcrypt hashing, we would:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Lookup a user from database using email&lt;/li&gt;
&lt;li&gt;Hash the user's password with salt which is part of PasswordHash field&lt;/li&gt;
&lt;li&gt;Compare
But in case of remember token we cannot lookup a user from database since we are not storing RememberToken in db (only it's hash), we need a way to hash value from cookie first, then find the user.
The simple hashing function like &lt;a href="https://golang.org/pkg/crypto/hmac/#New" rel="noopener noreferrer"&gt;crypto/hmac&lt;/a&gt; would work.
&lt;/li&gt;
&lt;/ol&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// Hash generates hash for given input with secret key of hmac object
func Hash(token string) string {
       // sha256 is hashing algorithm
       // key can be taken from env variable too
    h := hmac.New(sha256.New, []byte("somekey"))
    h.Reset() // Clear previous leftover bytes
    h.Write([]byte(token))
    b := h.Sum(nil)
    return base64.URLEncoding.EncodeToString(b)
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;
utils/utils.go




&lt;p&gt;Here's how we will use all of this:&lt;br&gt;
&lt;/p&gt;
&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;

&lt;p&gt;&lt;br&gt;&lt;br&gt;
These signIn method will be called once after &lt;em&gt;login&lt;/em&gt; or &lt;em&gt;sign up&lt;/em&gt; and a remember token would be stored in the browser as cookie and it's hash version would be saved to the database. &lt;/p&gt;

&lt;p&gt;Now when user visits authenticated pages like profile or accounts. We can use the token came into request and compare it with the hashed version stored in the database. &lt;br&gt;
&lt;/p&gt;
&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;
&lt;br&gt;
Since we know in &lt;em&gt;hashing&lt;/em&gt; for same input string same output is generated. We can hash the remember token came in cookie and compare.&lt;br&gt;
&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;
&lt;br&gt;
These are a few parts of building an authentication system. The full working project is available &lt;a href="https://github.com/erdahuja/blog-auth-system" rel="noopener noreferrer"&gt;here&lt;/a&gt;. This also has html templates parsing in go about which i wrote an in depth guide here:&lt;br&gt;
&lt;div class="ltag__link"&gt;
  &lt;a href="/dpkahuja" class="ltag__link__link"&gt;
    &lt;div class="ltag__link__pic"&gt;
      &lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F203744%2F7c85361d-d0ea-49e9-aa0b-74448e24f08d.jpg" alt="dpkahuja"&gt;
    &lt;/div&gt;
  &lt;/a&gt;
  &lt;a href="/dpkahuja/learn-and-use-templates-in-go-5cei" class="ltag__link__link"&gt;
    &lt;div class="ltag__link__content"&gt;
      &lt;h2&gt;Unlock SSR Superpowers (Learn and Use Templates In Go)&lt;/h2&gt;
      &lt;h3&gt;Deepak Ahuja 👨‍💻 ・ Jul 31 '19&lt;/h3&gt;
      &lt;div class="ltag__link__taglist"&gt;
        &lt;span class="ltag__link__tag"&gt;#go&lt;/span&gt;
        &lt;span class="ltag__link__tag"&gt;#webdev&lt;/span&gt;
        &lt;span class="ltag__link__tag"&gt;#beginners&lt;/span&gt;
        &lt;span class="ltag__link__tag"&gt;#tutorial&lt;/span&gt;
      &lt;/div&gt;
    &lt;/div&gt;
  &lt;/a&gt;
&lt;/div&gt;
&lt;br&gt;
The project structure is simplified for easier understanding with error handling, separate handler file for each route etc. Thanks for making it till last.&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fthepracticaldev.s3.amazonaws.com%2Fi%2Fco5tn743v039g88aecvn.gif" alt="Yay"&gt;&lt;br&gt;
Please feel free to comment any doubts about unclear things or say hello on &lt;a href="https://twitter.com/dpkahuja" rel="noopener noreferrer"&gt;twitter&lt;/a&gt;.&lt;br&gt;
My other work: &lt;br&gt;
&lt;div class="ltag__link"&gt;
  &lt;a href="/dpkahuja" class="ltag__link__link"&gt;
    &lt;div class="ltag__link__pic"&gt;
      &lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F203744%2F7c85361d-d0ea-49e9-aa0b-74448e24f08d.jpg" alt="dpkahuja"&gt;
    &lt;/div&gt;
  &lt;/a&gt;
  &lt;a href="/dpkahuja/get-a-taste-of-concurrency-in-go-1e58" class="ltag__link__link"&gt;
    &lt;div class="ltag__link__content"&gt;
      &lt;h2&gt;Get a Taste of Concurrency in Go&lt;/h2&gt;
      &lt;h3&gt;Deepak Ahuja 👨‍💻 ・ Aug 7 '19&lt;/h3&gt;
      &lt;div class="ltag__link__taglist"&gt;
        &lt;span class="ltag__link__tag"&gt;#go&lt;/span&gt;
        &lt;span class="ltag__link__tag"&gt;#beginners&lt;/span&gt;
        &lt;span class="ltag__link__tag"&gt;#showdev&lt;/span&gt;
        &lt;span class="ltag__link__tag"&gt;#webdev&lt;/span&gt;
      &lt;/div&gt;
    &lt;/div&gt;
  &lt;/a&gt;
&lt;/div&gt;


</description>
      <category>webdev</category>
      <category>security</category>
      <category>tutorial</category>
      <category>beginners</category>
    </item>
    <item>
      <title>Health for developers</title>
      <dc:creator>Deepak Ahuja 👨‍💻</dc:creator>
      <pubDate>Fri, 09 Aug 2019 16:00:29 +0000</pubDate>
      <link>https://dev.to/dpkahuja/health-for-developers-1g27</link>
      <guid>https://dev.to/dpkahuja/health-for-developers-1g27</guid>
      <description>&lt;p&gt;Long sitting hours leads to so many health problems. i am seeing lot of hip and heart opening exercises listed to cure "office bend".&lt;br&gt;
We spend most waking hours on front of screen, in a chair.&lt;/p&gt;

&lt;p&gt;For IT professionals back problems, mental stress etc are very common. What's your take on this? what you do to avoid it?&lt;/p&gt;

&lt;p&gt;I am thinking of publishing a list of exercises under 20 minutes, which can help. what should be on it?&lt;/p&gt;

</description>
      <category>discuss</category>
    </item>
    <item>
      <title>Unlock SSR Superpowers (Learn and Use Templates In Go)</title>
      <dc:creator>Deepak Ahuja 👨‍💻</dc:creator>
      <pubDate>Wed, 31 Jul 2019 16:13:54 +0000</pubDate>
      <link>https://dev.to/dpkahuja/learn-and-use-templates-in-go-5cei</link>
      <guid>https://dev.to/dpkahuja/learn-and-use-templates-in-go-5cei</guid>
      <description>&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fcdn-images-1.medium.com%2Fmax%2F800%2F1%2Anq-3AgPhq3vj2zewZvFzNA.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fcdn-images-1.medium.com%2Fmax%2F800%2F1%2Anq-3AgPhq3vj2zewZvFzNA.png"&gt;&lt;/a&gt;&lt;/p&gt;
Photo by John Doyle Unsplash



&lt;p&gt;While developing several full stack apps over years, I realised some apps don’t&lt;br&gt;
need a full fledged frontend application running. Most of these apps serve&lt;br&gt;
static content with dynamic values fitted here and there. For example, consider&lt;br&gt;
your social media feed, each post of a certain type looks same but it gets&lt;br&gt;
populated with data specific to that user. They use some sort of templating to&lt;br&gt;
achieve it.&lt;/p&gt;
&lt;h3&gt;
  
  
  What are templates?
&lt;/h3&gt;

&lt;p&gt;Templates are essentially text files that are used to create dynamic content.&lt;br&gt;
For instance the following javascript function takes “name” as argument and&lt;br&gt;
produce different strings.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fcdn-images-1.medium.com%2Fmax%2F800%2F1%2Ak1QNSXwHwS2ZfUtg_rgseA.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fcdn-images-1.medium.com%2Fmax%2F800%2F1%2Ak1QNSXwHwS2ZfUtg_rgseA.png"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;We can also use same principal to generate web pages in Go. Web templates allow&lt;br&gt;
us to serve personalised results to users. Generating web templates using string&lt;br&gt;
concatenation is a tedious tasks. It can also lead to injection attacks.&lt;/p&gt;
&lt;h3&gt;
  
  
  Templates in go
&lt;/h3&gt;

&lt;p&gt;There two packages in go to work with templates:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt; &lt;a href="https://golang.org/pkg/text/template/" rel="noopener noreferrer"&gt;text/templates&lt;/a&gt; (Used for generating
textual output)&lt;/li&gt;
&lt;li&gt; &lt;a href="https://golang.org/pkg/html/template/" rel="noopener noreferrer"&gt;html/templates&lt;/a&gt; (Used for generating
HTML output safe against code injection)&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Both of them basically have same interface with subtle web specific differences&lt;br&gt;
in latter like encoding script tags to prevent them from running, parsing maps&lt;br&gt;
as json in view.&lt;/p&gt;
&lt;h3&gt;
  
  
  Our First Template
&lt;/h3&gt;


&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;
Web template in go




&lt;ol&gt;
&lt;li&gt; The extension of template file could be anything. We are using &lt;code&gt;.gohtml&lt;/code&gt; so that
it is supported development tools across IDEs.&lt;/li&gt;
&lt;li&gt; “Actions” — data evaluations or control structures — is delimited by&lt;code&gt;{{&lt;/code&gt;and&lt;code&gt;}}&lt;/code&gt;.
The data evaluated inside it is called &lt;em&gt;Pipeline&lt;/em&gt;. Anything outside them is send
to output unchanged.&lt;/li&gt;
&lt;/ol&gt;


&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;
Code to execute the template with data: Use go run main.go to see output




&lt;p&gt;You can parse multiple files on line:10 as comma separated strings (&lt;em&gt;path to&lt;br&gt;
file&lt;/em&gt;) or parse all files inside a directory. For example:&lt;/p&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;tpl, err := template.ParseFiles(“index1.gohtml”, “index2.gohtml”)
tpl, err := template.ParseGlob("views/templates/*")
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;
&lt;ol&gt;
&lt;li&gt; It returns a template container (&lt;em&gt;here&lt;/em&gt; &lt;em&gt;called tpl&lt;/em&gt;) and error. We can use our
data to execute &lt;em&gt;tpl *by calling method Execute&lt;/em&gt;. *In case of multiple
templates, The name of template will be passed as 2nd argument while data being
3rd.&lt;/li&gt;
&lt;li&gt; We define our data structure (here type &lt;em&gt;struct&lt;/em&gt;). It could be anything in go
slice, map, struct, slice-of-structs, structs-of-slice of structs. We will see
each of them shortly.&lt;/li&gt;
&lt;li&gt; The data is fetched using *dot (aka cursor). *We use it to access variables of
data inside templates. Remember the identifiers in provided data have to start
with &lt;a href="https://golang.org/doc/effective_go.html#names" rel="noopener noreferrer"&gt;Capital Case&lt;/a&gt;. We can use
them to initialise a variable inside Actions like&lt;code&gt;$myCoupon := .Coupon&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt; We can output the execution result to web page or standard output because
template Execute method takes any value which implements type Writer interface.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;It renders as plain text in output console, but If we use it to send as response&lt;br&gt;
to web request it will be rendered as a web page enabling us to use HTML tags.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fcdn-images-1.medium.com%2Fmax%2F800%2F1%2AMOUSBb8bEXN38xcOqrFXng.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fcdn-images-1.medium.com%2Fmax%2F800%2F1%2AMOUSBb8bEXN38xcOqrFXng.png"&gt;&lt;/a&gt;&lt;/p&gt;
Standard template output



&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fthepracticaldev.s3.amazonaws.com%2Fi%2Frnxseyg3xsa8dee2uycu.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fthepracticaldev.s3.amazonaws.com%2Fi%2Frnxseyg3xsa8dee2uycu.png"&gt;&lt;/a&gt;&lt;/p&gt;
Web template output



&lt;blockquote&gt;
&lt;p&gt;&lt;em&gt;It is preferred to do the parsing job inside init function and execution at&lt;br&gt;
required places.&lt;/em&gt;&lt;/p&gt;
&lt;/blockquote&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;func init() {
 // Must is a helper that wraps a function returning  
 // (*Template, error) and panics if the error is non-nil.
 tpl = template.Must(template.ParseGlob(“templates/*”))
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;
&lt;h3&gt;
  
  
  Using different data structures in web templates
&lt;/h3&gt;
&lt;h3&gt;
  
  
  Slice (or Array)
&lt;/h3&gt;

&lt;p&gt;Let’s consider a&lt;br&gt;
&lt;a href="https://medium.com/rungo/the-anatomy-of-slices-in-go-6450e3bb2b94" rel="noopener noreferrer"&gt;slice&lt;/a&gt; of&lt;br&gt;
strings:&lt;br&gt;
&lt;/p&gt;
&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;
Slice of strings in go




&lt;p&gt;This can be used in template by ranging over the Slice (also array) inside&lt;br&gt;
&lt;em&gt;Actions&lt;/em&gt;. If the value of the pipeline has length zero, nothing will be&lt;br&gt;
executed&lt;br&gt; otherwise, dot(aka &lt;em&gt;cursor&lt;/em&gt;) is set to the successive elements of&lt;br&gt;
the Slice (also array) and template is executed.&lt;/p&gt;


&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;
Template for range over slice




&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fcdn-images-1.medium.com%2Fmax%2F800%2F1%2AEFozd10reyZRw2BacjG45A.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fcdn-images-1.medium.com%2Fmax%2F800%2F1%2AEFozd10reyZRw2BacjG45A.png"&gt;&lt;/a&gt;&lt;/p&gt;
Web template output



&lt;h3&gt;
  
  
  Map
&lt;/h3&gt;

&lt;p&gt;Let’s consider a &lt;a href="https://blog.golang.org/go-maps-in-action" rel="noopener noreferrer"&gt;Map&lt;/a&gt; data&lt;br&gt;
structure:&lt;/p&gt;


&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;
Map in go




&lt;p&gt;The value of the pipeline inside &lt;em&gt;Action&lt;/em&gt; is a map. If there are no key values&lt;br&gt;
pairs in map, nothing is output, otherwise, dot (aka &lt;em&gt;cursor&lt;/em&gt;) is set to the&lt;br&gt;
successive elements of the map and template is executed with &lt;code&gt;$key&lt;/code&gt; taking each&lt;br&gt;
key, &lt;code&gt;$val&lt;/code&gt; taking the respective value. If keys are of basic type with a&lt;br&gt;
defined order ("comparable"), the elements will be visited in sorted key order.&lt;br&gt;
&lt;/p&gt;
&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;
Web template for map




&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fcdn-images-1.medium.com%2Fmax%2F800%2F1%2AjT6bPWb-kWnTC51JZekAxw.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fcdn-images-1.medium.com%2Fmax%2F800%2F1%2AjT6bPWb-kWnTC51JZekAxw.png"&gt;&lt;/a&gt;&lt;/p&gt;
Web template output



&lt;h3&gt;
  
  
  Struct
&lt;/h3&gt;

&lt;p&gt;Let’s consider a &lt;a href="https://gobyexample.com/structs" rel="noopener noreferrer"&gt;struct&lt;/a&gt; with collection of&lt;br&gt;
fields as declared&lt;br&gt;
&lt;a href="https://stackoverflow.com/questions/26866879/initialize-nested-struct-definition-in-golang" rel="noopener noreferrer"&gt;inline&lt;/a&gt;:&lt;br&gt;
&lt;/p&gt;
&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;
Struct in go




&lt;p&gt;The name of a field of the data struct, preceded by a period, such as &lt;code&gt;.Name&lt;/code&gt; is&lt;br&gt;
the argument in template. The result is the value of the field. Field&lt;br&gt;
invocations may be chained: &lt;code&gt;.Field1.Field2&lt;/code&gt;. Fields can also be evaluated on&lt;br&gt;
variables, including chaining: &lt;code&gt;$x.Field1.Field2&lt;/code&gt; . The following template shows&lt;br&gt;
the fields store in variables and then evaluated in &lt;em&gt;Actions&lt;/em&gt;.&lt;/p&gt;


&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;
Web template for struct in go




&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fcdn-images-1.medium.com%2Fmax%2F800%2F1%2A3faMXA_vAGGpv-2Uxt02XA.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fcdn-images-1.medium.com%2Fmax%2F800%2F1%2A3faMXA_vAGGpv-2Uxt02XA.png"&gt;&lt;/a&gt;&lt;/p&gt;
&lt;br&gt;Web template output



&lt;h3&gt;
  
  
  Slice of structs
&lt;/h3&gt;

&lt;p&gt;Let’s consider a slice of &lt;a href="https://gobyexample.com/structs" rel="noopener noreferrer"&gt;struct&lt;/a&gt;s :&lt;br&gt;
&lt;/p&gt;
&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;
Slice to struct in go




&lt;p&gt;We use range to iterate over slice. The value of the pipeline in Action must be&lt;br&gt;
an array (or slice). If the value of the length of slice is zero, nothing is&lt;br&gt;
output; otherwise, dot (aka &lt;em&gt;cursor&lt;/em&gt;) is set to the successive elements of the&lt;br&gt;
array, slice and Template is executed.&lt;br&gt;
&lt;/p&gt;
&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;
Web template for slice of structs




&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fcdn-images-1.medium.com%2Fmax%2F800%2F1%2A5ysnJExJqRAhWUNoZaaF5w.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fcdn-images-1.medium.com%2Fmax%2F800%2F1%2A5ysnJExJqRAhWUNoZaaF5w.png"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Like this different data structures in go can be combined to make useful&lt;br&gt;
templates.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;A note on Conditionals in templates:&lt;/p&gt;

&lt;p&gt;It is also possible to write conditionals templates &lt;code&gt;{{if pipeline}} T1 {{else if pipeline}} T0 {{end}}&lt;/code&gt; like this. This gives us amazing abilities to generate dynamic content. If value of pipeline is empty (that is, false, 0, any  nil pointer or interface value, and any array, slice, map, or  string of length zero), T0 is executed else T1 is executed.&lt;/p&gt;
&lt;/blockquote&gt;
&lt;h3&gt;
  
  
  Function In templates
&lt;/h3&gt;

&lt;p&gt;To send a function in go template we can use, by default, no functions are&lt;br&gt;
defined in the template but the &lt;code&gt;Funcs&lt;/code&gt; method on template can be used to add&lt;br&gt;
function by creating mappings like this:&lt;/p&gt;

&lt;p&gt;&lt;code&gt;template.Must(template.New(“”).Funcs(fm).ParseFiles(“index.gohtml”))&lt;/code&gt;&lt;br&gt;
&lt;/p&gt;
&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;
Initialising a function for template in Go




&lt;p&gt;To create a mapping from names to functions we need to use type &lt;code&gt;FuncMap&lt;/code&gt;. Each&lt;br&gt;
function must have either a single return value, or two return values of which&lt;br&gt;
the second has type error.&lt;/p&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;type FuncMap map[]interface{}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;
&lt;p&gt;On line:7, we have defined a mapping of function &lt;em&gt;monthDayYear to *name&lt;/em&gt;&lt;br&gt;
fdateMDY. &lt;em&gt;Now this function can be used inside template. Remember dot (aka&lt;br&gt;
*cursor&lt;/em&gt;) holds the data provided to template.&lt;br&gt;
&lt;/p&gt;
&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;
Web template in go using function




&lt;p&gt;These are various ways we can use templates in Go. I will publish how to use&lt;br&gt;
what we learn’t to build our own working web pages using nested templates. You&lt;br&gt;
can drop me hello with questions and feedback on&lt;br&gt;
&lt;a href="https://twitter.com/Dpkahuja" rel="noopener noreferrer"&gt;twitter&lt;/a&gt;. Please consider leaving a feedback and share with anyone who may benefit from it. Thanks!&lt;/p&gt;

</description>
      <category>go</category>
      <category>webdev</category>
      <category>beginners</category>
      <category>tutorial</category>
    </item>
  </channel>
</rss>
