<?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[Code Uncomplicated - Medium]]></title>
        <description><![CDATA[A series on posts on simple solutions to complex code problems I’m working on. - Medium]]></description>
        <link>https://medium.com/code-uncomplicated?source=rss----4fd5faa62b56---4</link>
        <image>
            <url>https://cdn-images-1.medium.com/proxy/1*TGH72Nnw24QL3iV9IOm4VA.png</url>
            <title>Code Uncomplicated - Medium</title>
            <link>https://medium.com/code-uncomplicated?source=rss----4fd5faa62b56---4</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 14:07:14 GMT</lastBuildDate>
        <atom:link href="https://medium.com/feed/code-uncomplicated" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Moving Docker’s storage location]]></title>
            <link>https://medium.com/code-uncomplicated/moving-dockers-storage-location-6804c3f8b0ea?source=rss----4fd5faa62b56---4</link>
            <guid isPermaLink="false">https://medium.com/p/6804c3f8b0ea</guid>
            <category><![CDATA[cloud-computing]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[linux]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[docker]]></category>
            <dc:creator><![CDATA[Oliver Mascarenhas]]></dc:creator>
            <pubDate>Fri, 06 Oct 2023 16:04:39 GMT</pubDate>
            <atom:updated>2023-10-06T16:04:39.898Z</atom:updated>
            <content:encoded><![CDATA[<p>The right way to move Docker’s default storage location on Linux</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/610/1*x9U4qFx3vGgqtRc5W-3h4w.jpeg" /><figcaption>Move your docker storage, what could go wrong!</figcaption></figure><p>Docker has revolutionized the way we deploy and manage applications. However, as your Docker usage grows, you might find the need to move Docker’s default storage location. This could be due to various reasons such as running out of disk space, optimizing storage performance, or adhering to specific organizational requirements. In this post, we’ll explore the process of moving Docker’s default storage location and delve into the use cases where this move is most appropriate.</p><h3><strong>Docker’s Default Storage Location</strong></h3><p>By default, Docker stores its images, containers, and volumes in the /var/lib/docker directory on Linux systems. However, this location might not always be suitable, especially in scenarios where you have limited disk space on the system drive or need to distribute the storage across different partitions or drives.</p><h3><strong>Use Cases for Moving the Default Storage Location</strong></h3><p><strong>Disk Space Optimization:</strong> When your server is running low on disk space, moving Docker’s storage location to a drive with more available space is crucial. This prevents your system from becoming unresponsive due to insufficient disk space.</p><p><strong>Performance Enhancement:</strong> SSDs (Solid State Drives) are significantly faster than traditional HDDs (Hard Disk Drives). By moving Docker’s storage to an SSD, you can enhance the read/write speeds, leading to faster container operations and improved application performance.</p><p><strong>Data Separation:</strong> In scenarios where you need to keep sensitive data separate from the operating system, moving Docker’s storage to an encrypted external drive or a specific partition ensures data security. This is particularly important for applications dealing with sensitive customer information or compliance data.</p><p><strong>Backup and Disaster Recovery:</strong> When Docker’s storage location is on a separate drive, it becomes easier to manage backups and implement disaster recovery strategies. You can focus your backup efforts on the specific drive housing Docker’s data, ensuring quick recovery in case of system failures.</p><h3>Steps</h3><ol><li>Stop docker from running</li></ol><pre>&gt; sudo systemctl stop docker.service<br><br>&gt; sudo systemctl stop docker.socket</pre><p>2. Edit the systemd file located at /lib/systemd/system/docker.service with your preffered editor, we’ll use vi here.</p><pre>&gt; sudo vi /lib/systemd/system/docker.service</pre><p>3. Search for the line below.</p><pre>ExecStart=/usr/bin/dockerd -H fd:// --containerd=/run/containerd/containerd.sock</pre><p>Add the --data-root flag to point to the new directory. In the example below, we’ve mounted an SSD drive.</p><pre>ExecStart=/usr/bin/dockerd --data-root /mnt/ssddata/dockerdata -H fd:// --containerd=/run/containerd/containerd.sock</pre><p>4. Next we’ll create the directory we intend to use in case it dosen’t already exist and use the rsync command to copy the contents of /var/lib/docker to the new location.</p><pre>&gt; sudo mkdir -p /mnt/ssddata/dockerdata<br><br>&gt; sudo rsync -aqxP /var/lib/docker/ /mnt/ssddata/dockerdata</pre><p>5. Finally we’ll reload the systemd configuration and restart the Docker service.</p><pre>&gt; sudo systemctl daemon-reload<br><br>&gt; sudo systemctl start docker</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6804c3f8b0ea" width="1" height="1" alt=""><hr><p><a href="https://medium.com/code-uncomplicated/moving-dockers-storage-location-6804c3f8b0ea">Moving Docker’s storage location</a> was originally published in <a href="https://medium.com/code-uncomplicated">Code Uncomplicated</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Youtube Data API v3 — fetch view counts, thumbnails and more]]></title>
            <link>https://medium.com/code-uncomplicated/youtube-data-api-v3-fetch-view-counts-thumbnails-and-more-73df8b44b5a0?source=rss----4fd5faa62b56---4</link>
            <guid isPermaLink="false">https://medium.com/p/73df8b44b5a0</guid>
            <category><![CDATA[youtube]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[api]]></category>
            <dc:creator><![CDATA[Oliver Mascarenhas]]></dc:creator>
            <pubDate>Fri, 05 May 2023 10:49:49 GMT</pubDate>
            <atom:updated>2023-05-05T10:49:49.188Z</atom:updated>
            <content:encoded><![CDATA[<h3>Youtube Data API v3 — fetch view counts, thumbnails and more</h3><p>How to fetch view counts, thumbnails and likes using Youtube Data API v3 Golang client</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XMehNEXymkNChVMNj7GQYw.png" /><figcaption>Youtube Data API v3</figcaption></figure><p>YouTube is the largest video sharing platform on the internet, with over two billion monthly active users. It’s not only a place where people watch and share videos but also a massive source of data that can be used to understand user behavior, preferences, and trends. To access and analyze this data, developers can use the YouTube Data API v3. In this article, we will explore what the YouTube Data API v3 is, its features, and how it can be used.</p><h3><strong>What is YouTube Data API v3?</strong></h3><p>The YouTube Data API v3 is an API (Application Programming Interface) that enables developers to retrieve data from YouTube’s database. It provides access to a wide range of information, such as video details, channel information, user activities, and comments. This API is designed to help developers create applications that integrate with YouTube and provide better services to users.</p><h3>Features of YouTube Data API v3</h3><p>The YouTube Data API v3 offers a wide range of features that make it a powerful tool for developers. Some of the features are:</p><ol><li>Video details — access video details such as title, description, duration, and video ID using the API.</li><li>Channel information — retrieve channel details, such as channel ID, title, and description.</li><li>User activities — track user activities, such as likes, dislikes, subscriptions, and comments.</li><li>Comments — retrieve comments on videos and replies to comments.</li><li>Search — search for videos and channels based on various criteria, such as keywords, category, and location.</li><li>Analytics — retrieve analytics data, such as views, likes, dislikes, and engagement metrics.</li></ol><h3>How to use YouTube Data API v3?</h3><p>To use the YouTube Data API v3, you need to follow the following steps:</p><p>Step 1: Create a Google account and enable the YouTube Data API v3.</p><p>Step 2: Create a project in the Google Cloud Console and generate an API key.</p><p>Step 3: Configure the API key to restrict it to the appropriate APIs and IP addresses.</p><p>Step 4: Install the Google API client library for your preferred programming language.</p><p>Step 5: Make API requests using the client library.</p><h3>YouTube Data API v3 in action using Golang</h3><pre>package main<br><br>import (<br>    &quot;fmt&quot;<br>    &quot;google.golang.org/api/googleapi/transport&quot;<br>    &quot;google.golang.org/api/youtube/v3&quot;<br>    &quot;net/http&quot;<br>)<br><br>func main() {<br>    client := &amp;http.Client{<br>        Transport: &amp;transport.APIKey{<br>            Key: &quot;YOUR_API_KEY&quot;,<br>        },<br>    }<br><br>    youtubeService, err := youtube.New(client)<br>    if err != nil {<br>        panic(err)<br>    }<br><br>    videoResponse, err := youtubeService.Videos.<br>        List(&quot;statistics&quot;, &quot;snippet&quot;, &quot;contentDetails&quot;).<br>        Id(&quot;VIDEO_ID&quot;).Do()<br>    if err != nil {<br>        panic(err)<br>    }<br><br>    video := videoResponse.Items[0]<br><br>    fmt.Printf(&quot;Title: %s\n&quot;, video.Snippet.Title)<br>    fmt.Printf(&quot;View Count: %s\n&quot;, video.Statistics.ViewCount)<br>    fmt.Printf(&quot;Thumbnai Url: %s\n&quot;, video.Snippet.Thumbnails.Standard.Url)<br>}</pre><h3>Conclusion</h3><p>The YouTube Data API v3 is a powerful tool for developers to access and analyze data from the world’s largest video sharing platform. With features such as video details, channel information, user activities, comments, search, and analytics, developers can create applications that integrate with YouTube and provide better services to users. By following the steps outlined above, developers can start using the YouTube Data API v3 and leverage its capabilities to gain insights and make informed decisions.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=73df8b44b5a0" width="1" height="1" alt=""><hr><p><a href="https://medium.com/code-uncomplicated/youtube-data-api-v3-fetch-view-counts-thumbnails-and-more-73df8b44b5a0">Youtube Data API v3 — fetch view counts, thumbnails and more</a> was originally published in <a href="https://medium.com/code-uncomplicated">Code Uncomplicated</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Virtual Machines on MacOS With QEMU — Intel based]]></title>
            <link>https://medium.com/code-uncomplicated/virtual-machines-on-macos-with-qemu-intel-based-351b28758617?source=rss----4fd5faa62b56---4</link>
            <guid isPermaLink="false">https://medium.com/p/351b28758617</guid>
            <category><![CDATA[operating-systems]]></category>
            <category><![CDATA[qemu]]></category>
            <category><![CDATA[linux]]></category>
            <category><![CDATA[macos]]></category>
            <category><![CDATA[virtual-machine]]></category>
            <dc:creator><![CDATA[Oliver Mascarenhas]]></dc:creator>
            <pubDate>Mon, 12 Dec 2022 10:54:23 GMT</pubDate>
            <atom:updated>2022-12-12T17:05:54.601Z</atom:updated>
            <content:encoded><![CDATA[<h3>Virtual Machines on MacOS With QEMU — Intel based</h3><p>A guide on using QEMU on MacOS to run Virtual Machines</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*LQUGw9wTM0w7mL5ZJE-nxQ.jpeg" /><figcaption>Source: <a href="https://www.flickr.com/photos/sandialabs/4155733531/in/photostream/">https://www.flickr.com/photos/sandialabs/4155733531/in/photostream/</a></figcaption></figure><blockquote>TL;DR</blockquote><blockquote>Commands available here: <a href="https://github.com/oliversavio/youtube-vid-code/tree/main/qemu-virtual-machines-macos">https://github.com/oliversavio/youtube-vid-code/tree/main/qemu-virtual-machines-macos</a></blockquote><p>For the longest time, my go-to tool for spinning up Virtual Machines (VMs) has been VirtualBox. Yes, it works, but it can be a bit fiddly at times.</p><p>Then I came across QEMU, which runs as a command-line application and performed exceptionally well. This is achieved in part due to KVM (Kernel-based Virtual Machine) an open source virtualisation technology that’s built into linux.</p><p>QEMU announced support for Apple’s Hypervisor framework (HVF), this enables VMs to run on MacOS with near native performance.</p><h4>Checkout the Demo in the video below</h4><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FFSHUXe2aMso%3Fstart%3D3%26feature%3Doembed%26start%3D3&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DFSHUXe2aMso&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FFSHUXe2aMso%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/3f9b503590b59741190da2b55c16c07b/href">https://medium.com/media/3f9b503590b59741190da2b55c16c07b/href</a></iframe><h3>Installing QEMU</h3><p>The easiest way to install QEMU on MacOS is via HomeBrew or MacPorts.</p><pre># Homebrew<br>brew install qemu<br><br># MacPorts<br>sudo port install qemu</pre><h3>Create a virtual disk image</h3><p>Create a virtual disk image onto which the OS will be installed. This is done using the qemu-img command. The format of the disk image is qcow2 and the size of the disk is 15 GB .</p><pre>qemu-img create -f qcow2 mydisk.qcow2 15G</pre><h3>Install the OS</h3><p>Now that the virtual disk is ready, the next step is to install the operating system onto it. Since this guide is for Intel based Macs, the command used is qemu-system-x86_64 . The -m and -smp switches specify how much memory and cpu on the host is to be reserved for the guest VM.-cdrom points to the iso image of the operating system that will be installed on the VM and -drive points to the virtual disk created in the first step. The rest of the switches should be left as is.</p><pre>qemu-system-x86_64 \<br>-m 8G \<br>-smp 6 \<br>-cdrom /Volumes/Samsung_T5/iso/Fedora-Workstation-Live-x86_64-35-1.2.iso \<br>-drive file=mydisk.qcow2,if=virtio \<br>-vga virtio \<br>-display default,show-cursor=on \<br>-usb \<br>-device usb-tablet \<br>-cpu host \<br>-machine type=q35,accel=hvf \</pre><p>Once executed, the iso should boot-up. Follow the setup wizard of the OS being installed to complete the installation.</p><h3>Run the Virtual Machine</h3><p>Once the setup is done, the virtual machine is ready. The command is similar to the one above, except the -cdrom switch, which is no longer needed.</p><blockquote>A point to note is the -machine switch with specifies accel=hvf , this tells qemu to run with Apple’s Hypervisor Framework based acceleration which is responsible for the near native perfomance.</blockquote><pre>qemu-system-x86_64 \<br>-m 8G \<br>-smp 6 \<br>-drive file=mydisk.qcow2,if=virtio \<br>-vga virtio \<br>-display default,show-cursor=on \<br>-usb \<br>-device usb-tablet \<br>-cpu host \<br>-machine type=q35,accel=hvf</pre><h3>UTM — A GUI based alternative</h3><p>If using the command line is not something you’re comfortable with, check out UTM. It’s a GUI built around QEMU.</p><p>I believe, it also supports running VMs on Apple Silicon based machines, however that’s not something I have tried.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gBSuxijJtvUGBAW817gtPw.png" /></figure><h3>Reference &amp; Links</h3><ul><li><a href="https://mac.getutm.app/">UTM</a></li><li><a href="https://mac.getutm.app/">Commands</a></li></ul><h3>Support</h3><p><a href="https://www.buymeacoffee.com/4xdMY36Ek">Oliver Mascarenhas is simplifying software engineering concepts &amp;amp; practices.</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=351b28758617" width="1" height="1" alt=""><hr><p><a href="https://medium.com/code-uncomplicated/virtual-machines-on-macos-with-qemu-intel-based-351b28758617">Virtual Machines on MacOS With QEMU — Intel based</a> was originally published in <a href="https://medium.com/code-uncomplicated">Code Uncomplicated</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using database migrations to manage schema changes]]></title>
            <link>https://medium.com/code-uncomplicated/using-database-migrations-to-manage-schema-changes-939dd803a541?source=rss----4fd5faa62b56---4</link>
            <guid isPermaLink="false">https://medium.com/p/939dd803a541</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[database]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Oliver Mascarenhas]]></dc:creator>
            <pubDate>Wed, 09 Nov 2022 06:16:51 GMT</pubDate>
            <atom:updated>2022-11-09T12:42:45.931Z</atom:updated>
            <content:encoded><![CDATA[<p>A guide to manage structural changes to your database</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*HHv1KcC0XfuduC7w" /><figcaption>Great Migration — Wildebeest crossing the Mara river | Flickr</figcaption></figure><p>The first time I came across the concept of database migrations was while learning to build web apps using Rails. As stated in the Rails documentation;</p><blockquote>Migrations are a convenient way for you to alter your database in a structured and organized manner.</blockquote><p>While there are a multitude of tools out there to manage migrations in the language of your choice, the core principles remain the same. You could use a generic tool across languages and frameworks, however using one tailored for your current tech stack will give you the most benefit.</p><p>Let’s look at the core principles when working with migrations.</p><h3>Migrate Up or Down</h3><p>We migrate “UP” to the latest / newer database schema version or migrate “DOWN” to an older / previous database schema version.</p><p>It’s considered a best practice to be able to rollback or reverse migration changes. Each migration is usually organised in two files. One to apply the schema change aka “UP” and one to rollback the changes aka “DOWN”.</p><p>Ensuring the migrations are idempotent will also keep things simple and robust. This is easily achieved by using a statement like CREATE TABLE IF NOT EXISTS or the reverse DROP TABLE IF EXISTS . Running the same migration multiple times will have the same effect as running it once.</p><h3>File naming conventions</h3><p>Migration files need to be prefixed to maintain the order in which the migrations are to be applied. This can be achieved by using:</p><ul><li>Sequence numbers: 0001_migration_name.sql, 0002_migration_name.sql</li><li>Date and time : 20221105151510_migration_name.sql (YYYYMMDDHHMMSS format)</li><li>Timestamps: 1500445949_migration_name.sql</li></ul><h3>File format</h3><p>The format of the migration file can vary depending on the library or framework you are using.</p><p>Usually it will be a regular SQL statement supported by the database you are using.</p><pre>CREATE TABLE IF NOT EXISTS &quot;user&quot; <br>(<br>  id serial primary key,<br>  name text,<br>  email text not null<br>)</pre><p>Or, in the case of Rails, migration files are ruby classes that extend ActiveRecord::Migration</p><pre>class CreateProducts &lt; ActiveRecord::Migration<br>  def change<br>    create_table <strong>:products</strong> do |t|<br>      t.string <strong>:name<br></strong>      t.text <strong>:description<br>    <br>      </strong>t.timestamps<br>    end<br>  end<br>end</pre><h3>Version Controlled</h3><p>All the migrations files should be versioned controlled. One challenge that will surely need to be dealt with in larger teams is having multiple developers making simultaneous changes. This will require some development process in place and co-ordination among team members.</p><p>As a rule of thumb, once a migration file has been committed and pushed, modifications should take place via a new migration. Avoid modifying existing migrations. If the migration file only exists on your local machine, you’re free to modify the same file before it’s committed and pushed.</p><h3>Example with golang-migrate</h3><p>Now let’s take a look at an example using golang-migrate . We’ll use the CLI approach here.</p><h4>Step 1: Create a migration for the user table</h4><pre>❯ migrate create -ext sql -dir migrations -seq create_user_table</pre><p>Creates a migration file with an extension(ext) of sql in the migrations directory (dir) using a sequence (seq).</p><p>This creates two files</p><pre>❯ tree migrations<br>migrations<br>├── 000001_create_user_table.down.sql<br>└── 000001_create_user_table.up.sql</pre><h4>Step 2: Fill in the migration files</h4><pre>------000001_create_user_table.up.sql--------</pre><pre>CREATE TABLE IF NOT EXISTS &quot;user&quot; <br>(<br>  id serial primary key,<br>  name text,<br>  email text not null<br>)</pre><pre>------000001_create_user_table.down.sql--------<br>DROP TABLE IF EXISTS &quot;user&quot;</pre><h4>Step 3: Run migrate UP</h4><p>Assuming you have setup the ENV variable POSTGRESQL_URL , run the migrate “up” with command.</p><pre>❯ migrate -database ${POSTGRESQL_URL} -path migrations up</pre><p>If your syntax is correct, you’ll see a success message.</p><pre>1/u create_user_table (29.238127ms)</pre><p>Here POSTGRESQL_URL is the connection string to connect to the database, e.g.</p><pre>export POSTGRESQL_URL=postgres://scott:tiger@localhost:5432/example?sslmode=disable&amp;search_path=public</pre><h4>Step 4: Run migrate DOWN</h4><p>To reverse the migration we just ran, execute</p><pre>❯ migrate -database ${POSTGRESQL_URL} -path migrations down</pre><h3>Final thoughts</h3><p>And that’s about it. Database migrations are a simple albeit necessary concept to understand when building web applications. Sometimes the term can sound more complex than it actually is.</p><h3>Migrations tools &amp; frameworks</h3><ul><li>Node: <a href="https://github.com/db-migrate/node-db-migrate">https://github.com/db-migrate/node-db-migrate</a></li><li>Rails: <a href="https://guides.rubyonrails.org/active_record_migrations.html">https://guides.rubyonrails.org/active_record_migrations.html</a></li><li>Golang: <a href="https://github.com/golang-migrate/migrate">https://github.com/golang-migrate/migrate</a></li><li>Java: <a href="https://www.liquibase.org/">https://www.liquibase.org/</a></li></ul><h3>References</h3><ul><li><a href="https://github.com/golang-migrate/migrate/blob/master/GETTING_STARTED.md">https://github.com/golang-migrate/migrate/blob/master/GETTING_STARTED.md</a></li><li><a href="https://guides.rubyonrails.org/v3.2/migrations.html">https://guides.rubyonrails.org/v3.2/migrations.html</a></li><li><a href="https://github.com/golang-migrate/migrate">https://github.com/golang-migrate/migrate</a></li><li><a href="https://blog.f5.works/best-practices-manage-database-schema-changes-with-database-migration-and-version-control/">https://blog.f5.works/best-practices-manage-database-schema-changes-with-database-migration-and-version-control/</a></li></ul><h3>Support</h3><p>If you like reading my content and find it helpful, please consider buying me a coffee!</p><p><a href="https://www.buymeacoffee.com/4xdMY36Ek">Oliver Mascarenhas is simplifying software engineering concepts &amp;amp; practices.</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=939dd803a541" width="1" height="1" alt=""><hr><p><a href="https://medium.com/code-uncomplicated/using-database-migrations-to-manage-schema-changes-939dd803a541">Using database migrations to manage schema changes</a> was originally published in <a href="https://medium.com/code-uncomplicated">Code Uncomplicated</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Use a SSH Tunnel to access your private cloud server(s) — AWS / GCP / Azure]]></title>
            <link>https://medium.com/code-uncomplicated/use-a-ssh-tunnel-to-access-your-private-cloud-server-s-aws-gcp-azure-5214aab400b4?source=rss----4fd5faa62b56---4</link>
            <guid isPermaLink="false">https://medium.com/p/5214aab400b4</guid>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[linux]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[cloud-computing]]></category>
            <category><![CDATA[ssh-tunnel]]></category>
            <dc:creator><![CDATA[Oliver Mascarenhas]]></dc:creator>
            <pubDate>Mon, 26 Sep 2022 07:42:05 GMT</pubDate>
            <atom:updated>2022-09-26T07:47:16.854Z</atom:updated>
            <content:encoded><![CDATA[<h3>Using a SSH Tunnel to access your private cloud server(s) — AWS / GCP / Azure</h3><p>A guide to securely access private database or application servers from your local workstation</p><h3><strong>What is an SSH Tunnel</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rsED1e71abcR-TcvVJGTdg.png" /><figcaption>SSH Tunnelling aka SSH Port Forwarding</figcaption></figure><p>SSH tunnel aka SSH port forwarding enables your local development environment, to securely access a <strong>Private Server</strong> which cannot and should not be accessed directly via the public internet. This is usually facilitated by an intermediate <strong>Jump Server. </strong>Jump Servers can be accessed via the public internet and usually have hardened security in place which allows access only to specific ports and IP address ranges.</p><p>In the picture depicted above, we setup a secure connection or tunnel from the local machine to the Jump Server and configure a port to forward data to the appropriate private server.</p><h3>Typical Cloud environment setup — AWS</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VUGVI1DvxhVp_7GtvdaX1w.png" /><figcaption>Simplified AWS Deployment</figcaption></figure><p>Here’s a simplified AWS configuration, you have a VPC or Virtual Private Cloud which is divided into Public and Private Subnets - the latter being inaccessible via the public internet. The application and database servers are deployed within the private subnet. An HTTP(S) endpoint is exposed to the internet via the Application Load Balancer or ALB which in turn is configured as a reverse proxy to the Application server.</p><h3>The SSH command</h3><p>Let’s define some terms before we start</p><ul><li>jump-server-ip — The IP address of the publicly accessible server, in the example above it’s the jump server deployed with the public subnet.</li><li>jump-server-user — Username to log into the server. When using Amazon Linux on AWS , this defaults to ec2-user when using Ubuntu it defaults to ubuntu.</li><li>private-key.pem — This is the identity file or private key used to login to the server.</li><li>app-server-ip — The IP address of the private application server you want to access from your local machine. This could well be the database server as you’ll see in the use case below.</li><li>local-port — A free port on your local machine which will be used to tunnel traffic to the private server. Usually a port number greater than 1024 is specified.</li></ul><p>Let’s start with the command you’re probably familiar with. SSH into a remote machine, in this case it’s our Jump server.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/33870795b7f6c1a6a7939e6d52bec656/href">https://medium.com/media/33870795b7f6c1a6a7939e6d52bec656/href</a></iframe><p>Next, we’ll use the following switches:</p><ul><li>-L local-port:app-server-ip:app-server-port— to specify which port on our local machine to use to forward requests to the app server.</li><li>-N — This prevents the execution of a remote command since we’re only interested in port forwarding.</li></ul><p>We’ll put it all together by looking at two use cases.</p><h3>Use Cases</h3><blockquote>Assumption: The Jump server is appropriately configured to allow SSH access on port 22 via an identity file or private key.</blockquote><h4>View application logs</h4><p>We have our application server running within a private subnet, for example with an IP 100.0.1.101 . To view the application logs, we’ll need to SSH into the server. In order to do this from our local machine, we’ll setup a tunnel via the Jump server. As stated above, the IP of our Jump server is 40.23.32.111 and is configured with default user ec2-user .</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/891ec7a3133016b9019b22935bcddcb6/href">https://medium.com/media/891ec7a3133016b9019b22935bcddcb6/href</a></iframe><p>Once our tunnel is setup, open another terminal window and SSH into the application server as if it were running on your local machine i.e. 127.0.0.1 .</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d113e452c22a191698844f786af8901c/href">https://medium.com/media/d113e452c22a191698844f786af8901c/href</a></iframe><p>A few things to note here:</p><ul><li>We assume both the Jump server and remote application server can be accessed with the same identity file i.e. private-key.pem . This may not always be the case, servers may be configured with different identity files.</li><li>The -p switch overrides the default SSH port 22 and uses our forwarding port 9090 .</li></ul><p>Now you should be logged into the application server and can view the logs.</p><h4>Connect to a remote Database</h4><p>Now we’ll connect to a Postgres database which runs on port 5432 by default. We’ll assume the same port is free on our local machine and create a SSH tunnel.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2c8fd7ecf4190f7830cf9ac44dd5612a/href">https://medium.com/media/2c8fd7ecf4190f7830cf9ac44dd5612a/href</a></iframe><p>Here 10.0.11.120 is the IP address of our database server. Once this is running we can connect to it via our client of choice.</p><p>Here’s an example connecting the psql client</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b1ea47bc26855e3ab969422fce4d2386/href">https://medium.com/media/b1ea47bc26855e3ab969422fce4d2386/href</a></iframe><p>A few things to note:</p><ul><li>The database user is scott</li><li>Database name is ecomm_db</li><li>On successful connection you will be prompted to enter a password.</li></ul><h3>Conclusion</h3><p>Understanding how to use SSH tunnels is a useful tool to have in todays cloud environments. Do not be tempted to give your database or application server public access just because it’s convenient. With SSH tunnelling you can securely access you private servers.</p><h3>References &amp; Further reading</h3><ul><li><a href="https://www.ssh.com/academy/ssh/tunneling">https://www.ssh.com/academy/ssh/tunneling</a></li><li><a href="https://linuxize.com/post/how-to-setup-ssh-tunneling/">https://linuxize.com/post/how-to-setup-ssh-tunneling/</a></li></ul><h3>Support</h3><p><a href="https://www.buymeacoffee.com/4xdMY36Ek">Oliver Mascarenhas is simplifying software engineering concepts &amp;amp; practices.</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5214aab400b4" width="1" height="1" alt=""><hr><p><a href="https://medium.com/code-uncomplicated/use-a-ssh-tunnel-to-access-your-private-cloud-server-s-aws-gcp-azure-5214aab400b4">Use a SSH Tunnel to access your private cloud server(s) — AWS / GCP / Azure</a> was originally published in <a href="https://medium.com/code-uncomplicated">Code Uncomplicated</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why you should consider a Nginx reverse proxy for your Microservice]]></title>
            <link>https://medium.com/code-uncomplicated/why-you-should-consider-a-nginx-reverse-proxy-for-your-microservice-9deb6b5996cb?source=rss----4fd5faa62b56---4</link>
            <guid isPermaLink="false">https://medium.com/p/9deb6b5996cb</guid>
            <category><![CDATA[api]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[nginx]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[cloud-computing]]></category>
            <dc:creator><![CDATA[Oliver Mascarenhas]]></dc:creator>
            <pubDate>Thu, 05 May 2022 10:07:38 GMT</pubDate>
            <atom:updated>2022-05-05T10:07:38.765Z</atom:updated>
            <content:encoded><![CDATA[<p>A few use-cases to consider, a Nginx reverse proxy in front of your Microservice</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FFd9MtwGcQRTZFEaY_9nuw.png" /><figcaption>Nginx Reverse Proxy</figcaption></figure><p>So far we’ve looked at <a href="https://medium.com/code-uncomplicated/building-apis-in-go-beyond-hello-world-5d501d6403de">setting up our API</a>, <a href="https://medium.com/code-uncomplicated/you-should-unit-test-your-api-endpoints-its-easy-a685abc87982">testing it</a> and <a href="https://www.youtube.com/watch?v=pP2DKCKR4CQ">monitoring it</a>. Now we take it a step further with Nginx. All the use-cases described below can be achieved within our Go application with some amount of code, however web servers like Nginx are very efficient at these tasks and can do them with a few lines of configuration.</p><p>Setting up Nginx as a reverse proxy to an API server is a fundamental use-case. Reverse proxying help us with controlling:</p><ul><li>Accessibility to endpoints</li><li>Routing</li><li>SSL termination <em>(Not discussed in this post)</em></li><li>Load Balancing</li><li>Throttling / Rate limiting</li></ul><h3>Reverse proxy / URI routing</h3><p>Using the proxy_pass directive in Nginx, we can control which URIs are accessible. In this example, the swagger documentation endpoints we generated in Part 1 will not be accessible via Nginx.</p><p>With the help of nested location directives we can route to different API backends or different versions of the same backend as illustrated in the snippet below.</p><p>The nesting allows us to specify common properties like log location and proxy headers. Additionally, we could portray multiple microservices as a single service to the API clients.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/97b17fe97ec46beb00edf847e2b1c7f8/href">https://medium.com/media/97b17fe97ec46beb00edf847e2b1c7f8/href</a></iframe><blockquote>The way Nginx works, requests received from the client are stopped at the web server and a new request is sent to the backend. This results in loss of http headers, in order to make these headers available to the backend, we use the proxy_set_header directive.</blockquote><h3>Load balancer</h3><p>Modern cloud vendors provide SLAs around “availability”, it’s common to read about the 4 nines or 99.99% of availability. Having a load balancer in front of your API is the first step to achieve this. Firstly, it helps distribute the burden of processing among multiple instance of the application and more importantly, clients can continue to access your service in case one of the backend instances goes offline due to errors or upgrades.</p><p>The upstream directives allows us to specify a group of servers among which requests will be load balanced. Round-robin is the default load balancing method when nothing is specified. The other methods available in the open source version of Nginx are:</p><ul><li>Leas Connections — least_conn</li><li>IP Hash — ip_hash</li><li>Generic Hash — hash $request_uri</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8ea812475482d5da774212c9dc103897/href">https://medium.com/media/8ea812475482d5da774212c9dc103897/href</a></iframe><p>Using max_fails and, fail_timeout we can configure the number of failed attempts before deeming a server offline and the time after which a connection should be reattempted. The modified server configuration snippet is as follows.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b051e1c2f5bdb0261f38345b7bd39351/href">https://medium.com/media/b051e1c2f5bdb0261f38345b7bd39351/href</a></iframe><h3>Error pages</h3><p>Web servers like Nginx have default error pages, however when working with APIs it’s essential to send a response that&#39;s appropriate for the API client&#39;s consumption.</p><p>Another strategy is to map all 404 errors to 400, this prevents unauthorized clients from discovering the API structure. We can even go a step further and map all 5xx errors to a 503 and prevent server side exceptions and stack traces from propagating to the client.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8fe194ee35dec63631e3c665ebee841d/href">https://medium.com/media/8fe194ee35dec63631e3c665ebee841d/href</a></iframe><blockquote>Yes, you can configure this in your microservice, and we have done so in Part 1 of this series. However, configuring it at the Nginx level serves as a catch-all. It also ensures you have a consistent response across micro-services.</blockquote><h3>Rate Limiting</h3><p>It is essential to set up rate limits to protect your downstream application from being overwhelmed with requests. In today’s cloud environments, all services have rate limits set, you may have come across the “<strong>TooManyRequestsException</strong>” when using AWS services like S3.</p><p>Nginx implements the leaky bucket algorithm for rate limiting. We start by defining a request limit zone limit_req_zone and then use the limit_req directive within the location block we wish to limit.</p><blockquote>The Nginx documentation recommends including burst and the nodelay parameters to the limit_req directive for most deployments.</blockquote><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5783c6d9535cd74cbb1d093a2a9d95ce/href">https://medium.com/media/5783c6d9535cd74cbb1d093a2a9d95ce/href</a></iframe><h3>Bringing it all together</h3><p>All the configuration explained above is set up via docker. You can find the entire example here <a href="https://github.com/oliversavio/youtube-vid-code/tree/nginx/go-api-starter">https://github.com/oliversavio/youtube-vid-code/tree/nginx/go-api-starter</a>.</p><p>I will make a video explaining the Docker specific configurations sometime in the near future. If that’s something you’re looking forward to, please subscribe to my YouTube channel and hit the bell icon for instant notifications of a new video.</p><p><a href="https://www.youtube.com/channel/UCeeR00eo9qKiY-z3VQPQPBA">Code Uncomplicated</a></p><h3>References &amp; Further reading</h3><ul><li><a href="https://medium.com/code-uncomplicated/building-apis-in-go-beyond-hello-world-5d501d6403de">Part 1 — Building REST APIs beyond Hello World.</a></li><li><a href="https://medium.com/code-uncomplicated/you-should-unit-test-your-api-endpoints-its-easy-a685abc87982">Part 2 — Unit Testing API endpoints.</a></li><li><a href="https://www.youtube.com/watch?v=pP2DKCKR4CQ">Part 3 — Monitoring with Grafana and Prometheus.</a></li><li><a href="https://www.nginx.com/blog/deploying-nginx-plus-as-an-api-gateway-part-1/">Deploying Nginx as an API Gateway — Part 1</a></li><li><a href="https://docs.nginx.com/nginx/admin-guide/load-balancer/http-load-balancer/">HTTP Load balancing with Nginx</a></li><li><a href="https://www.nginx.com/blog/rate-limiting-nginx/">Rate Limiting with Nginx</a></li><li><a href="https://www.atlassian.com/blog/statuspage/high-availability">Four nines and beyond: A guide to high availability infrastructure</a></li></ul><h3>Support</h3><p>Any support would be appreciated if you find my content helpful.</p><p><a href="https://www.buymeacoffee.com/4xdMY36Ek">Oliver Mascarenhas is simplifying software engineering concepts &amp;amp; practices.</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9deb6b5996cb" width="1" height="1" alt=""><hr><p><a href="https://medium.com/code-uncomplicated/why-you-should-consider-a-nginx-reverse-proxy-for-your-microservice-9deb6b5996cb">Why you should consider a Nginx reverse proxy for your Microservice</a> was originally published in <a href="https://medium.com/code-uncomplicated">Code Uncomplicated</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[You should Unit Test your API endpoints, it’s easy!]]></title>
            <link>https://medium.com/code-uncomplicated/you-should-unit-test-your-api-endpoints-its-easy-a685abc87982?source=rss----4fd5faa62b56---4</link>
            <guid isPermaLink="false">https://medium.com/p/a685abc87982</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[test-driven-development]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[api-development]]></category>
            <category><![CDATA[microservices]]></category>
            <dc:creator><![CDATA[Oliver Mascarenhas]]></dc:creator>
            <pubDate>Thu, 17 Feb 2022 11:00:04 GMT</pubDate>
            <atom:updated>2022-03-28T07:33:57.839Z</atom:updated>
            <content:encoded><![CDATA[<p>An uncomplicated guide to unit test RESTful API endpoints in Go</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iX33n1IdlSIzNQpWMdu_nA.png" /></figure><p>Continuing to improve on the foundation setup in “<a href="https://medium.com/code-uncomplicated/building-apis-in-go-beyond-hello-world-5d501d6403de">Building APIs in Go beyond Hello World</a>” we’ll look at an approach for unit testing API endpoints.</p><p>It’s going to involve a bit of refactoring of the base project to make the code unit test friendly, however it should be intuitive to follow along.</p><blockquote><strong>TL;DR</strong><br>Source Code: <a href="https://github.com/oliversavio/youtube-vid-code/tree/unit-test/go-api-starter">https://github.com/oliversavio/youtube-vid-code/tree/unit-test/go-api-starter</a></blockquote><h3>Watch the video instead of reading?</h3><p><em>Bonus: I’ve added some funky tunes!!</em></p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FtTz7b2AongA%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DtTz7b2AongA&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FtTz7b2AongA%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/800d09522c9179f0c7275a5d7c20eacd/href">https://medium.com/media/800d09522c9179f0c7275a5d7c20eacd/href</a></iframe><h3>Encapsulate out the Server creation</h3><p>Create a struct to hold the fiber application, this can also hold the services and act as a dependency injection mechanism.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/568/1*1Pch-W1nugKKgaZ_izZAfw.png" /><figcaption>The Server struct</figcaption></figure><h3>Creating and testing the Server</h3><p>Now, in the unit tests, we can create an instance of the server and provide it the necessary mock service implementations. As you can see from the example in the code, fiber gives us the ability to call the “Test” method, which takes in a http request and gives back a response. The code snippet below is a slightly modified version of the examples provided by <a href="https://github.com/gofiber/recipes/tree/master/unit-test">fiber</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*r0gaiCCMcqKHDAGKb7VKZg.png" /><figcaption>Unit Test for API Endpoint</figcaption></figure><h3>Defining and Mocking the Service layer</h3><p>Defining the service as an interface lets us pass in mocked implementations during unit testing.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dtN6SKMVyGnXe5NOT7U28g.png" /><figcaption>Mocking the Service Layer</figcaption></figure><p>Setting up and unit testing with this approach ensures we test out our configuration from</p><blockquote>Endpoint -&gt; Route -&gt; Handler -&gt; Service Layer</blockquote><h3>References &amp; Links</h3><ul><li><strong>GoFiber examples</strong> <br><a href="https://github.com/gofiber/recipes">https://github.com/gofiber/recipes</a></li><li><strong>Part 1: Building APIs in Go beyond Hello World</strong><br><a href="https://medium.com/code-uncomplicated/building-apis-in-go-beyond-hello-world-5d501d6403de">https://medium.com/code-uncomplicated/building-apis-in-go-beyond-hello-world-5d501d6403de</a></li><li><strong>Part 3:</strong> <strong>How to set up API monitoring with Prometheus &amp; Grafana<br></strong><a href="https://www.youtube.com/watch?v=pP2DKCKR4CQ">https://www.youtube.com/watch?v=pP2DKCKR4CQ</a></li><li><strong>Source Code</strong><br><a href="https://github.com/oliversavio/youtube-vid-code/tree/unit-test/go-api-starter">https://github.com/oliversavio/youtube-vid-code/tree/unit-test/go-api-starter</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a685abc87982" width="1" height="1" alt=""><hr><p><a href="https://medium.com/code-uncomplicated/you-should-unit-test-your-api-endpoints-its-easy-a685abc87982">You should Unit Test your API endpoints, it’s easy!</a> was originally published in <a href="https://medium.com/code-uncomplicated">Code Uncomplicated</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building APIs in Go beyond Hello World]]></title>
            <link>https://medium.com/code-uncomplicated/building-apis-in-go-beyond-hello-world-5d501d6403de?source=rss----4fd5faa62b56---4</link>
            <guid isPermaLink="false">https://medium.com/p/5d501d6403de</guid>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[api]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Oliver Mascarenhas]]></dc:creator>
            <pubDate>Wed, 19 Jan 2022 09:47:45 GMT</pubDate>
            <atom:updated>2022-04-01T05:49:03.203Z</atom:updated>
            <content:encoded><![CDATA[<p>My current minimal approach when building production ready APIs in Go (golang).</p><p><strong><em>Update: Part Three</em></strong></p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FpP2DKCKR4CQ%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DpP2DKCKR4CQ&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FpP2DKCKR4CQ%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/44b5d9976c6da664473975ad34fdf92f/href">https://medium.com/media/44b5d9976c6da664473975ad34fdf92f/href</a></iframe><p><strong><em>Update: Part Two</em></strong></p><p><a href="https://medium.com/code-uncomplicated/you-should-unit-test-your-api-endpoints-its-easy-a685abc87982">You should Unit Test your API endpoints, it’s easy!</a></p><blockquote><strong>TL;DR<br></strong>Straight to the Source code then <a href="https://github.com/oliversavio/youtube-vid-code/tree/main/go-api-starter">https://github.com/oliversavio/youtube-vid-code/tree/main/go-api-starter</a></blockquote><p>Let’s get started right away, some of the things I use are as follows:</p><ul><li>A minimal web framework, for this post I’ve choosen <em>gofiber</em></li><li>A way to read configurations at runtime. The approach of using ENV variable has grown on me, we’ll use a lib called <em>godotenv</em> to achieve this.</li><li>A way to (self)document the API, <em>swagger</em> is a popular choice and our web framework integrates well with it. I use <em>swaggo/swag </em>and <em>arsmn/fiber-swagger.</em></li><li>A way to build, package and deploy the API, <em>Docker</em> will be the tool of choice here. Check out the video below for more details how and why I use Docker.</li><li>A way to manage the project on my development machine as well as on remote servers. This is where <em>make</em> will help keep things tidy.</li></ul><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2Ffi5lZTPwNyk%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3Dfi5lZTPwNyk&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2Ffi5lZTPwNyk%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/c5b9c1bac56e4ce3110668d378b08bc3/href">https://medium.com/media/c5b9c1bac56e4ce3110668d378b08bc3/href</a></iframe><h3>Tools needed on development system</h3><ul><li>Docker CE</li><li>make</li><li>Go 1.16</li><li>swaggo/swag</li></ul><h3>Project Dependencies</h3><pre>go get github.com/gofiber/fiber/v2<br>go get github.com/swaggo/swag/cmd/swag<br>go get github.com/arsmn/fiber-swagger/v2<br>go get github.com/joho/godotenv</pre><h3>Project Structure</h3><p>This is a highly opnionated topic, in general the Go convention is to keep things as simple and clear as possible. Here’s what works for me.</p><pre>├── Dockerfile<br>├── Makefile<br>├── config.go<br>├── errors<br>│   └── custom.go<br>├── go.mod<br>├── go.sum<br>├── handlers<br>│   └── handler.go<br>├── main.go<br>├── middlewares<br>│   └── fiber_builtin.go<br>└── routes<br>    ├── public.go<br>    └── swagger.go<br></pre><h3>The Makefile</h3><p>The Makefile is used to build, run, stop the Docker container and generate the swagger documentation. It also contains some default parameters which may be overriden as per the runtime enviroment.</p><pre>ENV=development<br>VERSION=latest<br>LOCAL_PORT=9000</pre><pre>docker.build:<br> docker build -t oliversavio/api:$(VERSION) .</pre><pre>docker.run:<br> docker run --name api_test -d \<br>  -e FOO_ENV=$(ENV) \<br>  -p $(LOCAL_PORT):80 \<br>  --log-driver local \<br>  --log-opt max-size=10m \<br>  --log-opt max-file=5 \<br>  oliversavio/api:$(VERSION)</pre><pre>docker.clean:<br> docker container rm api_test</pre><pre>docker.stop:<br> docker stop api_test</pre><pre>swag:<br> swag init</pre><pre>.PHONY build: swag docker.build</pre><pre>.PHONY run: docker.clean docker.run</pre><blockquote>An important point to note is the use of the “log-driver local” switch when running the Docker container, this uses a filesystem based log store with log rotation.</blockquote><h4>Commands</h4><pre>make build    <br>make run      </pre><h3>The Dockerfile</h3><p>I use multi-stage Docker builds to test, build and create the standalone Docker container to execute the API. One advantage of this approach is that I only have to configure Docker on remote servers.</p><blockquote>This approach plays nicely with the CI/CD mechanism provided by Gitlab and GitHub, however I will not go into it in this post, you may view my previous video on the topic linked below.</blockquote><pre>from golang:1.16 AS builder</pre><pre>LABEL MAINTAINER=&quot;Oliver M&quot;</pre><pre>WORKDIR /src/<br>COPY . .<br>RUN go fmt $(go list ./... | grep -v /vendor/) &amp;&amp;\<br>    go vet $(go list ./... | grep -v /vendor/) &amp;&amp;\<br>    go test -race $(go list ./... | grep -v /vendor/) &amp;&amp;\<br>    GOOS=linux go build -a -o bin/app *.go</pre><pre>FROM debian:buster-slim<br>WORKDIR /api/<br>COPY --from=builder [&quot;/src/bin/app&quot;, &quot;/src/.env*&quot;, &quot;/src/docs&quot;, &quot;/api&quot;]</pre><pre>EXPOSE 80<br>CMD [&quot;./app&quot;]</pre><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FOjc5yc5F2Gs%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DOjc5yc5F2Gs&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FOjc5yc5F2Gs%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/b575ce93a02a7feb924a4780844e042d/href">https://medium.com/media/b575ce93a02a7feb924a4780844e042d/href</a></iframe><h3>The Code</h3><p>I strive to keep this as minimal as possible.</p><h4>The main Function</h4><p>This is where I initialise and configure the web framework aka <em>gofiber </em>in this case, configure the middlewares and routes. Then I start the server and listen for termination/interrupt signals, this is essential to implement a graceful shutdown of the application.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/962/1*WVYYUAHSQDoyOSKPDZKk_w.png" /></figure><h4>Loading ENV and Configuring GoFiber</h4><p>I have merely included the <em>loadEnv()</em> function mentioned in the godotenv documentation <a href="https://github.com/joho/godotenv">here</a>. IMHO the convention on handling configuration across environments works wonderfully.</p><p>Note that fiber has been configured with a custom error handler, we’ll go into the details later in this post. GoFiber and Echo have a nice mechanism of handling errors centrally.</p><blockquote>The approach we use here will work for Echo as well.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aKwB2IH2douY-27GleGefg.png" /></figure><h4>Server Start and Graceful Shutdown</h4><p>In order to implement graceful shutdown for GoFiber, I create a channel which will get notified whever there is an interrupt, typically invoked via CTRL+C. The server listener is started on a seperate go routine and the main thread waits for shutdown interrupts as shown in the section above.</p><p>In the <em>shutdownGracefully()</em> function, I’ve created a timeout and invoked the server shutdown. This ensures either a successful shutdown or a forceful termination of the server. In the defer func() is where other resource like database connections may be released.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lDGAmdELVCD8tFo4TE6SMg.png" /></figure><h4>Custom Error Handling</h4><p>By defining a custom error type, I’m able to propagate specific error responses from either my handler or service code and also have a standard response to unexpected / unhandled errors.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RHhXtsQibNOL9DLwu2-ZNA.png" /></figure><p>An example from handler.go</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1012/1*uiaL69WgeXaQFpiX_ekzZA.png" /><figcaption>handlers/handler.go</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/844/1*QxvBRGgx4hWMEN8fm8XvCg.png" /><figcaption>routes/public.go</figcaption></figure><h3>Swagger Documentation</h3><p>To get started with Swagger documentation, the <em>main()</em> function and the handlers need to have the swagger augmentations via comments. Next we need to ensure the <em>swaggo/swag</em> tool is installed on the development system. If you look at the Makefile in the section above, you’ll notice I have defined a “swag” target, which has been chained to the “build” target. This ensures we generate the most up-to-date documentation whenever there is a change in our code.</p><p>This is what the main function looks like now. You may explore the documentation at <a href="https://github.com/swaggo/swag">https://github.com/swaggo/swag</a> to see all the possible annotations available.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1012/1*hM0N-O8_LcbGi9drTVu6pQ.png" /><figcaption>main.go</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OK6Bv_WyQVv1Dqk7umTjhQ.png" /><figcaption>handlers/handler.go</figcaption></figure><p><strong>Two essential steps for getting the swagger documentaion to work are</strong><br>- Adding <em>import _ “oliversavio/api/docs”</em> to the main.go<br>- Setting up the Swagger route.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gpCqLZL7eweylVbmHMFWfQ.png" /><figcaption>routes/swagger.go</figcaption></figure><p>Now, invoking a <em>make build run </em>should generate the documentation as shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tv77fr6zQjvkdRFESJDHlQ.png" /><figcaption>Generated Swagger Documentation</figcaption></figure><h3>Further Reading</h3><p>There are a lot of advanced topics like monitoring, alerting, distributed tracing etc that are often needed for production application which I have not covered here. Some of the tools I use and encourage you to explore are:</p><ul><li><a href="https://prometheus.io/docs/introduction/overview/">Prometheus</a> for monitoring and alerting.</li><li><a href="https://www.jaegertracing.io/">Jaeger</a> for distributed tracing.</li><li><a href="https://github.com/uber-go/zap">uber-go/zap</a> for structured logging.</li></ul><figure><a href="https://www.buymeacoffee.com/4xdMY36Ek"><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tEuYZbZRIkPUieOP3nReNg.png" /></a></figure><h3>Part Two</h3><p>You can follow along with the next part in this series <a href="https://medium.com/code-uncomplicated/you-should-unit-test-your-api-endpoints-its-easy-a685abc87982">here</a>. This goes into a bit of code refactoring in order to make our API endpoints easier to unit-test.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5d501d6403de" width="1" height="1" alt=""><hr><p><a href="https://medium.com/code-uncomplicated/building-apis-in-go-beyond-hello-world-5d501d6403de">Building APIs in Go beyond Hello World</a> was originally published in <a href="https://medium.com/code-uncomplicated">Code Uncomplicated</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>