<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Danny Aguswahyudi on Medium]]></title>
        <description><![CDATA[Stories by Danny Aguswahyudi on Medium]]></description>
        <link>https://medium.com/@nydan?source=rss-38d5fa077ec2------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*rFjZrJtZO7OaLfrbAAMLmA.jpeg</url>
            <title>Stories by Danny Aguswahyudi on Medium</title>
            <link>https://medium.com/@nydan?source=rss-38d5fa077ec2------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 18 Nov 2026 05:59:14 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@nydan/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Structuring Integration Testing in Golang]]></title>
            <link>https://nydan.medium.com/structuring-integration-testing-in-golang-41f98697ac86?source=rss-38d5fa077ec2------2</link>
            <guid isPermaLink="false">https://medium.com/p/41f98697ac86</guid>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[integration-testing]]></category>
            <category><![CDATA[structure]]></category>
            <category><![CDATA[code]]></category>
            <category><![CDATA[practice]]></category>
            <dc:creator><![CDATA[Danny Aguswahyudi]]></dc:creator>
            <pubDate>Thu, 15 Apr 2021 09:49:06 GMT</pubDate>
            <atom:updated>2021-04-15T09:49:06.270Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oBqquc1vC5kFFintPQ1VLw.jpeg" /><figcaption>Documenting high level flow</figcaption></figure><h4>Integration testing test case structure with a long flow on a HTTP server could be hard to maintain. This is how I structure it as another form of a documentation for the application flow.</h4><p>Writing integration testing for a HTTP server could end up to be a long line of code in Golang. This case is going to happen for a test case that has several steps to achieve a certain state of data. The longer your test case the harder it is to read for understanding the application flow and maintaining it.</p><p>The hard part from writing an integration test is how easy we can understand what the test does. With this post I would like to share how I organize it and give my opinion on it when it is implemented to a team of 3–5 persons.</p><p>In a high level the integration test that I wrote is running these steps:</p><ol><li>Starting your dependency applications (RDBMS, Redis, etc)</li><li>Setup the dependencies (do database migration for RDBMS)</li><li>Starting the HTTP server</li><li>Execute the integration test cases</li></ol><h3>Starting dependency applications</h3><p>The first step is preparing dependencies for your HTTP server. The dependency application can be a RDBMS or Redis server. Creating those dependencies on top of containers is going to help to build and destroy it multiple times whenever we want to run the integration testing. Hence, put this step before we run the integration testing in our CI/CD.</p><h3>Setup the dependency application</h3><p>Once the dependency application is up and running we can go to the next setup. The setup here is more into preparing the application to replicate the actual system in production. In this case we start to do a database migration to set up the database schema, do <a href="https://en.wikipedia.org/wiki/Database_seeding">database seeding</a> or anything that is predefined stuff for your application. Keeping the migration and seed files the same with the production environment to actually replicate the behavior is a good start.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b8827a9e0831a2e7f6485346c532f5ab/href">https://medium.com/media/b8827a9e0831a2e7f6485346c532f5ab/href</a></iframe><h3>Separate the build or not to separate</h3><p>In unit tests we can simply simulate the parameter and mock some func that have another responsibility. In integration tests, we want to make a test that is actually integrated with a dependency application like a database. Spin up a database application and setup database schema is not required in order to run a unit tests. Doing so is going to add the running time for your unit test, and you have to think more about data consistency since your unit test might run in parallel.</p><p>Using <a href="https://golang.org/pkg/go/build/#hdr-Build_Constraints">build tag</a> is one way to separate the scope of unit tests and integration tests. By adding the build tag to all the integration tests files helps us to set up a constraint. When we run go test ./..., go tools only run the unit test and when we run go test ./... — tag={build-tag} it is only runs the integration tests that might take extra steps.</p><p>However, separating the build comes with cons to your project. When you implement build tag to integration testing, failing build won’t be detected on those test files when you simply do go build. This causes you to have a late feedback from your code changes since you only knew it when the integration testing is running. Imagine if you put the step for unit test and integration test in different pipelines in your CI/CD, then it costs you more time to get the failing feedback.</p><h3>Starting the HTTP Server</h3><p>In this step, run the application which is a HTTP server where basically the application is going to read application configurations, make a connection to dependency applications and start to listen and serve for any HTTP requests. For this step, you have to make sure that the configuration is aiming to the dummy dependencies application that you set earlier and not actually connected to the production environment you have.</p><h3>Structuring Test Case</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0f3971a721c7dacff9c2af03f1f01885/href">https://medium.com/media/0f3971a721c7dacff9c2af03f1f01885/href</a></iframe><p>From the struct successLoginTest, it has all the methods that are relevant to the test case and it contains references to be used for a state preparation step, assertion and for clean up step.</p><p>To understand the flow, you can directly go to the TestSuccessLogin(). This func already calls each method from successLoginTest step by step that also shows how the flow of your Login API implicitly. By separating all the steps into a method, it helps us to know the high level flow for a particular test case. Hence, a good method name will help to understand the flow clearly.</p><p>When the test case grew into a more complex case, practically I still found this approach helped the team to understand the flow. That condition only grows the struct for the reference to have more fields and methods, and for the test case it is still a clear flow since each step is separated into a method and good method naming helps so much.</p><p>I found a table driven test is not a good practice when it comes to structuring an integration test. The long test step for preparing the data might end up to be a unique case until you can’t fit it into a struct for the test data. Reading the t.Run(&quot;name&quot;, func() {} part is also not that clear since each step will be renamed with the struct field names.</p><p>Hope this story gives you some more perspective on structuring your integration test in Go. :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=41f98697ac86" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Setup Windows 10 With WSL for Golang Development]]></title>
            <link>https://medium.com/swlh/setup-windows-10-with-wsl-for-golang-development-a284c279d885?source=rss-38d5fa077ec2------2</link>
            <guid isPermaLink="false">https://medium.com/p/a284c279d885</guid>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[powertoys]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[wsl]]></category>
            <category><![CDATA[linux]]></category>
            <dc:creator><![CDATA[Danny Aguswahyudi]]></dc:creator>
            <pubDate>Mon, 03 Aug 2020 15:28:08 GMT</pubDate>
            <atom:updated>2020-08-06T13:46:59.450Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*PM8DtXL9a25Li0F-8xMjFQ.jpeg" /></figure><p>Windows 10 now supports Windows Subsystem for Linux and it let you run GNU/Linux environment on top of the Windows system.</p><p>I am going to walk through the minimum setup for Golang development with Windows 10 + WSL.</p><p>The setups are:</p><ul><li>Installing WSL</li><li>Installing Ubuntu for the WSL</li><li>Installing Docker</li><li>Installing VS Code</li><li>Installing Golang in WSL</li></ul><p>Before you start, check your windows version with Windows Key + R and then type winver.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lFGVGW5ccN64K6qFR78gVw.png" /><figcaption>Windows version</figcaption></figure><p>In case you have Windows version older than version 2004 you can’t install WSL 2, but you still able to install WSL 1. You need to update your Windows 10 to version 2004 Build 19041 in order to install WSL 2. To update it, you can update from your Windows setting or use the <a href="https://support.microsoft.com/en-us/help/3159635/windows-10-update-assistant">Windows update assistant</a>.</p><p>In case you saw this following screen from update assistant, that is fine and you can keep installing WSL and using Linux environment on your Windows.</p><figure><img alt="Update Assistant failed to update Windows to ver 2004" src="https://cdn-images-1.medium.com/max/1024/1*wC8WeyKBWRXb9x1XKtYLyw.png" /><figcaption>Windows update to version 2004 issues</figcaption></figure><p>In my case, it is not an issue with WSL 1 for my development enviroment. For full comparison between WSL and WSL 2 you can check it <a href="https://docs.microsoft.com/en-us/windows/wsl/compare-versions">here</a>.</p><h3>Installing WSL</h3><p>To install WSL, you need to enabling “Windows Subsystem for Linux” optional feature. There are two ways to doing it.</p><p>First way, open PowerShell as Administrator and run:</p><pre>dism.exe /online /enable-feature /featurename:Microsoft-Windows-Subsystem-Linux /all /norestart</pre><p>Second way, goes to Turn Windows features on or off setting and check Virtual Machine Platform and Windows subsystem for Linux</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qCXBv25m4YvxjbeNe69lfQ.png" /><figcaption>Turn Windows features on or off</figcaption></figure><h3>Installing Ubuntu for WSL</h3><p>Installing Ubuntu is pretty simple in Windows 10. You can go to Windows Store and search ubuntu then click “Get”, it will install it on your WSL directly.</p><p>Once the installation is done, try to press Windows Key and type “Ubuntu”, then open the Ubuntu application listed there, you should be redirected to a linux terminal and your linux system already up and running.</p><h3>Install Golang in WSL</h3><p>In this example, we are going to install Go 1.14.4 version, in case you want to install the newer version, the steps should be identical you just need to replace the download link from <a href="https://golang.org/dl/">Go official site</a>. Open your WSL terminal and run these commands:</p><pre># Download the Golang source into ~/Download folder<br>wget -P ~/Download https://golang.org/dl/go1.14.4.linux-amd64.tar.gz                       </pre><pre># Extract the source code<br>sudo tar -C /usr/local/ -xzf ~/Download/go1.14.4.linux-amd64.tar.gz</pre><p>To verify your installation you can type go version and it should show the go version installed on WSL.</p><h3>Installing VS Code</h3><p>For working with VS Code, you should install it on your Windows side, not in the WSL. Go to <a href="https://code.visualstudio.com/">VS Code site</a> and download the Windows installer. Then open the downloaded .exe file and finish the installation.</p><p>When prompted to <strong>Select Additional Tasks</strong> during installation, be sure to check the <strong>Add to PATH</strong> option so you can easily open a folder in WSL by typing code command on the working directory.</p><p>After the installation is finish, install the “Remote Development Extension Pack” to your VS Code. You can install it from <a href="https://marketplace.visualstudio.com/items?itemName=ms-vscode-remote.vscode-remote-extensionpack">here,</a> or you can search it on the VS Code extension market place.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/370/1*xBbc2cIlgWa3o5JyuUv1Qw.png" /><figcaption>Extension Marketplace</figcaption></figure><p>After restarting you VS Code, you should see WSL on the bottom left corner of your VS Code. And now you are able to use your VS Code normally.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/275/1*NDtcAcg9IdIR9jf762kexA.png" /></figure><h3><strong>Installing Docker in WSL</strong></h3><p>This step might not required if you are not using docker for your development. In case you need it you can run these following command from your WSL.<em> (in my case, I am installing Ubuntu 20.04 in my WSL)</em></p><pre># download .deb package for docker                       <br>wget -P ~/Download <a href="https://download.docker.com/linux/ubuntu/dists/focal/pool/stable/amd64/docker-ce_19.03.12~3-0~ubuntu-focal_amd64.deb">https://download.docker.com/linux/ubuntu/dists/focal/pool/stable/amd64/docker-ce_19.03.12~3-0~ubuntu-focal_amd64.deb</a><br>    <br>wget -P ~/Download https://download.docker.com/linux/ubuntu/dists/focal/pool/stable/amd64/docker-ce-cli_19.03.12~3-0~ubuntu-focal_amd64.deb</pre><pre>wget -P ~/Download https://download.docker.com/linux/ubuntu/dists/focal/pool/stable/amd64/containerd.io_1.2.13-2_amd64.deb</pre><pre><br># installing docker-cli and docker-ce                      <br>sudo dpkg -i ~/Downloads/docker-ce-cli_19.03.12\~3-0\~ubuntu-focal_amd64.deb                        </pre><pre>sudo dpkg -i ~/Downloads/containerd.io_1.2.13-2_amd64.deb                       </pre><pre>sudo dpkg -i ~/Downloads/docker-ce_19.03.12\~3-0\~ubuntu-focal_amd64.deb</pre><p>Try verify your installation with docker info, in case you found the output something like this one, try to use sudo.</p><pre>Client:<br> Debug Mode: false</pre><pre>Server:<br>ERROR: Got permission denied while trying to connect to the Docker daemon socket at unix:///var/run/docker.sock: Get <a href="http://%2Fvar%2Frun%2Fdocker.sock/v1.40/info">http://%2Fvar%2Frun%2Fdocker.sock/v1.40/info</a>: dial unix /var/run/docker.sock: connect: permission denied<br>errors pretty printing info</pre><p>If you want to access docker without sudo you can run this following command:</p><pre>sudo usermod -aG docker $USER</pre><p>Afterwards, close the terminal or logout your profile to take effect. That command is going to add your linux user into docker user group.</p><h3>Further Setup</h3><h4>AutoHotkey (Key Mapper)</h4><p><a href="https://www.autohotkey.com/">AutoHotkey</a> will help you to remap your keyboard buttons for better experience with your development. Let say you are using vim and you want to swap your CapsLock into extra Esc button.</p><p>Config for Swap CapsLock into extra Esc button:</p><pre>;Remap hotkeys                       <br>CapsLock::Esc<br>Esc::CapsLock</pre><h4>PowerToys (App Launcher)</h4><p><a href="https://github.com/microsoft/PowerToys">PowerToys</a> is an app launcher that might help you productivity. This app launcher works like “Spotlight Search” in the MacOS.</p><p>References:</p><ol><li>Update Assistant for update Windows 10 to version 2004: <a href="https://support.microsoft.com/en-us/help/4028685/windows-10-get-the-update">https://support.microsoft.com/en-us/help/4028685/windows-10-get-the-update</a></li><li>Install WSL and update to WSL 2: <a href="https://docs.microsoft.com/en-us/windows/wsl/install-win10">https://docs.microsoft.com/en-us/windows/wsl/install-win10</a></li><li>Using VS Code for development in WSL <a href="https://code.visualstudio.com/docs/remote/wsl">https://code.visualstudio.com/docs/remote/wsl</a></li><li>WSL documentation <a href="https://docs.microsoft.com/en-us/windows/wsl/">https://docs.microsoft.com/en-us/windows/wsl/</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a284c279d885" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/setup-windows-10-with-wsl-for-golang-development-a284c279d885">Setup Windows 10 With WSL for Golang Development</a> was originally published in <a href="https://medium.com/swlh">The Startup</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Watching Netflix  in Full-screen with Samsung Dex]]></title>
            <link>https://nydan.medium.com/watching-netflix-in-full-screen-with-samsung-dex-5d29b9e09fc5?source=rss-38d5fa077ec2------2</link>
            <guid isPermaLink="false">https://medium.com/p/5d29b9e09fc5</guid>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[netflix]]></category>
            <category><![CDATA[fullscreen]]></category>
            <category><![CDATA[samsung-dex]]></category>
            <dc:creator><![CDATA[Danny Aguswahyudi]]></dc:creator>
            <pubDate>Sat, 04 Apr 2020 16:05:13 GMT</pubDate>
            <atom:updated>2020-04-04T16:05:13.896Z</atom:updated>
            <content:encoded><![CDATA[<h3>Watching Netflix in Full-screen with Samsung Dex</h3><p>When you are using samsung Dex mode, you find that Netflix app can’t be open in full-screen mode. And it force you to keep watching it in small screen.</p><p>This tutorial might be useful if you having this conditions but not limited to:</p><ol><li>Not a tech expert. Since no need to root your phone at all.</li><li>Having slow / unstable internet connection that force you to download your Netflix movie first and watch it without buffer after it is fully downloaded.</li><li>Enabling <a href="https://help.netflix.com/en/node/101262">Smart Downloads</a> feature from Netflix.</li></ol><p><em>Declaimer: I am using Samsung Galaxy S8 for this tutorial. And do it with your own risk!</em></p><h3>Requirement</h3><p>I am using Samsung S8 for this tutorial, but I think it would works for any other Samsung S series that support Samsung Dex. Before start, you need to enable developer option for your phone. You can follow this samsung official <a href="https://www.samsung.com/uk/support/mobile-devices/how-do-i-turn-on-the-developer-options-menu-on-my-samsung-galaxy-device/">site</a> to do it.</p><p>Once you done it, you should see Developer Option menu at the bottom of your settings.</p><h3>Steps for Enabling Netflix to be full-screen</h3><ol><li>Go into Samsung Dex mode. You can do it with plug your phone to monitor.</li><li>Go to settings &gt; Samsung Dex</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WisaV5kvd2wZZ6QMirnEeQ.jpeg" /><figcaption>Samsung Settings</figcaption></figure><p>3. Go to about About Samsung Dex</p><p>4. Tap Samsung Dex version text multiple times to enable developer option for your Samsung Dex</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1h-5DvnSEm6hs67OivmkIQ.jpeg" /><figcaption>Enabled Samsung Dex developer option</figcaption></figure><p>5. Go back to Samsung Dex and go to Samsung Dex Labs</p><p>6. Enable Force apps to resize</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Jqa7nf92ffauXDF56ZowRA.jpeg" /><figcaption>Enabling Force apps to resize</figcaption></figure><p>7. Go back to Samsung Setting and go to Developer Options</p><p>8. Scroll down and enable Force activities to be resizable</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DD3w76Pr-f9EI68TlRuTQA.jpeg" /></figure><p>9. Open your Netflix apps. And you can click the maximize icon beside close icon on the window. It will show an error and restarting your Netflix app in maximize mode.</p><p>10. Once it starting up again after the error, you can watch it with full screen.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fEHA390Z-rA0_UIw9kINsg.jpeg" /><figcaption>Full-screen Netflix in Samsung Dex mode</figcaption></figure><p>Hope this tutorial helps!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5d29b9e09fc5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How I Structure Go Code After 2 Years Working in Industrial Programming]]></title>
            <link>https://nydan.medium.com/how-i-structure-go-code-after-2-years-working-in-industrial-programming-17ed5ef83e1e?source=rss-38d5fa077ec2------2</link>
            <guid isPermaLink="false">https://medium.com/p/17ed5ef83e1e</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[interfaces]]></category>
            <category><![CDATA[dependency-injection]]></category>
            <category><![CDATA[code-architecture]]></category>
            <category><![CDATA[golang]]></category>
            <dc:creator><![CDATA[Danny Aguswahyudi]]></dc:creator>
            <pubDate>Thu, 03 Jan 2019 03:01:00 GMT</pubDate>
            <atom:updated>2019-01-03T03:01:00.854Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*7Kic39c8bc8vg9dO" /><figcaption>Photo by <a href="https://unsplash.com/@maximilianweisbecker?utm_source=medium&amp;utm_medium=referral">Maximilian Weisbecker</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Currently I’m working on a growing start up company as a software engineer. For day to day basis I need write golang code that able to serve a highly mutable business requirement. Since we know that business is never converge and it is only diverge linearly as the business grows.</p><p>If you are on the same path as me, I believe you also notice that people (engineers) are often come and go. The code on that company also outlives a single engineer as well. Those problems may describe our work environment, an industrial context.</p><p>Industrial programming means writing code once and maintaining it perpetuity. What I mean with maintenance here is a practice of reading and refactoring the code. Based on Peter Bourgon talks about <a href="https://peter.bourgon.org/go-for-industrial-programming/">industrial programming</a>, I learnt that industrial programming favor reads and dependency injection is a powerful tool to optimize for read comprehension.</p><p>So here is some basic knowledge that I used to implementing dependency injection.</p><h4>Dependency Injection (non-container DI)</h4><p><a href="https://en.wikipedia.org/wiki/Dependency_injection">Dependency injection</a> is a technique whereby one object (or static method) supplies the dependencies of another object. A dependency is an object that can be used (a <a href="https://en.wikipedia.org/wiki/Service_(systems_architecture)">service</a>). For example if you have an object that may need a database client to run a function, that means your object is dependent to a database object. So instead of creating a new database connection every time you are going to call that function, we injecting a database object once as a parameter, so that function don’t need to recreate it over and over.</p><p>By implementing this technique, I intent to decouple objects and let the new engineer that join the team can easily understand that the Resource(may be a package in real case) is dependent to a database connection in order to properly running it. Before going to dependency injection, here is an example of simple golang object that depend on database object.</p><pre>package resource</pre><pre>import &quot;database/sql&quot;<br><br>// Resource is type that being used as an object to receive <br>// dependency<br>type Resource struct {<br>	db *sql.DB<br>}<br><br>// New is constructor function that do the injection to Resource<br>func New(db *sql.DB) *Resource {<br>	r := &amp;Resource{<br>		db: db,<br>	}<br><br>	return r<br>}<br><br>// PingDB is method receiver from type Resource which using <br>// database injection from constructor func<br>func (r *Resource) PingDB() error {<br>	return r.db.Ping()<br>}</pre><p>On the snippet above we can see that the constructor function New() receive a database object as parameter to create object Resource. This constructor function can help us to determine what are Resource need to properly run and it help us to check any error in compile time if there is addition/deletion of parameters.</p><h4>Interface</h4><p>An <em>interface type</em> is defined as a set of method signatures. A value of interface type can hold any value that implements those methods. Here is simple example about how interface is going to be useful for implementing dependency injection.</p><pre>package main<br><br>// Dog struct<br>type Dog struct{}<br><br>// Speak is receiver method from Dog struct<br>func (d *Dog) Speak() string {<br>	return &quot;woof&quot;<br>}<br><br>// Animal interface will be like a contract that going to <br>// implement any animal that implementing Speak() method<br>type Animal interface {<br>	Speak() string<br>}<br><br>func main() {<br>	var a Animal<br>	a = &amp;Dog{} // example of using Dog as an Animal<br><br>	fmt.Println(a.Speak())<br>}</pre><p>On example above, interface Animal can receive any kind of type as long as that type has a receiver method Speak() string. The benefit of this way, we can make a <a href="https://en.wikipedia.org/wiki/Loose_coupling">loose coupled</a> code since we don’t need to know what really happen on the (d *Dog) Speak()or I can say the injector. More over we can generate a mock function through the interface Animal as well using <a href="https://github.com/golang/mock">gomock</a>. With those capability it would be more easier to our service to test a specific function since we are using declared interface to create mocking and be more focusing to test another business logic.</p><p><strong>Implementing Dependency Injection</strong></p><p>Based on the knowledge earlier, I implementing dependency injection into three part which are <strong>Injector, Service, Resource. </strong>For simplicity and learning purpose, I will be using a case where there is a user going to make an order in marketplace.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/361/1*ywHwEQKu-0yeQ6t0j6llUQ.jpeg" /><figcaption>Simple flow</figcaption></figure><p><strong>Resource </strong>is a part where all the call to dependencies (database, redis, etc) happen. The call it self will be invoked by injecting the dependency to resource as parameter on constructor func and make this part can be using a single connection over and over (in case of database connection). I implement all the stuff that related to mutating data to resource part.</p><pre>package order</pre><pre>import &quot;database/sql&quot;</pre><pre>// Resource is struct that containing of package user dependencies<br>type Resource struct {<br> db *sql.DB<br>}</pre><pre>// New is constructor function to inject dependency to user resource<br>func New(db *sql.DB) *Resource {<br> return &amp;Resource{<br>  db: db,<br> }<br>}</pre><pre>// CreateOrder do insert order data to database<br>// Will return error when no record found<br>func (r *Resource) CreateOrder(userID int64, item string, quantity int) error {<br> /*<br>  insert data to database<br>  _, err := r.db.Exec()<br> */<br> return nil<br>}</pre><p><strong>Service </strong>is part where we put resource as dependency, and using it to do all of our business logic. In constructing this part, we will rely on interface and it will be a part that consuming the resource. So if a type (resource) support multiple functions and your service only need one of them, we can define it on the interface at the point of use.</p><pre>package order</pre><pre>import &quot;errors&quot;</pre><pre>type (<br> // Order represent order table<br> Order struct {<br>  ID       int64  `db:&quot;id&quot;`<br>  UserID   int64  `db:&quot;user_id&quot;`<br>  Item     string `db:&quot;item&quot;`<br>  Quantity int    `db:&quot;quantity&quot;`<br>  Amount   int64  `db:&quot;amount&quot;`<br> }</pre><pre>// UserService indicate what function from user service that being <br>// used by order service<br> UserService interface {<br>  IsLoggedIn(userID int64) (bool, error)<br> }</pre><pre>// OrderResource indicate what function being used from resource <br>// order<br> OrderResource interface {<br>  CreateOrder(userID int64, item string, quantity int) error<br> }</pre><pre>// Service struct containing list of dependency from service order<br>Service struct {<br>  userService   UserService // This is how each service communicate with each others<br>  orderResource OrderResource<br> }<br>)</pre><pre>// New construct new order service<br>func New(orderResource OrderResource, userService UserService) *Service {<br> return &amp;Service{<br>  orderResource: orderResource,<br>  userService:   userService,<br> }<br>}</pre><pre>// NewOrder is example of using multiple service<br>func (s *Service) NewOrder(userID int64, item string, qty int) error {<br> loggedIn, err := s.userService.IsLoggedIn(userID)<br> if err != nil {<br>  return err<br> }</pre><pre>if !loggedIn {<br>  return errors.New(&quot;please login&quot;)<br> }</pre><pre>return s.orderResource.CreateOrder(userID, item, qty)<br>}</pre><p>On the code above we can see that we use userservice and put it as a dependency to orderservice . Since the userservice is an interface, we can easily make mock of that service and when we are going to test a function that using it, our test become more focus on testing the business logic.</p><p><strong>Injector </strong>will work as a place where you instantiate all your dependencies such as database connection, service packages, resource packages, etc and do the injection to each part. I didn’t implement dependency container approach or others like <a href="https://github.com/uber-go/dig">uber-go/dig</a> or <a href="https://github.com/google/wire">google/wire</a> but rather much simple approach by treating dependencies as parameters to type or constructor.</p><pre>package main</pre><pre>import (<br> resourceorder &quot;github.com/nydan/resource/order/order&quot;<br> resourceuser &quot;github.com/nydan/resource/user/user&quot;<br> serviceorder &quot;github.com/nydan/service/order/order&quot;<br> serviceuser &quot;github.com/nydan/service/user/user&quot;<br>)</pre><pre>func main() {<br> cfg := GetConfig()</pre><pre> db, err := ConnectDatabase(cfg.Database)<br> if err != nil {<br>  panic(err)<br> }</pre><pre> cache, err := ConnectRedis(cfg.Redis)<br> if err != nil {<br>  panic(err)<br> }</pre><pre> resourceUser := resourceuser.New(db, cache)<br> serviceUser := serviceuser.New(resourceUser)</pre><pre> resourceOrder := resourceorder.New(db)<br> serviceOrder := serviceorder.New(resourceOrder, serviceUser)</pre><pre> server := NewServer(cfg.ListenAddr, serviceUser, serviceOrder)<br> server.Run()<br>}</pre><p>At the code above, by the end all the instantiated services will become a parameter on NewServer where you may put your http.Handler there. For my implementation, I made one more package for managing my API and define an interface again at the point of use for what service going to be exposed to public.</p><p>Based on my experience, this approach working well for my requirements. It help engineers to easily adapt the workflow because the code is getting clean and straight forward. It help us to create more efficient unit test because we can mock some part of a function and more focus on the business logic. It help us to easily maintain our code since if we are going to add and/or delete more dependencies, it is checkable on the compile time.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=17ed5ef83e1e" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>