<?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[Learning Cloud Native Go - Medium]]></title>
        <description><![CDATA[Tutorials about Cloud Native Go - Medium]]></description>
        <link>https://medium.com/learning-cloud-native-go?source=rss----587178f14a6e---4</link>
        <image>
            <url>https://cdn-images-1.medium.com/proxy/1*TGH72Nnw24QL3iV9IOm4VA.png</url>
            <title>Learning Cloud Native Go - Medium</title>
            <link>https://medium.com/learning-cloud-native-go?source=rss----587178f14a6e---4</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 07:28:22 GMT</lastBuildDate>
        <atom:link href="https://medium.com/feed/learning-cloud-native-go" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Setting Up a Fedora 31 Workstation for Go Cloud Native Application Development]]></title>
            <link>https://medium.com/learning-cloud-native-go/setting-up-a-fedora-31-workstation-for-go-cloud-native-application-development-77700467bf7b?source=rss----587178f14a6e---4</link>
            <guid isPermaLink="false">https://medium.com/p/77700467bf7b</guid>
            <category><![CDATA[fedora]]></category>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[linux]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[golang]]></category>
            <dc:creator><![CDATA[Dumindu Madunuwan]]></dc:creator>
            <pubDate>Sun, 17 Nov 2019 15:39:49 GMT</pubDate>
            <atom:updated>2020-03-20T01:46:47.184Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DlZiZUsDq1mkY5MSDV6ZcA.png" /><figcaption><a href="https://wallhaven.cc/w/p8jgze">wallhaven.cc/w/p8jgze</a></figcaption></figure><p>If you are new to Linux and would like to install the Fedora 31 workstation into an empty hard drive, follow the <a href="https://wiki.archlinux.org/index.php/Partitioning">partitioning page of arch wiki</a> . For a PC with 1Tb hard drive and 16GB ram, we are following bellow partition schema.</p><p>▸ 500mb for EFI system partition/ boot loaders: /boot/efi <br>▸ 50 GB for operating system files: / <br>▸ 20GB for swap swap <br>▸ Rest for /home</p><p>01. <strong>Update your system</strong><br>~<em>Yeah! First things first</em> 😃</p><pre>sudo dnf update</pre><p>02. <strong>Installing zsh and powerline</strong><br>~<em> Why not</em>?</p><p>▸ sudo yum install zsh <br>▸ sh -c “$(curl -fsSL https://raw.githubusercontent.com/robbyrussell/oh-my-zsh/master/tools/install.sh)&quot; to install <a href="https://github.com/robbyrussell/oh-my-zsh#via-curl">oh-my-zsh</a>. <br>▸ git clone — depth=1 <a href="https://github.com/romkatv/powerlevel10k.git">https://github.com/romkatv/powerlevel10k.git</a> $ZSH_CUSTOM/themes/powerlevel10k to install <a href="https://github.com/romkatv/powerlevel10k#oh-my-zsh">powerlevel10k</a> theme. And set ZSH_THEME=powerlevel10k/powerlevel10k in ~/.zshrc. <br>▸ git clone <a href="https://github.com/zsh-users/zsh-autosuggestions">https://github.com/zsh-users/zsh-autosuggestions</a> ${ZSH_CUSTOM:-~/.oh-my-zsh/custom}/plugins/zsh-autosuggestions to install <a href="https://github.com/zsh-users/zsh-autosuggestions/blob/master/INSTALL.md#oh-my-zsh">zsh-autosuggestions</a> plugin. And add zsh-autosuggestions to plugins=() in ~/.zshrc. <br>▸ sudo lchsh $USER to set zsh as the default shell and restart the terminal.</p><p><strong>03. Installing Tilix</strong><br>~ <em>Tiling terminal matters…</em></p><pre>sudo dnf install tilix</pre><p>04. <strong>Installing Golang</strong><br>~ <em>Let’s Go…</em></p><p>▸ Download the latest go binary via <a href="https://golang.org/dl/">https://golang.org/dl/</a> . <br>▸ sudo tar -C /usr/local -xzf ~/Downloads/go1.13.4.linux-amd64.tar.gz to extract the archive into /usr/local .<br>▸ Add following line to ~/.zshrc file.</p><pre>export PATH=$PATH:/usr/local/go/bin<br>export GOPATH=$HOME/dev/go</pre><blockquote><em>💡</em> $HOME/dev is my workspace of saving all codes. You can set this any place you want; The default GOPATH is $HOME/go .</blockquote><p>▸ Run source ~/.zshrc or restart the terminal.</p><p><strong>05. Installing Docker</strong><br>~ <em>Sorry Podman! </em>🐳</p><blockquote><em>💡 </em>Fedora 31 has been enabled <a href="https://www.kernel.org/doc/Documentation/cgroup-v2.txt">cgroupsv2</a> by default. But, the container ecosystems and cloud native projects are not fully supported for those changes. Even the Docker alternative, <a href="https://podman.io/">Podman</a> is not a fully reliable replacement for Docker. So, we have to disable cgroupsv2 by editing the boot loader.</blockquote><p>▸ sudo nano /etc/default/grub <br> ▸ Add systemd.unified_cgroup_hierarchy=0 to GRUB_CMDLINE_LINUX . ex,</p><pre>GRUB_CMDLINE_LINUX=&quot;resume=UUID=633b0b8a-52ce-4a70-9f1b-397dd10cf148 rhgb quiet systemd.unified_cgroup_hierarchy=0&quot;</pre><p>▸ ⚠️ sudo grub2-mkconfig &gt; /boot/efi/EFI/fedora/grub.cfg or only if you not using efi boot sudo grub2-mkconfig &gt; /boot/grub2/grub.cfg .</p><p>Let’s install Docker via .rpm packages,<br>▸ Download containerd.io, docker-ce-cli and docker-ce packages from <a href="https://download.docker.com/linux/fedora/31/x86_64/stable/Packages/">https://download.docker.com/linux/fedora/31/x86_64/stable/Packages/</a> .<br>▸ The current version of Docker is 19.03.4, while writing this article. So install them via bellow commands or simply double click on .rpm files.</p><pre>sudo dnf install ~/Downloads/containerd.io-1.2.10–3.2.fc31.x86_64.rpm<br>sudo dnf install ~/Downloads/docker-ce-cli-19.03.4–3.fc31.x86_64.rpm<br>sudo dnf install ~/Downloads/docker-ce-19.03.4–3.fc31.x86_64.rpm</pre><p>▸ To install docker-compose, sudo dnf install docker-compose.<br>▸ To run Docker without sudo, sudo gpasswd -a ${USER} docker .<br>▸ To start Docker at system boot, sudo systemctl enable docker .<br>▸ Reboot the system.</p><p>06. <strong>Installing kubectl</strong><br>~<em>Hope you have access for clusters</em> ☸️</p><pre>curl -LO <a href="https://storage.googleapis.com/kubernetes-release/release/%60curl">https://storage.googleapis.com/kubernetes-release/release/`curl</a> -s <a href="https://storage.googleapis.com/kubernetes-release/release/stable.txt%60/bin/linux/amd64/kubectl">https://storage.googleapis.com/kubernetes-release/release/stable.txt`/bin/linux/amd64/kubectl</a></pre><pre>chmod +x ./kubectl<br>sudo mv ./kubectl /usr/local/bin/kubectl</pre><p>07. <strong>Installing Minikube</strong><br>~ <em>If you want to test cluster deployments locally</em></p><blockquote>Minikube relies on a hypervisor installation like <a href="https://www.virtualbox.org/wiki/Downloads">VirtualBox</a> or <a href="https://www.linux-kvm.org/">KVM</a> . Fedora uses the libvirt family of tools as its virtualization solution. <a href="https://www.linux-kvm.org/">KVM</a> comes with them. Let’s install them and enable running <em>libvirt tools without </em><em>sudo,</em></blockquote><p>▸ sudo dnf group install Virtualization <br>▸ sudo usermod -a -G libvirt $(whoami) &amp;&amp; newgrp libvirt</p><p>▸ Let’s install Minikube,</p><pre>curl -Lo minikube <a href="https://storage.googleapis.com/minikube/releases/latest/minikube-linux-amd64">https://storage.googleapis.com/minikube/releases/latest/minikube-linux-amd64</a></pre><pre>chmod +x minikube<br>sudo install minikube /usr/local/bin/</pre><p>▸ minikube config set vm-driver kvm2 to faster Minikube start up.</p><p>08. <strong>Installing Goland</strong><br>~ <em>Can use EAP builds for free</em></p><p>▸ Download <a href="https://www.jetbrains.com/go/download/#section=linux">Goland</a> or <a href="https://www.jetbrains.com/go/nextversion/">Goland early access program build</a> from <a href="https://www.jetbrains.com/">jetbrains.com</a>. The current Goland version while writing this is 2019.2.5. <br>▸ Extract tar.gz file and move GoLand directory to /opt/goland .</p><pre>sudo mv ~/Downloads/GoLand-2019.2.5/GoLand /opt/goland<br>sudo chmod -R 775 /opt/goland</pre><p>▸ Add .desktop for GoLand to open it via GNOME activities overview via sudo nano /usr/share/applications/jetbrains-goland.desktop</p><pre>[Desktop Entry]<br>Categories=Development;IDE;<br>Comment=A clever IDE to Go<br>Exec=&quot;/opt/goland/bin/goland.sh&quot; %f<br>Icon=/opt/goland/bin/goland.svg<br>Name=GoLand<br>StartupWMClass=jetbrains-goland<br>Terminal=false<br>Type=Application<br>Version=1.0</pre><p>09. <strong>Installing Sublime Text</strong><br>~<em>A text editor for code, markup and prose</em></p><pre>sudo rpm -v --import <a href="https://download.sublimetext.com/sublimehq-rpm-pub.gpg">https://download.sublimetext.com/sublimehq-rpm-pub.gpg</a></pre><pre>sudo dnf config-manager --add-repo <a href="https://download.sublimetext.com/rpm/stable/x86_64/sublime-text.repo">https://download.sublimetext.com/rpm/stable/x86_64/sublime-text.repo</a></pre><pre>sudo dnf install sublime-text</pre><p>10. <strong>Tweaking default UI</strong><br>~ <em>Because this is Linux</em></p><p>▸ To install GNOME tweak tool, sudo dnf install gnome-tweak-tool .<br>▸ Download and install custom icons and themes via <a href="https://www.gnome-look.org/">gnome-look.org</a> to /usr/share/themes, if it’s a theme; /usr/share/icons, if it’s an icon set.</p><blockquote>I like the cleaness of macOS UI. So, in here, I am using <a href="https://www.gnome-look.org/p/1335592/">Enso-gnome GTK3 theme</a> and <a href="https://www.gnome-look.org/p/1210856">Mojave-CT-Light</a> icons.</blockquote><p>▸ Change the theme and icon set via GNOME tweak tool. 💡 You can see more screenshots in the bottom of the page.</p><p><strong>11. Installing Firefox Nightly</strong><br>~<em>Because I love open source and the freedom it has.</em></p><blockquote><em>💭</em> By default Fedora comes with Firefox stable release. But I am using Nightly builds since Firefox 4 and trust me even Nightly builds also so stable these days.</blockquote><p>▸ To remove existing Firefox installtion, sudo dnf remove firefox <br>▸ Download Firefox Nightly build via <a href="https://www.mozilla.org/en-US/firefox/channel/desktop/#nightly">www.mozilla.org/en-US/firefox/channel/desktop/#nightly</a> and extract it to /opt/firefox <br>▸ Add .desktop for Firefox Nightly to open it via GNOME activities overview via sudo nano /usr/share/applications/firefox.desktop</p><pre>[Desktop Entry]<br>Version=1.0<br>Name=Firefox Nightly<br>GenericName=Web Browser<br>Comment=Browse the Web<br>Exec=/opt/firefox/firefox-bin %u<br>Icon=/opt/firefox/browser/chrome/icons/default/default128.png<br>Terminal=false<br>Type=Application<br>MimeType=text/html;text/xml;application/xhtml+xml;application/vnd.mozilla.xul+xml;text/mml;x-scheme-handler/http;x-scheme-handler/https;<br>StartupNotify=true<br>Categories=Network;WebBrowser;<br>Keywords=web;browser;internet;<br>Actions=new-window;new-private-window;</pre><pre>X-Desktop-File-Install-Version=0.24</pre><pre>[Desktop Action new-window]<br>Name=Open a New Window<br>Exec=/opt/firefox/firefox --new-window %u</pre><pre>[Desktop Action new-private-window]<br>Name=Open a New Private Window<br>Exec=/opt/firefox/firefox --private-window %u</pre><blockquote>For extra UI tweaks, I am using <a href="https://addons.mozilla.org/en-US/firefox/addon/night_owl/">night_owl</a> addon and <a href="https://gist.github.com/dumindu/94d6985c2a980a1698cb975719f9c653">userChrome.css</a> file attched to it.💡 You can see more screenshots in the bottom of the page.</blockquote><p><strong>12. Installing Slack</strong><br>~ <em>Especially for kubernetes.slack.com</em></p><p>▸ Download the .rpm file via <a href="https://slack.com/intl/en-sg/downloads/linux">slack.com/intl/en-sg/downloads/linux</a><br>▸ To install, you can either double click on the .rpm file or run sudo dnf install command via terminal.</p><p>13. Installing Postman<br>~ <em>Because we build APIs</em></p><pre>sudo su</pre><pre>flatpak remote-add --if-not-exists flathub <a href="https://flathub.org/repo/flathub.flatpakrepo">https://flathub.org/repo/flathub.flatpakrepo</a></pre><pre>flatpak install flathub com.getpostman.Postman</pre><p><strong>14. Installing official CLI applications of cluster providers</strong><br>~ <em>If you have privileges for production cluster.</em></p><p>▸ For Amazon EKS : <a href="https://github.com/weaveworks/eksctl#installation">https://github.com/weaveworks/eksctl#installation</a><br>▸ For Google cloud : <a href="https://cloud.google.com/sdk/docs/quickstart-linux">https://cloud.google.com/sdk/docs/quickstart-linux</a><br>▸ For IBM cloud : <a href="https://cloud.ibm.com/docs/cli?topic=cloud-cli-getting-started">https://cloud.ibm.com/docs/cli?topic=cloud-cli-getting-started</a></p><p><strong>15. Adding aliases<br></strong>~Productivity first!</p><p>Creating short aliases for long kubectl commands can increase the productivity a lot. For example, instead typing kubectl get po -n kube-system, with the following aliases we need to type kp kube-system.</p><p>To enable these, add follow lines to ~/.zshrc and run source ~/.zshrc.</p><pre>alias kn=&quot;kubectl get ns&quot;<br>alias kp=&quot;kubectl get po -n&quot;<br>alias kd=&quot;kubectl describe po -n&quot;<br>alias kdl=&quot;kubectl delete po -n&quot;<br>alias kdlf=&quot;kubectl delete po --grace-period=0 --force -n&quot;</pre><pre>alias ke=&quot;kubectl exec -it -n&quot;<br>alias kl=&quot;kubectl logs -f -n&quot;</pre><pre>alias ks=&quot;kubectl get service -n&quot;<br>alias ksa=&quot;kubectl get service --all-namespaces&quot;<br>alias kep=&quot;kubectl get endpoints&quot;</pre><pre>alias kca=&quot;kubectl config get-contexts&quot;<br>alias kcu=&quot;kubectl config use-context&quot;<br>alias kcv=&quot;kubectl config view&quot;</pre><pre>alias kt=&quot;kubectl -n kube-system describe secret $(kubectl -n kube-system get secret | grep eks-admin | awk &#39;{print $1}&#39;)&quot;<br><br>alias kpx=&quot;kubectl proxy&quot;</pre><p>This is how it looks like at the end…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WOWw1hske_jAv0Q_rl7Rzw.png" /><figcaption>Wallpaper: <a href="https://wallhaven.cc/w/p8jgze">https://wallhaven.cc/w/p8jgze</a></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wVEDdhu_B2hRlPvVvxJ40g.png" /><figcaption>GNOME activities overview</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Gu9XaXj5i5dZMEu4v5gX5g.png" /><figcaption>Firefox, Tilix, Gnome tweak tool with <a href="https://www.gnome-look.org/p/1335592/">Enso-gnome GTK3 theme</a> and <a href="https://www.gnome-look.org/p/1210856">Mojave-CT-Light</a> icons</figcaption></figure><p><em>Last but not least, <br></em>If you are new to Go and would like to learn “<strong>How to build a Dockerized RESTful API application using Go”</strong>, the first post of <a href="https://medium.com/learning-cloud-native-go"><strong>learning-cloud-native-go</strong></a><strong> </strong>publication will be helpful for you. You can read the same content <a href="https://learning-cloud-native-go.github.io/"><strong>via learning-cloud-native-go.github.io</strong></a> 👈 as well.</p><p><a href="https://medium.com/learning-cloud-native-go/lets-get-it-started-dc4634ef03b">Let’s Get It Started!</a></p><p>If you found any mistake or something I need to be changed, even a spelling or a grammar mistake, feel free to buzz me. See you on the next post. 👋</p><blockquote>⭐ <a href="https://github.com/learning-cloud-native-go/website">Contribute!</a> 🥤 <a href="https://www.buymeacoffee.com/dumindu">Buy me a coffee!</a> 🚀 <a href="https://github.com/dumindu/hire-me/">Hire me!</a></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=77700467bf7b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/learning-cloud-native-go/setting-up-a-fedora-31-workstation-for-go-cloud-native-application-development-77700467bf7b">Setting Up a Fedora 31 Workstation for Go Cloud Native Application Development</a> was originally published in <a href="https://medium.com/learning-cloud-native-go">Learning Cloud Native Go</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Let’s Get It Started!]]></title>
            <link>https://medium.com/learning-cloud-native-go/lets-get-it-started-dc4634ef03b?source=rss----587178f14a6e---4</link>
            <guid isPermaLink="false">https://medium.com/p/dc4634ef03b</guid>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Dumindu Madunuwan]]></dc:creator>
            <pubDate>Sun, 06 Oct 2019 22:33:29 GMT</pubDate>
            <atom:updated>2019-10-13T04:57:57.702Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Gs1cLsPT1FdiGZeI0h2RiQ.jpeg" /></figure><h4>Building a Dockerized RESTful API application using Go - microservices</h4><p>Cloud Native Application Development is a one way of speeding up building web applications, using micro-services, containers and orchestration tools. First, let’s see what is a cloud and what cloud native means.</p><h3>What is Cloud Native?</h3><p>There are many definitions for cloud and cloud native architecture. First let’s check the definitions given by<a href="https://www.redhat.com/"> RedHat</a> via their <a href="https://www.redhat.com/en/topics/cloud">Understanding cloud computing</a> and <a href="https://www.redhat.com/en/topics/cloud-native-apps">Understanding cloud-native applications</a> articles.</p><p><a href="https://www.redhat.com/en/topics/cloud">📖</a> <em>Clouds are </em><strong><em>pools of virtual resources</em></strong><em> (such as raw processing power, storage, or cloud-based applications) orchestrated by management and automation software so they can be accessed by users on-demand through self-service portals supported by automatic scaling and dynamic resource allocation.</em></p><p><a href="https://www.redhat.com/en/topics/cloud-native-apps">📖</a> <em>Cloud native applications are a </em><strong><em>collection of small, independent and loosely coupled services</em></strong><em> which are specifically designed to provide </em><strong><em>a fast and consistent development and automated management experience</em></strong><em> across private, public, and hybrid clouds.</em></p><p>I think, you are now quite clear about cloud and cloud native applications. The definition provided by <a href="https://www.cncf.io/">Cloud Native Computing Foundation,</a> explains that how Cloud native applications achieve a fast and consistent development.</p><p><a href="https://www.cncf.io/">📖</a> <em>Cloud native computing uses an open source software stack to deploy applications as </em><strong><em>microservices</em></strong><em>, packaging each part into its own </em><strong><em>container</em></strong><em>, and dynamically </em><strong><em>orchestrating</em></strong><em> those containers </em><strong><em>to optimize resource utilization</em></strong><em>. Cloud native technologies enable software developers to build great products faster.</em></p><blockquote>Explaining the concepts behind cloud native architecture is beyond the purpose of this article. But I would like to highly recommend you to read the first chapter of <a href="https://www.amazon.com/Cloud-Native-DevOps-Kubernetes-Applications/dp/1492040762">Cloud Native DevOps with Kubernetes</a> which is written by <a href="https://twitter.com/bitfield">John Arundel</a> and <a href="https://twitter.com/JustinDomingus">Justin Domingus</a>. You can get this as a free e-book via <a href="https://www.nginx.com/resources/library/cloud-native-devops-with-kubernetes/">NGINX resources</a> as well.</blockquote><p><a href="https://www.amazon.com/Cloud-Native-DevOps-Kubernetes-Applications/dp/1492040762">Cloud Native DevOps with Kubernetes: Building, Deploying, and Scaling Modern Applications in the Cloud</a></p><h3>The First Step</h3><p>This is the very beginning of this project. So, as the first step, we are going to discuss about “<strong>How to build a Dockerized RESTful API application using Go”</strong>. In the future discussions, we will discuss about <a href="https://kubernetes.io/">Kubernetes</a> and how to deploy our application in a cloud environment.</p><p>In this post, we are going to build a RESTful API application to manage a simple bookshelf. And in here, we are discussing,<br>01. Creating a new Go project.<br>02. Adding initial HTTP server.<br>03. Adding initial Docker files.<br>04. Adding initial configurations.<br>05. Adding <a href="https://github.com/go-chi/chi">Chi router</a>.<br>06. Adding <a href="https://github.com/rs/zerolog">Zerolog logger</a>.<br>07. Adding DB docker file.<br>08. Adding initial database migrations.<br>09. Adding <a href="http://gorm.io/">GORM</a>.<br>10. Adding initial books API routes.<br>11. Implementing RESTful handlers.<br>12. Adding <a href="https://github.com/go-playground/validator">Validator.v9</a>.</p><blockquote>⭐ <a href="https://github.com/learning-cloud-native-go/website">Contribute!</a> 🥤 <a href="https://www.buymeacoffee.com/dumindu">Buy me a coffee!</a> 🚀 <a href="https://github.com/dumindu/hire-me/">Hire me!</a></blockquote><p>The completed project can be found in <a href="https://github.com/learning-cloud-native-go/myapp"><strong>learning-cloud-native-go/myapp</strong></a> GitHub repository and you can check the code on each step by using step- branches of that repository. The completed API application supports the following API endpoints.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Xvoa32pqW7idYAo6Ztb2xA.png" /></figure><p>OK, Let’s get it started!</p><h3>Creating a new Go project</h3><h4>Creating a remote repository</h4><p>It’s a good practice to save the code in a remote repository. So, I am using <a href="https://github.com/learning-cloud-native-go/myapp"><strong>https://github.com/learning-cloud-native-go/myapp</strong></a> to store the code.</p><blockquote><em>💡</em> You can use <a href="https://github.com/">GitHub</a>, <a href="https://bitbucket.org/">Bitbucket</a>, <a href="https://gitlab.com/">GitLab</a> or any preferable version control repository hosting service to store the code.</blockquote><p>In here, I prefer to use myapp as the project name. But you can choose a better name according to the purpose of your application.</p><p>We are going to implement this application as a <a href="https://github.com/golang/go/wiki/Modules">Go module</a>. So, better use any folder <strong>outside the </strong><a href="https://golang.org/doc/code.html#GOPATH"><strong>GOPATH</strong></a> to store the code locally. In here, I am using dev folder inside my home folder.</p><pre>cd ~/dev<br>git clone git@github.com:learning-cloud-native-go/myapp.git</pre><h4>Creating a Go module</h4><blockquote><a href="https://github.com/golang/go/wiki/Modules#modules"><em>📖</em></a><em> </em>A Go module is a collection of related Go packages that are versioned together as a single unit. Most often, a version control repository contains exactly one module defined in the repository root. (<a href="https://github.com/golang/go/wiki/Modules#faqs--multi-module-repositories">Multiple modules are supported in a single repository</a>, but typically that would result in more work on an on-going basis than a single module per repository).</blockquote><p>Use go mod init command with the project name, inside the project folder to make it a <a href="https://blog.golang.org/using-go-modules">Go module</a>.</p><pre>cd myapp<br>go mod init myapp</pre><blockquote><em>💡</em> If you want to reuse this module inside another project, better use go mod init with either github.com/mycompany/myapp or mycompany.com/myapp.</blockquote><p>This creates the go.mod file with the following content,</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fc6d78dd664815577b64f9754e0f3c3c/href">https://medium.com/media/fc6d78dd664815577b64f9754e0f3c3c/href</a></iframe><blockquote><em>💭 </em>In the next steps, I assume you are inside the myapp folder while mentioning file paths and commands to run.</blockquote><h3>Adding initial HTTP server</h3><blockquote><em>💡</em> If you are a newcomer to Go, I recommend you to read the overview of the documentation of the <a href="https://golang.org/pkg/net/http/"><strong>net/http</strong></a><strong> </strong>package, the descriptions of <a href="https://golang.org/pkg/net/http/#ServeMux"><strong>ServeMux</strong></a> type and <a href="https://golang.org/pkg/net/http/#HandleFunc"><strong>HandleFunc</strong></a> &amp; <a href="https://golang.org/pkg/net/http/#ListenAndServe"><strong>ListenAndServe</strong></a> functions, before continuing this.</blockquote><p>It’s a convention to store executable packages inside cmd directory. So, let’s save this code under cmd/app/main.go.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6ab3e13e206280ac681ee631602ac2f0/href">https://medium.com/media/6ab3e13e206280ac681ee631602ac2f0/href</a></iframe><p>▸ You can use <em>go run cmd/app/main.go </em>command, to run it locally.<br>▸ You should see <em>Hello World! text while visit </em>localhost:8080<em> </em>in the browser.</p><blockquote><em>🔎</em> Search why we need to set custom timeouts on default <a href="https://golang.org/pkg/net/http/#Server">http.Server</a>.</blockquote><h3>Adding initial docker files</h3><p><a href="https://docs.docker.com/get-started/#docker-concepts">📖</a> <a href="https://www.docker.com/">Docker</a> is <strong>a platform</strong> for developers and sysadmins <strong>to develop, deploy, and run applications</strong> with <strong>containers</strong>.</p><p><a href="https://www.docker.com/resources/what-container">📖</a> A container is <strong>a standard unit of software</strong> that packages up code and all its dependencies so the application runs quickly and reliably from one computing environment to another.</p><blockquote><em>💡</em> If you are a newcomer to Docker, I recommend you to read <a href="https://www.docker.com/resources/what-container"><strong>What is a Container?</strong></a> article and its <a href="https://docs.docker.com/get-started/part2/"><strong>Get Started guild</strong></a> on its official documentation.</blockquote><h4>Adding a Dockerfile</h4><p>▸ I would like to store all Docker related files inside the docker folder in the project root, except the docker-compose.yml .<br>▸ We are going to add another Dockerfile for the database. So, let’s save this code under docker/app/Dockerfile .<br>▸ In here, we are using golang:1.13-alpine base image with gcc, musl-dev , git, bash packages.</p><blockquote><em>💡</em> If you don’t like to add an extra weight to your images by installing bash, just use builtin ash or /bin/sh shells.</blockquote><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2922b393a5c026df4b3bb50310156129/href">https://medium.com/media/2922b393a5c026df4b3bb50310156129/href</a></iframe><blockquote><em>🔎</em> Search the difference between golang, <em>golang</em>:alpine , <em>golang</em>:stretch , <em>alpine</em> and <em>stretch</em> Docker images.</blockquote><h4>Adding a docker-compose.yml</h4><p><a href="https://docs.docker.com/compose/">📖</a> Compose is a <strong>tool for defining and running multi-container Docker applications</strong>. With a single command, we can create and start all the services according to the content in the docker-compose.yml file.</p><blockquote><em>💡</em> If you are new to Docker Compose, I recommend you to read its <a href="https://docs.docker.com/compose/gettingstarted/"><strong>Get Started guild</strong></a> on its official documentation.</blockquote><p>As mentioned earlier, we keep the docker-compose.yml in the project root.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/286c971eade2167c8e2cfb0c0f3f5642/href">https://medium.com/media/286c971eade2167c8e2cfb0c0f3f5642/href</a></iframe><p>▸ You can use docker-compose build<em> </em>and docker-compose up commands, to build and run the application.<br>▸ You should see <em>Hello World! text while visit </em>localhost:8080<em> </em>in the browser.</p><h4>Support Docker multi-stage builds</h4><p>Docker images with the Go SDK is quite large. Because of Go is a <strong>statically compiled language</strong>, after creating the executable files, we don’t need the Go SDK and the codebase to run the application.</p><pre>golang      1.13-alpine      359MB<br>alpine      latest           5.58MB</pre><p>Docker multi-stage build is a new feature which is using a <strong>single Docker file</strong> with multiple stages to <strong>build the application in one environment</strong> and <strong>copy each executable and run on another environment</strong> to reduce the resources needed in the production environment.</p><p>Let’s update the docker/app/Dockerfile to support multi-stage builds.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a6a348dc8b870b6b13d4866890f5f977/href">https://medium.com/media/a6a348dc8b870b6b13d4866890f5f977/href</a></iframe><p>▸ After updating the Dockerfile, we need to rebuild and rerun the application.<br>▸ Always run docker-compose down before running docker-compose up to stop running containers and remove containers, networks, volumes, and images created by previous up commands.</p><blockquote><em>💡 </em>The docker images command shows all top-level Docker images with their ID, repository name, tag name and the size. You can use the docker rmi -f command with the image ID to delete any old images from your system.<br><em>💡</em> Better skip using Docker multi-stage builds in the development environment, due to we can reduce the build time of the second step.</blockquote><h3>Adding initial configurations</h3><p>If you remember the <a href="https://github.com/learning-cloud-native-go/myapp/blob/step-2/cmd/app/main.go">code of initial HTTP server</a> at <a href="https://github.com/learning-cloud-native-go/myapp/tree/step-2">step-2</a>, we have hard-coded the server port and timeout values with the code. Things like them should be configurable. So better extract them to a config package and use those config parameters in the code.</p><blockquote><em>💭</em> To store configurations, we can use many formats like .xml, .json, .env, .yaml, .toml files or systems like <a href="https://etcd.io/">etcd</a>, <a href="https://docs.aws.amazon.com/systems-manager/latest/userguide/systems-manager-parameter-store.html">AWS Parameter Store</a>, <a href="https://cloud.google.com/deployment-manager/runtime-configurator/">GCP Runtime Configurator</a>. I chose <strong><em>.env</em> files</strong> to store configurations in here due to the simplicity of usage.</blockquote><h4>Using environment variables for configurations</h4><p>▸ Because of these configs should be loaded with Docker application start, we store them under docker/app/.env .</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/41bdc109cfe2239f9024fb43d24f40e7/href">https://medium.com/media/41bdc109cfe2239f9024fb43d24f40e7/href</a></iframe><p>▸ We can use <a href="https://docs.docker.com/compose/environment-variables/#the-env_file-configuration-option"><strong>env_file</strong> configuration option</a> on docker-compose.yml to set environment variables via an .env file on application start; (Line 5-6).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2d5e25961818bf166a16577877398d1c/href">https://medium.com/media/2d5e25961818bf166a16577877398d1c/href</a></iframe><h4>Populating data from environment variables</h4><blockquote><em>💭</em> Go standard library provides <a href="https://golang.org/pkg/os/#Getenv">os.Getenv()</a> function to read each environment variable separately. But there are Go libraries like <a href="https://github.com/spf13/viper">spf13/viper</a>, <a href="https://github.com/kelseyhightower/envconfig">kelseyhightower/envconfig</a>, <a href="https://github.com/caarlos0/env">caarlos0/env</a>, <a href="https://github.com/joeshaw/envdecode">joeshaw/envdecode</a> to get data on multiple environment variables as a set, by populating a struct from environment variables. I chose <a href="https://github.com/joeshaw/envdecode"><strong>joeshaw/envdecode</strong></a> to use in here, due to its simplicity.</blockquote><p>▸ We need to run go get github.com/joeshaw/envdecode to download and install the package. This will update go.mod and go.sum files as well.</p><p>▸ We can cache go modules by copying go.mod and go.sum files to Docker first and by running go mod download before copying all other files to Docker. So, let’s update docker/app/Dockerfile for this; (Line 6-8).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4503892416c79bc9f9c914c7e9419d5e/href">https://medium.com/media/4503892416c79bc9f9c914c7e9419d5e/href</a></iframe><p>▸ Let’s create a config package to get all configuration values once by adding Conf struct to map each configuration and AppConfig() function to get the populated struct. I save this code under config/config.go .</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7a0c44fc505d61216bb7842cef6fc711/href">https://medium.com/media/7a0c44fc505d61216bb7842cef6fc711/href</a></iframe><blockquote><em>💡 </em>In here, we have created Conf struct with embedded struct serverConf to get initial server configs. So, when we need to add new configurations for DB in the future, we can easily add another embedded struct for them to maintain simplicity and readability of the code.</blockquote><p>▸ Then, let’s update cmd/app/main.go to get configuration values via AppConfig() function; (Line 6,10,15 and 22–24).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/260e2e01795e3bf46cd7be52592e4d6b/href">https://medium.com/media/260e2e01795e3bf46cd7be52592e4d6b/href</a></iframe><p>▸ Rebuild and rerun the application. You should see the same Hello World! response on localhost:8080 .</p><h3>Adding Chi router</h3><blockquote><em>💭 </em>The <a href="https://golang.org/pkg/net/http/#ServeMux">default HTTP request multiplexer</a> in <a href="https://golang.org/pkg/net/http">net/http</a> is not very powerful. For example, if you visit localhost:8080/invalid-path it gives the same Hello World! response with 200 HTTP status instead giving 404 HTTP status. There are many powerful router libraries in Go like <a href="https://github.com/gorilla/mux">gorilla/mux</a>, <a href="https://github.com/go-chi/chi">go-chi/chi</a>, <a href="https://github.com/julienschmidt/httprouter">julienschmidt/httprouter</a>, <a href="https://github.com/buaazp/fasthttprouter">buaazp/fasthttprouter</a>. In here, we are using <a href="https://github.com/go-chi/chi"><strong>go-chi/chi</strong></a> due to its lesser weight and extensibility.</blockquote><p>▸ We need to run go get github.com/go-chi/chi to download and install the package. As you know, this updates go.mod and go.sum files as well.</p><p>⭐ Instead of using cmd/app to store all application logic, it’s a good practice to create a separate package to store the main application code and call it from cmd/app while creating the executable. So, I am creating the <strong>app</strong> package <strong>in the project root</strong> for this. However, you can name this as server or http, according to the purpose of the application.</p><p>▸ Let’s create a simple Handler which gives the Hello World! text response. I save this under app/app/indexHandler.go . It’s a simple function which matches <a href="https://golang.org/pkg/net/http/">net/http</a> handler signature func(ResponseWriter, *Request) to pass to <a href="https://golang.org/pkg/net/http/#ServeMux.HandleFunc">func (*ServeMux) HandleFunc</a> with a URL pattern.</p><blockquote><em>💡</em> In the next steps, we are going to build a struct which contains main dependencies like DB connection, under app/app to use them with handlers. If you don’t like the name app/app , I recommend you to name this as app/server or server/app .</blockquote><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/203c428a9b742fb46cc330b0b722f2c0/href">https://medium.com/media/203c428a9b742fb46cc330b0b722f2c0/href</a></iframe><p>▸ Then, let’s create a <a href="https://godoc.org/github.com/go-chi/chi#NewRouter">new Chi router</a> and bundle our handler to &quot;/&quot; route pattern via <a href="https://godoc.org/github.com/go-chi/chi#Mux.MethodFunc"><strong>MethodFunc()</strong></a> . I save this under app/router/router.go .</p><blockquote><em>💡</em> If you are not familiar with <a href="http://github.com/go-chi/chi">Chi router</a>, I recommend you to read <a href="https://github.com/go-chi/chi/blob/master/README.md">its README</a> for more details. If you are new to Go, again I recommend you to read the overview of the documentation of the <a href="https://golang.org/pkg/net/http/"><strong><em>net/http</em></strong></a><strong> </strong>package before that. As you see <a href="https://godoc.org/github.com/go-chi/chi#Mux.MethodFunc"><em>MethodFunc()</em></a> is matching <a href="https://golang.org/pkg/net/http/#HandleFunc"><strong>http.HandleFunc()</strong></a> signature.</blockquote><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/11bc646f83da22d1c6bcce105273a19f/href">https://medium.com/media/11bc646f83da22d1c6bcce105273a19f/href</a></iframe><p>▸ After that, we need to update cmd/app/main.go to use our Chi router instead using <a href="https://golang.org/pkg/net/http/#ServeMux">default HTTP route multiplexer</a>; (Line 6, 13 and 21).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9e70c4151eb6bd3e166925b2afa5ed0a/href">https://medium.com/media/9e70c4151eb6bd3e166925b2afa5ed0a/href</a></iframe><p>▸ Rebuild and rerun the application. You should see the same Hello World! response on localhost:8080. And this time, you should see 404 page not found response if you visit <em>localhost:8080/invalid-path.</em></p><h3>Adding zerolog logger</h3><blockquote><em>⭐ </em>While using microservices architectures, multiple services might be invoked to handle a single client request. The <a href="https://en.wikipedia.org/wiki/Syslog"><strong>Syslog</strong></a> is a <a href="https://en.wikipedia.org/wiki/Log_file">message logging protocol</a> which can be used to send all log events in different systems to a centralized log storage like <a href="https://www.graylog.org/">Graylog</a>, <a href="https://cloud.google.com/logging/">Stackdriver</a>, <a href="https://www.elastic.co/what-is/elk-stack">ELK Stack</a>, to provide visibility into the behavior of microservices. There are many powerful logging libraries which support <a href="https://en.wikipedia.org/wiki/Syslog"><strong><em>Syslog</em></strong></a> standards in Go like <a href="https://github.com/uber-go/zap">uber-go/zap</a>, <a href="https://github.com/apex/log">apex/log</a>, <a href="https://github.com/Sirupsen/logrus">sirupsen/logrus</a>, <a href="https://github.com/rs/zerolog">rs/zerolog</a>. In here, we are using <a href="https://github.com/rs/zerolog"><strong>rs/zerolog</strong></a> due to its speed and lesser allocations.</blockquote><h4>Adding Zerolog as the Syslog logger</h4><p>▸ We need to run go get github.com/rs/zerolog to download and install the package. As you know, this updates go.mod and go.sum files as well.</p><p>▸ Let’s create a global logger under util/logger/logger.go by wrapping <a href="https://godoc.org/github.com/rs/zerolog#Logger">zerolog.Logger</a>. We can find an example under <a href="https://github.com/rs/zerolog/blob/master/log/log.go">rs/zerolog/log</a> package.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/26de3384f40d1099a64ab900eaaa3a9b/href">https://medium.com/media/26de3384f40d1099a64ab900eaaa3a9b/href</a></iframe><blockquote><em>💡</em> Above code block shows how to convert the code in <a href="https://github.com/rs/zerolog/blob/master/log/log.go">rs/zerolog/log</a> to util/logger/logger.go. Due to we need to prevent using lengthy code blocks in the blog post, I have added only one method/ Output() in the above code. <a href="https://github.com/learning-cloud-native-go/myapp/tree/step-6/util/logger">The complete code</a> can be found on util/logger package with tests.</blockquote><p>▸ In the previous step, we used isDebug boolean parameter to choose the log level. We set the log level as Debug, only if that value is true. Otherwise, we set it as Info. Let’s add this to our configurations by adding DEBUG=true to docker/app/.env and by adding Debug bool `env:&quot;DEBUG,required&quot;` to config/config.go Conf struct. Check the <a href="https://github.com/learning-cloud-native-go/myapp/tree/step-6">step-6 branch</a> for the complete code.</p><p>▸ Let’s update cmd/app/main.go to use new <a href="https://github.com/learning-cloud-native-go/myapp/tree/step-6/util/logger"><em>util/logger</em></a><em> instead the default </em><a href="https://golang.org/pkg/log/"><em>log</em></a><em> package.</em></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b5b01aa1821ced265936d84b4a26ca05/href">https://medium.com/media/b5b01aa1821ced265936d84b4a26ca05/href</a></iframe><h4>Implementing a request logger</h4><blockquote><em>💭 </em>Besides the main application events, it’s helpful having logs of each request and response details. For that we can create a custom <a href="https://golang.org/pkg/net/http/#Handler">Handler</a> which maps <a href="https://golang.org/pkg/net/http/#HandlerFunc.ServeHTTP">ServeHTTP(ResponseWriter, *Request)</a> signature and an embedded util/logger to log request and response details.<br><em>🔎 </em>A good example can be found in <a href="https://github.com/google/go-cloud/blob/master/server/requestlog/requestlog.go"><em>google/go-cloud/server/requestlog</em></a>.</blockquote><p>▸ Let’s create the new custom <a href="https://golang.org/pkg/net/http/#Handler">Handler</a> under app/handler/handler.go. Later, we will use the NewHandler() function to convert normal handlers to this custom handlers. If you don’t like the naming <em>app/</em>handler use <em>app/requestlog.</em></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/956cc0d1176807b391d0566cfbdd5341/href">https://medium.com/media/956cc0d1176807b391d0566cfbdd5341/href</a></iframe><p>▸ To keep the code cleaner, the code related with log entry is moved to app/handler/logEntry.go.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fa14f36016ac19635ae19e3ebb3b9efb/href">https://medium.com/media/fa14f36016ac19635ae19e3ebb3b9efb/href</a></iframe><h4>Creating the main app package</h4><blockquote><em>💭 </em>In the previous steps, we just created a global <em>Syslog</em> logger and a custom <a href="https://golang.org/pkg/net/http/#Handler"><em>Handler</em></a> which logs each request and response details. We need to integrate both of them with our application handles like <em>app/app/indexHandler.go.</em></blockquote><p>▸ One way to set the logger as a dependency for our server application is<em>, creating a struct with embedded </em><a href="https://github.com/rs/zerolog"><em>rs/zerolog</em></a><em> logger, to represent our server application and then attach our </em>application handles to that struct. For that, let’s create the App struct <em>under </em>app/app/app.go. If you don’t like the naming <em>app/app/app.go</em> , I recommend you to name this as <em>app/server/server.go</em> with Server struct or <em>server/app/app.go with </em>App struct.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/65a056b5dac3f9c87ccb495c1bef1244/href">https://medium.com/media/65a056b5dac3f9c87ccb495c1bef1244/href</a></iframe><blockquote><em>⭐</em> However, this is not the most efficient way of packaging Go applications. But to make the project more accessible for different levels of programmers, especially for the newcomers to Go web API development, we assume all API always depends on the same set of dependencies.</blockquote><blockquote><em>💡</em>With this structure, we can easily load application dependencies inside handlers. For the moment it’s only about a <em>Syslog</em> logger. Same way, we can add the DB connections, Redis connections, messaging systems like <a href="https://nats.io/">NATS</a> and etc.</blockquote><p>▸ Then, let’s convert the HandleIndex() function in app/app/indexHandler.go to a method of above App struct.<br>func (app *App) HandleIndex(w http.ResponseWriter, _ *http.Request) {</p><p>▸ Now, let’s update app/router/router.go to use NewHandler() function in app/handler to convert the normal handlers into the custom handlers which logs request and response details.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bde5b455aa73f6f2f1769f7643793f75/href">https://medium.com/media/bde5b455aa73f6f2f1769f7643793f75/href</a></iframe><p>▸ Due to we are passing *App to the New() function in app/router , we have to update cmd/app/main.go.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/173fe26790af17b8fafbf841e3927738/href">https://medium.com/media/173fe26790af17b8fafbf841e3927738/href</a></iframe><p>▸ Rebuild and rerun the application. You should see the same Hello World! response on localhost:8080, as well as logs like this.</p><pre>{&quot;level&quot;:&quot;info&quot;,&quot;received_time&quot;:&quot;2019-08-05T13:37:29Z&quot;,&quot;method&quot;:&quot;GET&quot;,&quot;url&quot;:&quot;/&quot;,&quot;header_size&quot;:322,&quot;body_size&quot;:0,&quot;agent&quot;:&quot;Mozilla/5.0 (Macintosh; Intel Mac OS X 10.14; rv:71.0) Gecko/20100101 Firefox/71.0&quot;,&quot;referer&quot;:&quot;&quot;,&quot;proto&quot;:&quot;HTTP/1.1&quot;,&quot;remote_ip&quot;:&quot;172.18.0.1&quot;,&quot;server_ip&quot;:&quot;172.18.0.2&quot;,&quot;status&quot;:200,&quot;resp_header_size&quot;:96,&quot;resp_body_size&quot;:12,&quot;latency&quot;:0.068137,&quot;time&quot;:&quot;2019-09-02T13:37:29Z&quot;}</pre><h3>Adding DB docker file</h3><p>▸ As I informed earlier, we use the docker folder in the project root to store all Docker related files. So, Let’s save this under docker/mariadb/Dockerfile.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/519c792f669b8c8fda57a9fb90627590/href">https://medium.com/media/519c792f669b8c8fda57a9fb90627590/href</a></iframe><blockquote><em>💡 </em>In here, I am just using a mariadb alpine image with bash. <em>If you don’t like to add an extra weight to your images by installing </em><em>bash, just use builtin </em><em>sh or </em><em>ash shells and directly add </em>image: &quot;yobasystems/alpine-mariadb:latest&quot; to docker-compose.yml without using build: in the next step.</blockquote><p>▸ Then, let’s update docker-compose.yml;(From line 9)</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6ac615325f2a40ec4c1a30179115045f/href">https://medium.com/media/6ac615325f2a40ec4c1a30179115045f/href</a></iframe><p>▸ Rebuild and rerun the application. Now you should see two containers are running while you run <a href="https://docs.docker.com/compose/reference/ps/">docker-compose ps</a> (or <a href="https://docs.docker.com/engine/reference/commandline/ps/">docker ps</a>)</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f34443be64f485903b7fc7d0dfadc074/href">https://medium.com/media/f34443be64f485903b7fc7d0dfadc074/href</a></iframe><blockquote><em>💡 </em>Also you can use any <em>mariadb</em> client to connect to the (empty) database.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9wSIbiYe3WiQktibtzVBOA.png" /></figure><h3>Adding initial database migrations</h3><blockquote><em>💭</em> Database migrations are like version controls for the database. There are few popular options for database migration in the Go ecosystem like <a href="https://github.com/golang-migrate/migrate">golang-migrate/migrate</a>, <a href="https://github.com/pressly/goose">pressly/goose</a>, <a href="http://gorm.io/docs/migration.html">GORM migrations</a> and etc. In here, we are using <a href="https://github.com/pressly/goose"><strong>pressly/goose</strong></a>, due to its lesser resource usage and the simplicity of usage.</blockquote><h4>Implementing a DB adapter</h4><p>▸ In the previous section, inside the docker-compose.yml file, we adjusted the configurations of the MariaDB instance by setting environment variables to overwrite the default database name, username and passwords. From the Go application side, we need those configurations to connect with the database. So, let’s add those to docker/app/.env.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4568335da34d086d5deec96296ab3027/href">https://medium.com/media/4568335da34d086d5deec96296ab3027/href</a></iframe><p>▸ To read those from the Go application side, we need to add those to Conf struct in config/config.go file.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5b080bf3dc6fac876e6ca27587dc58b7/href">https://medium.com/media/5b080bf3dc6fac876e6ca27587dc58b7/href</a></iframe><p>▸ Go standard library provides a generic interface around SQL databases via the <a href="https://golang.org/pkg/database/sql/">database/sql</a> package. But we have to use a specific <a href="https://github.com/golang/go/wiki/SQLDrivers">database driver implementation</a> according to the the database driver we use. In here we use go-<a href="https://github.com/go-sql-driver/mysql">sql-driver/mysql</a> as the MariaDB driver. So we need to run go get github.com/go-sql-driver/mysql to download and install the package. As you know, this updates go.mod and go.sum files as well.</p><p>▸ Let’s create the database adapter in adapter/db/db.go.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4122ae41f525578fb1a1119760a066ac/href">https://medium.com/media/4122ae41f525578fb1a1119760a066ac/href</a></iframe><h4>Implementing a DB migration tool using Goose</h4><p>▸ We need to run go get github.com/pressly/goose to download and install the package.</p><p>▸ Let’s create a custom <a href="https://github.com/pressly/goose">pressly/goose</a> binary. A good example can be found in <a href="https://github.com/pressly/goose/blob/master/cmd/goose/main.go">https://github.com/pressly/goose/blob/master/cmd/goose/main.go</a>. We save this under cmd/migrate/main.go with few modifications to remove few unnecessary codes, due to we are using only MariaDB in our application.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/35115466487385d18b204aa2c1de918b/href">https://medium.com/media/35115466487385d18b204aa2c1de918b/href</a></iframe><blockquote><em>💡</em> If you are not familiar with <a href="https://github.com/pressly/goose"><em>pressly/goose</em></a>, now it’s the time to read <a href="https://github.com/pressly/goose/blob/master/README.md">its README</a> for more details. Also in here, we are going to use only <em>.sql</em> migrations. So, I set the migrations directory to /myapp/migrations.</blockquote><p>▸ Due to we need to build this package and copy the binary file to the smaller alpine image with .sql migration files, we have to update docker/app/Dockerfile; (Line 1,2,11,12).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a34daecbbad990e9da2c66f9c3fbc091/href">https://medium.com/media/a34daecbbad990e9da2c66f9c3fbc091/href</a></iframe><p>▸ Rebuild and rerun the application. Login to myapp_app_1 container by running docker exec -it myapp_app_1 bash and run /myapp/migrate status. You should see no migrations available.</p><pre>Applied At                  Migration<br>=====================================</pre><h4>Adding initial SQL migrations</h4><p>▸ As mentioned in the very beginning of this post, we are building a RESTful CRUD API for a bookshelf. So, let’s create our first sql migration file to create books table under migrations/20190805170000_create_books_table.sql.</p><blockquote><em>💡 </em>We can use create command of our goose binary; ex: /myapp/migrate create create_books_table sql.</blockquote><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3723a3d91090b6dfa71c7020bb7001f0/href">https://medium.com/media/3723a3d91090b6dfa71c7020bb7001f0/href</a></iframe><p>▸ Rebuild and rerun the application. Login to myapp_app_1 container by running docker exec -it myapp_app_1 bash and run /myapp/migrate status. Now, you should see one pending migration is available.</p><pre>Applied At        Migration<br>==========================================================<br>Pending           -- 20190805170000_create_books_table.sql</pre><blockquote><em>💡 </em>We can run migrations manually with /myapp/migrate up command. But, let’s see how to automate running migrations in the development environment.</blockquote><h4>Running migrations at the application startup</h4><blockquote><em>🔎</em> This step is quite tricky, due to we need to wait till myapp_bd_1 container starts, to run database migrations. Otherwise, myapp_app_1 will be stopped with an error, if migrations run before creating the database.</blockquote><p>💡<em> </em>In here, I am going to install <em>mysql-client</em> package to the myapp_app docker image and wait till database is running, by checking the database connection via a <a href="https://dev.mysql.com/doc/refman/8.0/en/mysql.html">MySQL command-line client</a> call.</p><p>▸ Let’s save the script which checks the database connection, under docker/app/bin/wait-for-mysql.sh.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b9cd94e1f29841437c5d0ccbc329eb5a/href">https://medium.com/media/b9cd94e1f29841437c5d0ccbc329eb5a/href</a></iframe><p>▸ We need to update the docker/app/Dockerfile file, to install mysql-client, copy above script to the deployment environment and make them executable; (Line 4, 10,11).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8b8df9fa4540b21e031fc515b79961d9/href">https://medium.com/media/8b8df9fa4540b21e031fc515b79961d9/href</a></iframe><p>▸ To run migrations at the applications startup and delete mysql-client after running migrations, let’s use this under docker/app/bin/init.sh.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/456cc19c8c6f05b5308d3d87e6e97739/href">https://medium.com/media/456cc19c8c6f05b5308d3d87e6e97739/href</a></iframe><blockquote><em>💡</em> Due to we already copy files in docker/app/bin to deployment environment, no need to update docker/app/Dockerfile.</blockquote><p>▸ Let’s use above scripts inside docker-compose.yml to safely run migrations after database starts.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ddf0ef082c21598d8e20d6104134b06d/href">https://medium.com/media/ddf0ef082c21598d8e20d6104134b06d/href</a></iframe><p>▸ Rebuild and rerun the application. You can see that database migrations are running while starting the application by reviewing the logs.</p><h3>Adding GORM</h3><blockquote><em>💭</em> <a href="http://gorm.io/">GORM</a> is a full featured <a href="https://en.wikipedia.org/wiki/Object-relational_mapping"><strong>ORM</strong></a> for Golang. It supports database associations, preloading associated models, database transactions and many more. If you are not familiar with GORM, I highly recommend you to check <a href="http://gorm.io/docs/">its documentation</a> before starting this section.</blockquote><h4>Implementing a GORM adapter</h4><p>▸ We need to run go get github.com/jinzhu/gorm to download and install the package. As you know, this updates go.mod and go.sum files as well.</p><p>▸ Even though <a href="http://gorm.io/docs/connecting_to_the_database.html">GORM uses </a><a href="http://gorm.io/docs/connecting_to_the_database.html">go-sql-driver/mysql</a> to connect with MySQL/ MariaDB databases, still it does not allow us to use existing *sql.DB connections. Instead, we need to use *gorm.DB. So, we need to create a new adapter for GORM under adapter/gorm/gorm.go.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cc98d17938431281e6b27d0a389945ba/href">https://medium.com/media/cc98d17938431281e6b27d0a389945ba/href</a></iframe><h4>Adding GORM adapter to the main app</h4><p>▸ Let’s update the App struct to set the GORM connection as a dependency for our server application, by updating the app/app/app.go (Line 9,14,18).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6d71fe89cbc9f4ebe20d78b06d203345/href">https://medium.com/media/6d71fe89cbc9f4ebe20d78b06d203345/href</a></iframe><p>▸ Then we need to update cmd/app/main.go to get the GORM connection at the startup of the application.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d3bdf58b48179f51b40a3c5d62baefd8/href">https://medium.com/media/d3bdf58b48179f51b40a3c5d62baefd8/href</a></iframe><p>💡<em> </em>In here, we enable database logs according to the boolean value in Debug configurations.</p><h4>Checking application health</h4><p>▸ Adding handlers for <a href="https://kubernetes.io/docs/tasks/configure-pod-container/configure-liveness-readiness-probes/">liveness and readiness probes</a> is a common practice in modern Go applications especially while using <a href="https://kubernetes.io/">Kubernetes</a> for deployments. With that, we can check the health of GORM connection as well. So, let’s add those under app/app/heathHandler.go.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/48ebe47f798ae514dbcac0ddbfc0e006/href">https://medium.com/media/48ebe47f798ae514dbcac0ddbfc0e006/href</a></iframe><p>▸ Then, we need to update app/router/router.go to attach those handlers to the router.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b48568920397bdf60137633ed412bb06/href">https://medium.com/media/b48568920397bdf60137633ed412bb06/href</a></iframe><p>▸ Rebuild and rerun the application. You should get 200 HTTP status while visit localhost:8080/healthz/readiness in the browser if the GORM connection is healthy.</p><h3>Adding initial books API routes</h3><h4>Implementing initial books API Handlers</h4><p>▸ As mentioned earlier, in here we are building a <strong>RESTful </strong><a href="https://en.wikipedia.org/wiki/Create,_read,_update_and_delete"><strong>CRUD</strong></a><strong> API for a bookshelf</strong>. So, let’s create initial handler functions for the <em>books</em> API under app/app/bookHandler.go.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1d1d4bc986e3bcedebfee5d9b39b1fc9/href">https://medium.com/media/1d1d4bc986e3bcedebfee5d9b39b1fc9/href</a></iframe><p>▸ We need to update app/router/router.go to add the handlers to the router.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a81b4c2f21ed9831b36891360109b6cf/href">https://medium.com/media/a81b4c2f21ed9831b36891360109b6cf/href</a></iframe><p>▸ Rebuild and rerun the application. And then, test /books API by using a REST client application like <a href="https://insomnia.rest/">Insomnia REST Client</a> or <a href="https://www.getpostman.com/downloads/">Postman</a>. You should see request logs like these on each request.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d170063734c442b33a9be911d0b7e2bd/href">https://medium.com/media/d170063734c442b33a9be911d0b7e2bd/href</a></iframe><h4>Implementing Content-Type JSON middleware</h4><p>▸ Instead of setting HTTP header &quot;Content-Type&quot;: &quot;application/json&quot; on each handler code, we can create a <a href="https://github.com/go-chi/chi#middleware-handlers">router middleware</a> for this under app/router/middleware/content_type_json.go.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d5aba1e4fd13b38122eb11407b5bebe5/href">https://medium.com/media/d5aba1e4fd13b38122eb11407b5bebe5/href</a></iframe><p>▸ Also, we can add tests under app/router/middleware/content_type_json_test.go to test the middleware.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9d9d8e7384bf98dcb577542a4e25ec0f/href">https://medium.com/media/9d9d8e7384bf98dcb577542a4e25ec0f/href</a></iframe><p>▸ Then, update app/router/router.go to attach above middleware to API routes. In here, we prefix all API routes with /api/v1 as well.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2e979631126658e695d434cf94dfa1c5/href">https://medium.com/media/2e979631126658e695d434cf94dfa1c5/href</a></iframe><p>▸ Rebuild and rerun the application. And now, you should see &quot;Content-Type&quot;: &quot;application/json&quot; headers in API responses.</p><h3>Implementing RESTful handlers</h3><p>Let’s complete the functionality of each handler functions.</p><blockquote><em>💭</em> To make examples simpler and easier to understand for different levels of programmers, in here I am using models and <a href="https://docs.microsoft.com/en-us/dotnet/architecture/microservices/microservice-ddd-cqrs-patterns/infrastructure-persistence-layer-design#the-repository-pattern">repositories</a>. This may not be the most idiomatic way of structuring Go applications but, this is one of hassle-free structure, even an absolute newcomer can understand.</blockquote><h4>Completing list books functionality</h4><p>▸ We use model/book.go to save models related to books. Book struct is used <strong>to map database records</strong> and BookDto struct is used <strong>to control how to show the model to outside</strong>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e72fe294130ca7d7d80fcf45f7c2d8f8/href">https://medium.com/media/e72fe294130ca7d7d80fcf45f7c2d8f8/href</a></iframe><p>▸ <a href="http://gorm.io/">GORM</a> provides multiple ways to <a href="http://gorm.io/docs/query.html">query data from the database</a>. To get the all records from a batabase table, we can use its Find() method. So, let’s create the ListBooks() method in repository/book.go to get all books records.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/58d2e47601a967c623e2e45ad14c6967/href">https://medium.com/media/58d2e47601a967c623e2e45ad14c6967/href</a></iframe><p>▸ Now, let’s complete the HandleListBooks() method in app/app/bookHandler.go. If an error occurs inside the handler, we <strong>log the actual error and use a static message to create the error response</strong>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2519c79da1f789a14a1eec703f9014c1/href">https://medium.com/media/2519c79da1f789a14a1eec703f9014c1/href</a></iframe><p>▸ We save those static error messages inside app/app/app.go</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bf2a077ff5a69bff7c0444ce272050a1/href">https://medium.com/media/bf2a077ff5a69bff7c0444ce272050a1/href</a></iframe><h4>Completing read book functionality</h4><p>▸ To get a single record from the database, we can use GORM’s First() method. Let’s add ReadBook() method in repository/book.go to query a single book record.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f73287098c9d885985061d15ca822ee4/href">https://medium.com/media/f73287098c9d885985061d15ca822ee4/href</a></iframe><blockquote><em>💡 </em>Because of we use the primary key to get data, we can use db.First(&amp;book, id) directly, without using its Where() method.</blockquote><p>▸ This is how we can complete HandleReadBook() method in app/app/bookHandler.go.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b525a8c13fc16a174b794b55a8cc6674/href">https://medium.com/media/b525a8c13fc16a174b794b55a8cc6674/href</a></iframe><h4>Completing delete book functionality</h4><p>▸ To delete a database record, we can use <a href="http://gorm.io/docs/delete.html">GORM’s </a><a href="http://gorm.io/docs/delete.html">Delete()</a> method. So, let’s add DeleteBook() method in repository/book.go to delete a single book record.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7788dbc9029752c000b002c3bb94993f/href">https://medium.com/media/7788dbc9029752c000b002c3bb94993f/href</a></iframe><p>▸ Then, let’s complete the HandleDeleteBook() method in app/app/bookHandler.go.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8cabf4e557143733e817179ad740fea2/href">https://medium.com/media/8cabf4e557143733e817179ad740fea2/href</a></iframe><h4>Completing create book functionality</h4><p>▸ To create a new database record, we can use <a href="http://gorm.io/docs/create.html">GORM’s </a><a href="http://gorm.io/docs/create.html">Create()</a> method. So, let’s add CreateBook() method in repository/book.go to create a new book record.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/81f85a037c26c8d0deadeedf7807022b/href">https://medium.com/media/81f85a037c26c8d0deadeedf7807022b/href</a></iframe><p>▸ Let’s update model/book.go. Input structures may not match with the models or <a href="https://en.wikipedia.org/wiki/Data_transfer_object">dtos</a>. So in here, I am using a different structure for the form. But, if both input and output/ model structures are same, we can reuse same structures without creating new structures for forms.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/79f58694a53e48c809bf99b0106d79f2/href">https://medium.com/media/79f58694a53e48c809bf99b0106d79f2/href</a></iframe><p>▸ Then, let’s complete the HandleCreateBook() method in app/app/bookHandler.go.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4816de0690a6536707fad2c73fd3686a/href">https://medium.com/media/4816de0690a6536707fad2c73fd3686a/href</a></iframe><blockquote><em>💭</em> We will add form validations in the next section.</blockquote><p>▸ We save those static error messages inside app/app/app.go.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6960205ba0ff6522b1e0d80519eb5637/href">https://medium.com/media/6960205ba0ff6522b1e0d80519eb5637/href</a></iframe><h4>Completing update book functionality</h4><p>▸ To update the database records, we can use <a href="http://gorm.io/docs/update.html#Update-Changed-Fields">GORM’s </a><a href="http://gorm.io/docs/update.html#Update-Changed-Fields">Update()</a> method. So, let’s add UpdateBook() method in repository/book.go to update a book record.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/35317127c9c083d224f9b5436a6b4606/href">https://medium.com/media/35317127c9c083d224f9b5436a6b4606/href</a></iframe><p>▸ Then, let’s complete the HandleUpdateBook() method in app/app/bookHandler.go.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a22c907f60c9a24b6c3eabd6005060a6/href">https://medium.com/media/a22c907f60c9a24b6c3eabd6005060a6/href</a></iframe><blockquote><em>💭</em> We will add form validations in the next section.</blockquote><p>▸ We save those static error messages in app/app/app.go.</p><pre>const <em>appErrDataUpdateFailure </em>= “data update failure”</pre><p>▸ Rebuild and rerun the application. Now, the functionalities of book handlers should be worked, expect form validations which we are going to add in the next section.</p><h3>Adding Validator.v9</h3><blockquote><em>💭</em> Form validation is an important step while inserting and updating data. In the Go ecosystem we can see few validation packages like <a href="https://gopkg.in/go-playground/validator.v9">go-playground/validator.v9</a> , <a href="https://github.com/go-ozzo/ozzo-validation">go-ozzo/ozzo-validation</a>. In here, we are using <a href="https://gopkg.in/go-playground/validator.v9">playground/validator.v9</a> due to its simplicity of usage.</blockquote><h4>Adding initial validator</h4><p>▸ We need to run go get gopkg.in/go-playground/validator.v9 to download and install the package. As you know, this updates go.mod and go.sum files as well.</p><p>▸ Let’s create util/validator/validator.go to get the *validator.Validate with a custom configuration. By default, it uses validate struct field tags to read meta data. But, in here, we replace it with form struct field tags.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9d26235dc14563821d9ba07988d44e8b/href">https://medium.com/media/9d26235dc14563821d9ba07988d44e8b/href</a></iframe><p>▸ To use this *validator.Validate as the global validator, let’s add this to App struct in app/app/app.go.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0af57a9dd93c457ec29ff717c9be84eb/href">https://medium.com/media/0af57a9dd93c457ec29ff717c9be84eb/href</a></iframe><p>▸ Then, we need to update cmd/app/main.go to get this *validator.Validate at the startup of the application.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a65f809a723fc0e09be25a3b3f46c314/href">https://medium.com/media/a65f809a723fc0e09be25a3b3f46c314/href</a></iframe><p>▸ Let’s add validation rules to the BookForm struct in the model/book.go.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/341c4cd22693034e827ab27a8dc5322e/href">https://medium.com/media/341c4cd22693034e827ab27a8dc5322e/href</a></iframe><blockquote><em>💡 </em>You can see all list of validation rule types, supported by <a href="https://gopkg.in/go-playground/validator.v9">playground/validator.v9</a> in <a href="https://github.com/go-playground/validator/blob/v9/baked_in.go#L64">https://github.com/go-playground/validator/blob/v9/baked_in.go#L64</a>.</blockquote><p>▸ Then, let’s add validations to the HandleCreateBook() and HandleUpdateBook() methods in the app/app/bookHandler.go.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4db2dfbcc77619a777203debcada692e/href">https://medium.com/media/4db2dfbcc77619a777203debcada692e/href</a></iframe><p>▸ Rebuild and rerun the application. You should see error messages like following messages, while inserting invalid data.</p><pre>{<br>  &quot;error&quot;: &quot;Key: &#39;BookForm.Title&#39; Error:Field validation for &#39;Title&#39; failed on the &#39;required&#39; tag&quot;<br>}</pre><blockquote><em>💭</em> As you can see, those are not having valid <a href="https://en.wikipedia.org/wiki/JSON">JSON</a> formats. And also messages are not suitable to show to the end user. So, we will add custom messages for these in the next section.</blockquote><h4>Implementing custom validation messages</h4><p>We <strong>need to fix two things</strong> in the default error messages of <a href="https://gopkg.in/go-playground/validator.v9">playground/validator.v9</a>.</p><p>01. It shows struct field names, instead of names in json tags; (“Field validation for ‘Title’ failed” instead “Field validation for ‘title’ failed”).</p><blockquote><em>🔎</em> We can see the solution in <a href="https://github.com/go-playground/validator/blob/173026262523a492668bd6d78b8934c2ad69843f/validator_instance.go#L122">https://github.com/go-playground/validator/blob/173026262523a492668bd6d78b8934c2ad69843f/validator_instance.go#L122</a> .</blockquote><p>02. The error response is not having a valid <a href="https://en.wikipedia.org/wiki/JSON">JSON</a> format and error messages are not suitable to show to the end users.</p><blockquote><em>🔎 </em>The solution <a href="https://gopkg.in/go-playground/validator.v9">playground/validator.v9</a> developers suggest is to use its <a href="https://github.com/go-playground/validator/tree/v9/translations">go-playground/validator/translations</a> package. But due to we don’t need to support multiple translations in our API application, we will write ToErrResponse() function in util/validator/validator.go to convert the default error messages to a valid <a href="https://en.wikipedia.org/wiki/JSON">JSON</a> format with end user friendly error messages. However better check their implementation in <a href="https://github.com/go-playground/validator/blob/v9/translations/en/en.go">https://github.com/go-playground/validator/blob/v9/translations/en/en.go</a>.</blockquote><p>▸ Let’s update util/validator/validator.go to fix both above issues.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/86eb791f09758cba2efaff202f50e145/href">https://medium.com/media/86eb791f09758cba2efaff202f50e145/href</a></iframe><p>▸ Then let’s update app/app/bookHandler.go.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/05b1aeaf5d47fcf467f08eefbc64a9fa/href">https://medium.com/media/05b1aeaf5d47fcf467f08eefbc64a9fa/href</a></iframe><blockquote><em>⭐ As you can see, we duplicate 20 lines of code in each handler and it is not a good practice. 👨‍🏫 Assume this as </em><strong><em>the homework</em></strong><em> and find how we can remove these duplicates. 🔎</em> <em>One way is, moving these codes to a private method in </em>app/app/common.go.</blockquote><p>▸ We save those static error messages in app/app/app.go.</p><pre>const appErrFormErrResponseFailure = &quot;form error response failure&quot;</pre><p>▸ Rebuild and rerun the application. Now, you should see error messages like these.</p><pre>{<br>  &quot;errors&quot;: [<br>    &quot;title is a required field&quot;,<br>    &quot;author must be a maximum of 255 in length&quot;,<br>    &quot;image_url must be a valid URL&quot;<br>  ]<br>}</pre><h4>Implementing custom validation types</h4><p>▸ One last thing! We don’t fully validate the author’s name and the published date of the BookForm struct. For the moment <a href="https://gopkg.in/go-playground/validator.v9">playground/validator.v9</a> is not supporting “<em>alphabetic characters with space” </em>and <em>“date” </em>validations. So, let’s create a custom validation types for these in util/validator/validator.go.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/38b0f4038a6d64b803e9d63f5d02ebdc/href">https://medium.com/media/38b0f4038a6d64b803e9d63f5d02ebdc/href</a></iframe><p>▸ Then, we need to update BookForm struct in model/book.go.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d98f470aea54f7347383f33ccada3b37/href">https://medium.com/media/d98f470aea54f7347383f33ccada3b37/href</a></iframe><p>▸ Rebuild and rerun the application. Now, you should get validation errors even for author and image_url.</p><pre>{<br>  &quot;errors&quot;: [<br>    &quot;title is a required field&quot;,<br>    &quot;author can only contain alphabetic and space characters&quot;,<br>    &quot;published_date must be a valid date&quot;,<br>    &quot;image_url must be a valid URL&quot;<br>  ]<br>}</pre><p>Okay, Let’s stop our first post of <a href="https://medium.com/learning-cloud-native-go">Learning Cloud Native Go</a> series in here. In this post, we discussed,</p><p>▸ Creating a new Go project ▸ Adding initial HTTP server ▸ Adding initial Docker files ▸ Adding initial configurations ▸ Adding Chi router ▸ Adding Zerolog Syslog logger ▸ Adding DB docker file ▸ Adding initial database migrations ▸ Adding GORM ▸ Adding initial books API routes ▸ Implementing RESTful handlers ▸ Adding Validator.v9</p><p>As mentioned at the beginning of this post, the completed project can be found in <a href="https://github.com/learning-cloud-native-go/myapp"><strong>learning-cloud-native-go/myapp</strong></a> GitHub repository and you can check the code on each step by using step- branches in that repository.</p><p>Last but not least,<br>I’ll upload the same content to <a href="https://learning-cloud-native-go.github.io/"><strong>learning-cloud-native-go.github.io</strong></a> 👈 which uses <a href="https://v2.docusaurus.io/">Docusaurus</a> in the upcoming days. Hope it will be more structured and easy to see the big picture.</p><p><a href="https://learning-cloud-native-go.github.io/">Hello from Learning Cloud Native Go</a></p><p>Also, I am not a native English speaker. So, if you found any mistake or something I need to be changed, even a spelling or a grammar mistake, please let me know. Thanks for reading, hope it helped for you.</p><blockquote>⭐ <a href="https://github.com/learning-cloud-native-go/website">Contribute!</a> 🥤 <a href="https://www.buymeacoffee.com/dumindu">Buy me a coffee!</a> 🚀 <a href="https://github.com/dumindu/hire-me/">Hire me!</a></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dc4634ef03b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/learning-cloud-native-go/lets-get-it-started-dc4634ef03b">Let’s Get It Started!</a> was originally published in <a href="https://medium.com/learning-cloud-native-go">Learning Cloud Native Go</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>