<?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 Muhamad Alfarisy on Medium]]></title>
        <description><![CDATA[Stories by Muhamad Alfarisy on Medium]]></description>
        <link>https://medium.com/@muhamadalfarisy98?source=rss-e82a348689f5------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*l5nGGMG8912VhcP6</url>
            <title>Stories by Muhamad Alfarisy on Medium</title>
            <link>https://medium.com/@muhamadalfarisy98?source=rss-e82a348689f5------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 18 Nov 2026 01:36:35 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@muhamadalfarisy98/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[Stop Writing Nested Subqueries: The Complete Guide to SQL CTEs]]></title>
            <link>https://medium.com/@muhamadalfarisy98/stop-writing-nested-subqueries-the-complete-guide-to-sql-ctes-ab98b15dfd1c?source=rss-e82a348689f5------2</link>
            <guid isPermaLink="false">https://medium.com/p/ab98b15dfd1c</guid>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[golang]]></category>
            <dc:creator><![CDATA[Muhamad Alfarisy]]></dc:creator>
            <pubDate>Sun, 25 Jan 2026 08:46:46 GMT</pubDate>
            <atom:updated>2026-01-25T08:54:38.486Z</atom:updated>
            <content:encoded><![CDATA[<p>If you have ever looked at a SQL query and felt like you were deciphering a nesting doll of SELECT statements inside WHERE clauses, you have encountered “Spaghetti SQL.”</p><p>As backend engineers and data analysts, we often deal with complex logic — multi-level aggregations, intermediate calculations, and hierarchical data. The solution to taming this complexity is not writing <em>smarter</em> subqueries, but writing <em>clearer</em> ones using <strong>Common Table Expressions (CTEs)</strong>.</p><p>In this guide, we will explore why CTEs are a crucial tool in modern SQL, how they compare to temporary tables, and walk through real-world scenarios — including a complex harvesting report generation pipeline.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_UgVLK4R8kIwpZaSCWSePw.png" /></figure><h3>1. What is a CTE?</h3><p>A Common Table Expression (CTE) is a temporary result set that you define within the execution scope of a single SELECT, INSERT, UPDATE, DELETE, or MERGE statement.</p><p>Think of it as a <strong>temporary variable</strong> for your SQL query. Instead of repeating a complex calculation, you define it once, give it a name, and reuse it.</p><h3>The Anatomy of a CTE</h3><p>The syntax uses the WITH clause:</p><pre>WITH revenue_per_region AS (<br>    -- Logic defined once<br>    SELECT region, SUM(amount) as total_revenue<br>    FROM sales<br>    GROUP BY region<br>)<br><br>-- Main query using the CTE<br>SELECT * <br>FROM revenue_per_region <br>WHERE total_revenue &gt; 10000;</pre><h3>2. CTE vs. Subquery vs. Temp Table</h3><p>A common question is: <em>“Why not just use a Temp Table or a Subquery?”</em></p><p>Here is the technical breakdown:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/742/1*79xmKzbBKigVBdTgyZXCIw.png" /><figcaption>Comparison Decision</figcaption></figure><p><strong>Key Takeaway:</strong> Use CTEs when you need to structure a single complex query for readability or when you need to reference the same intermediate result multiple times within that query.</p><h3>3. Real-World Use Cases</h3><h3>Use Case A: The “Don’t Repeat Yourself” (DRY) Principle</h3><p>Without a CTE, if you need to filter employees who earn more than their department’s average, you have to write the average calculation twice.</p><p><strong>The “Spaghetti” Way (Subqueries):</strong></p><pre>SELECT e.name, e.salary<br>FROM employees e<br>WHERE e.salary &gt; <br>  (SELECT AVG(salary) FROM employees WHERE dept_id = e.dept_id)<br>-- The calculation above is invisible and hard to debug</pre><p><strong>The “Clean” Way (CTE):</strong></p><pre>WITH department_average AS (<br>    SELECT dept_id, AVG(salary) as avg_sal<br>    FROM employees<br>    GROUP BY dept_id<br>)<br>SELECT e.name, e.salary, da.avg_sal<br>FROM employees e<br>JOIN department_average da ON e.dept_id = da.dept_id<br>WHERE e.salary &gt; da.avg_sal;</pre><h3>Use Case B: Complex Aggregation Pipelines (The Harvesting Report)</h3><p>This is where CTEs shine. In a recent project, I needed to generate a report calculating harvester wages based on:</p><ol><li>Daily Harvest Totals</li><li>BJR (Bunch Weight Ratio) calculation</li><li>Wage rates</li></ol><p>The logic requires the output of Step 1 to calculate Step 2, and the output of Step 2 to calculate Step 3.</p><p><strong>The Logic Flow:</strong></p><pre>[Harvest Totals] --&gt; [BJR Calculation] --&gt; [Final Wage Calculation]</pre><p>Using CTEs allows us to chain these logic blocks linearly:</p><pre>-- Step 1: Calculate total quantity harvested per block/day<br>WITH harvesting_totals_daily AS (<br>    SELECT <br>        block_id,<br>        DATE(harvest_date) as harvest_date,<br>        SUM(ffb_quantity + medium_quantity + small_quantity) as total_quantity<br>    FROM activity_harvesting<br>    GROUP BY block_id, DATE(harvest_date)<br>),<br>-- Step 2: Calculate BJR (Dependent on Step 1)<br>bjr_harvest_daily AS (<br>    SELECT <br>        ht.block_id,<br>        ht.harvest_date,<br>        -- BJR = Total Weight / Total Quantity<br>        CASE <br>            WHEN ht.total_quantity &gt; 0 THEN tw.total_weight_kg / ht.total_quantity<br>            ELSE 0 <br>        END as bjr<br>    FROM harvesting_totals_daily ht<br>    LEFT JOIN plantation_ffb_sale tw <br>        ON tw.block_id = ht.block_id <br>        AND tw.delivery_date = ht.harvest_date<br>),<br>-- Step 3: Final Calculation (Uses Step 2)<br>upah_panen_harvest AS (<br>    SELECT <br>        h.harvester_name,<br>        h.ffb_quantity,<br>        bd.bjr,<br>        -- Wage = Qty * BJR * Rate<br>        (h.ffb_quantity * bd.bjr * r.rate) as calculated_wage<br>    FROM activity_harvesting h<br>    JOIN bjr_harvest_daily bd <br>        ON bd.block_id = h.block_id AND bd.harvest_date = DATE(h.harvest_date)<br>    JOIN harvest_rate r ON r.block_id = h.block_id<br>)<br>SELECT * FROM upah_panen_harvest;</pre><p><strong>Why this works:</strong></p><ul><li><strong>Modular:</strong> We can debug bjr_harvest_daily independently before using it in the final wage calculation.</li><li><strong>Reusable:</strong> The bjr_harvest_daily CTE is referenced in the final query, but it could also be referenced in a separate summary CTE without recalculating it.</li></ul><h3>Use Case C: Recursive Queries (Hierarchies)</h3><p>Standard SQL struggles with tree structures (like Organization Charts or Category Trees). WITH RECURSIVE allows a query to reference itself.</p><p><strong>Example: Finding the CEO down to Interns</strong></p><pre>WITH RECURSIVE org_tree AS (<br>    -- 1. Anchor Member (The Top Level)<br>    SELECT id, name, manager_id, 1 as level, CAST(name AS TEXT) as path<br>    FROM employees<br>    WHERE manager_id IS NULL<br>    <br>    UNION ALL<br>    <br>    -- 2. Recursive Member (Self-Reference)<br>    SELECT e.id, e.name, e.manager_id, ot.level + 1, ot.path || &#39; &gt; &#39; || e.name<br>    FROM employees e<br>    JOIN org_tree ot ON e.manager_id = ot.id<br>)<br>SELECT * FROM org_tree ORDER BY path;</pre><p><em>This query loops through the table until no more relationships are found, building the “Path” string as it goes.</em></p><h3>4. Performance Considerations &amp; The “Optimization Fence”</h3><p>While CTEs are powerful, they are not a silver bullet.</p><ol><li><strong>Optimization Fence (PostgreSQL &lt; 12):</strong><br>In older versions of PostgreSQL, CTEs were “materialized” separately. The database would run the CTE, store the result, and then run the main query. This prevented the optimizer from pushing down WHERE clauses into the CTE.</li></ol><ul><li><em>Good:</em> If the CTE calculation is heavy and used multiple times.</li><li><em>Bad:</em> If you select 1,000,000 rows in the CTE but only need 10 rows in the main query.</li><li><em>Note: In PostgreSQL 12+, the optimizer can choose to “inline” the CTE (treat it like a subquery) for better performance.</em></li></ul><p><strong>2. No Indexing:</strong><br>Since a CTE is a temporary result, it has no indexes. If you are doing heavy joins <em>inside</em> a CTE result against another large table, performance might suffer compared to a temporary table (where you can add an index).</p><h3>Summary</h3><p>Common Table Expressions are an essential tool for writing professional-grade SQL.</p><p><strong>Use a CTE when:</strong></p><ul><li>✅ You have a complex query with multiple steps (e.g., Aggregation → Calculation → Filtering).</li><li>✅ You need to reuse a calculation result multiple times in one query.</li><li>✅ You are dealing with recursive data (Trees/Graphs).</li><li>✅ You prioritize <strong>Readability</strong> and <strong>Maintainability</strong>.</li></ul><p><strong>Avoid a CTE when:</strong></p><ul><li>❌ The query is extremely simple (it adds unnecessary verbosity).</li><li>❌ You are processing massive datasets where an indexed Temporary Table would offer significant performance gains.</li></ul><p>By moving from nested subqueries to structured CTEs, you not only make your code easier to read for your team but also easier to debug for your future self.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ab98b15dfd1c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Context in Golang]]></title>
            <link>https://medium.com/@muhamadalfarisy98/context-in-golang-d6c1178f46a5?source=rss-e82a348689f5------2</link>
            <guid isPermaLink="false">https://medium.com/p/d6c1178f46a5</guid>
            <category><![CDATA[go]]></category>
            <category><![CDATA[context]]></category>
            <dc:creator><![CDATA[Muhamad Alfarisy]]></dc:creator>
            <pubDate>Tue, 16 Aug 2022 14:07:42 GMT</pubDate>
            <atom:updated>2022-08-16T14:07:42.072Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/315/0*X6H2qGbZH2fLodEw" /><figcaption>Context..</figcaption></figure><p>Context is a data that carries a value, cancel signal, timeout and deadline signals. Context usually created by each request (for instance if there is a request enters into web through <em>http </em>request). Context can be used to pass the value and signal between the process.</p><blockquote>When we want to terminate all processes, we just only need to send a signal to context and automatically terminate it. Almost everything in golang use context like Database, http server, http client, etc.</blockquote><p>Context is represented in an interface Context , found in a package called Context <a href="https://golang.org/pkg/context/"><strong>https://golang.org/pkg/context/</strong></a></p><p><strong>Function to create Context</strong></p><p>context.Background() , is to create an empty context. doesnt have any value, usually used in main function, test function, or in the beginning of request process.</p><p>context.TODO() , is to create an empty context like Background() . But, usually used when we dont sure about its usage.</p><p><strong>Parent and Child Context</strong></p><p>context follows parent and child concept which means we can create child context from previous context. Parent context can have many child, but child context only have one parent.</p><p>parent and child context always connected. if we want to terminate context A , every child from context A will also get terminated.</p><p><strong>Immutable</strong></p><p>context is immutable object, when context is created it cant be altered. when we want to add value inside the context or add timeout configuration and others. Automatically it will create a new child context not changing existing context .</p><p><strong>Creating child context</strong></p><ul><li><strong><em>Context with value</em></strong></li></ul><p>at first context doesnt have any values. we can add a value with key-value data into context. after adding it, automatically will create a new child context that means original context didnt get any change.</p><p>context.WithValue(parent, key, value)</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/265fd58bcc876576e684698186eeb6d1/href">https://medium.com/media/265fd58bcc876576e684698186eeb6d1/href</a></iframe><ul><li><strong><em>Context get value</em></strong></li></ul><p>used to get the value of specified context</p><p>fmt.Println(bgD.Value(&quot;b&quot;))</p><ul><li><strong><em>Context with cancel</em></strong></li></ul><p>when we need to execute other process, we want to give cancel signal to that process. usually this process is like a different goroutine.</p><p>context.WithCancel(parent)</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4ff0cee0f8b0f6e52f7c5cb05fd58bda/href">https://medium.com/media/4ff0cee0f8b0f6e52f7c5cb05fd58bda/href</a></iframe><ul><li><strong><em>Context with timeout</em></strong></li></ul><p>we also can add cancel signal to context automatically with timeout configuration. it will trigger cancel when receive timeout.</p><p>usecase of context with timeout is appropriate when we want to query into database or <em>http</em> API and want to set the timeout limit.</p><p>context.WithTimeout(parent,duration)</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/679b6e69eb907c8935e5e0840d7edfe4/href">https://medium.com/media/679b6e69eb907c8935e5e0840d7edfe4/href</a></iframe><ul><li><strong><em>Context with deadline</em></strong></li></ul><p>using deadline context we can set the time when will the timeout happen.</p><p>context.WithDeadline(parent,time)</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a256893d8277342b047fe8138aceaaa9/href">https://medium.com/media/a256893d8277342b047fe8138aceaaa9/href</a></iframe><ul><li><strong><em>Example Get and Set Context</em></strong></li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/640cad8b8b54f17718621bdeb6301e05/href">https://medium.com/media/640cad8b8b54f17718621bdeb6301e05/href</a></iframe><h3>Conclusion</h3><p>In this article, you created a program to interact with Go’s context package in various ways. Context can be used to pass the value and signal between the process.</p><h3>Reference</h3><ol><li><a href="https://www.digitalocean.com/community/tutorials/how-to-use-contexts-in-go">https://www.digitalocean.com/community/tutorials/how-to-use-contexts-in-go</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d6c1178f46a5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[GoMock in Golang]]></title>
            <link>https://medium.com/@muhamadalfarisy98/gomock-in-golang-7d48e86f7673?source=rss-e82a348689f5------2</link>
            <guid isPermaLink="false">https://medium.com/p/7d48e86f7673</guid>
            <category><![CDATA[mock]]></category>
            <category><![CDATA[golang]]></category>
            <dc:creator><![CDATA[Muhamad Alfarisy]]></dc:creator>
            <pubDate>Tue, 28 Jun 2022 09:40:20 GMT</pubDate>
            <atom:updated>2022-06-28T09:59:49.641Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*h2OQHBsRusmCfJfe24S4qw.png" /></figure><p>GoMock is a Go framework. it integrates well with the built-in testing package, and provides flexibility during unit test. As we know, unit testing of codes with external resources (databases, networks, and files) or dependencies is always a pain.</p><h3>Installation</h3><p>In order to use <strong>GoMock</strong>, we need to install the gomock package github.com/golang/mock/gomock and mockgen code generation tool github.com/golang/mock/mockgen. use this command line:</p><pre>go get github.com/golang/mock/gomock<br>go github.com/golang/mock/mockgen</pre><p>Usage of <em>GoMock </em>follows four basic steps:</p><ol><li>Use mockgen to generate a mock for the interface you wish to mock.</li><li>In test section, create an instance of gomock.Controller and pass it to your mock object’s constructor to obtain a mock object.</li><li>Call EXPECT() on mocks to set up the expectation and return values.</li><li>Call Finish() on the mock controller to assert the mock’s expectations.</li></ol><h3>Getting our hand dirty</h3><p>Lets create a folder like this</p><p>gomock_test<br>├── doer<br>│ └── doer.go<br>├── mocks<br>│ └── mock_doer.go<br>└── uzer<br> ├── user.go<br> └── user_test.go</p><p>doer/doer.go</p><pre>package doer</pre><pre>type Doer interface {<br>  DoSomething(int, string) error<br>  SaySomething(string) string<br>}</pre><p>then here’s the code that we want to test while mocking out the Doer interface:</p><p>uzer/user.go</p><pre>package uzer</pre><pre>import &quot;gomock_test/doer&quot;</pre><pre>const (<br> filtered   = &quot;OK&quot;<br> unfiltered = &quot;spam&quot;<br> Nice       = &quot;nice&quot;<br> Bad        = &quot;bad&quot;<br>)</pre><pre>type User struct {<br> // struct while mocking the doer interface<br> Doer doer.Doer<br>}</pre><pre>// method Use using it<br>func (u *User) Use() error {<br> return u.Doer.DoSomething(123, &quot;Hello GoMock&quot;)<br>}</pre><pre>func (u *User) SaySomething(num int) string {<br> if num == 3 {<br>  return u.Doer.SaySomething(unfiltered)<br> }<br> return u.Doer.SaySomething(filtered)<br>}</pre><pre>type Student struct {<br>}</pre><pre>func (s *Student) DoSomething(_ int, _ string) error {<br> panic(&quot;not implemented&quot;) // TODO: Implement<br>}</pre><pre>func (s *Student) SaySomething(kata string) string {<br> if kata == filtered {<br>  return Nice<br> }<br> return Bad<br>}</pre><p>we’ll put the mock for Doer in a package mocks. We start by creating a directory mocks that will contain our mock implementations and then running mockgen on the doer package:</p><pre>mockgen -destination=../mocks/mock_doer.go -package=mocks gomock_test/doer Doer</pre><p>running mockgen for each package and interface is utopian when there is a large number of interfaces/package to mock. To alleviate this problem, the mockgen command may be placed with go:generate</p><pre>go:generate mockgen -destination=../mocks/mock_doer.go -package=mocks gomock_test/doer Doer</pre><p>we have to create the directory mocks ourselves because GoMock won’t do it for us and will quit with an error instead.</p><ul><li><strong>-destination=../mocks/mock_doer.go</strong> : put the generated mocks in this path</li><li><strong>-package=mocks</strong> : put the generated mocks in the package</li><li><strong>gomock_test/doer </strong>: generate mocks for this package</li><li><strong>Doer</strong> : generate mocks for this interface (required), as we need to specify which the interfaces to generate mocks. (can specify multiple interfaces if needed as a comma-seperated list. e.g, Doer1, Doer2)</li></ul><p>as our invocation of mockgen places a file mocks/mock_doer.go in our project. This is how such a generated mock implementation looks:</p><pre>// Code generated by MockGen. DO NOT EDIT.<br>// Source: gomock_test/doer (interfaces: Doer)</pre><pre>// Package mocks is a generated GoMock package.<br>package mocks</pre><pre>import (<br> reflect &quot;reflect&quot;</pre><pre>gomock &quot;github.com/golang/mock/gomock&quot;<br>)</pre><pre>// MockDoer is a mock of Doer interface.<br>type MockDoer struct {<br> ctrl     *gomock.Controller<br> recorder *MockDoerMockRecorder<br>}</pre><pre>// MockDoerMockRecorder is the mock recorder for MockDoer.<br>type MockDoerMockRecorder struct {<br> mock *MockDoer<br>}</pre><pre>// NewMockDoer creates a new mock instance.<br>func NewMockDoer(ctrl *gomock.Controller) *MockDoer {<br> mock := &amp;MockDoer{ctrl: ctrl}<br> mock.recorder = &amp;MockDoerMockRecorder{mock}<br> return mock<br>}</pre><pre>// EXPECT returns an object that allows the caller to indicate expected use.<br>func (m *MockDoer) EXPECT() *MockDoerMockRecorder {<br> return m.recorder<br>}</pre><pre>// DoSomething mocks base method.<br>func (m *MockDoer) DoSomething(arg0 int, arg1 string) error {<br> m.ctrl.T.Helper()<br> ret := m.ctrl.Call(m, &quot;DoSomething&quot;, arg0, arg1)<br> ret0, _ := ret[0].(error)<br> return ret0<br>}</pre><pre>// DoSomething indicates an expected call of DoSomething.<br>func (mr *MockDoerMockRecorder) DoSomething(arg0, arg1 interface{}) *gomock.Call {<br> mr.mock.ctrl.T.Helper()<br> return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, &quot;DoSomething&quot;, reflect.TypeOf((*MockDoer)(nil).DoSomething), arg0, arg1)<br>}</pre><pre>// SaySomething mocks base method.<br>func (m *MockDoer) SaySomething(arg0 string) string {<br> m.ctrl.T.Helper()<br> ret := m.ctrl.Call(m, &quot;SaySomething&quot;, arg0)<br> ret0, _ := ret[0].(string)<br> return ret0<br>}</pre><pre>// SaySomething indicates an expected call of SaySomething.<br>func (mr *MockDoerMockRecorder) SaySomething(arg0 interface{}) *gomock.Call {<br> mr.mock.ctrl.T.Helper()<br> return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, &quot;SaySomething&quot;, reflect.TypeOf((*MockDoer)(nil).SaySomething), arg0)<br>}</pre><p>Next, we define a mock controller inside our test. A mock controller responsible for tracking and asserting the expectations of its associated mock objects. We can obtain a mock controller by passing a value t of type *testing.T to its constructor, and the use it to construct a mock of the Doer interface.</p><pre>//core of gomock<br>mockCtrl := gomock.NewController(t)</pre><pre>//used to trigger final assertions. if its ignored, mocking assertions will never fail<br>defer mockCtrl.Finish()</pre><pre>// create a new mock object, passing the controller instance as parameter</pre><pre>// for a newly created mock object it will accept any input and outpuite</pre><pre>// need to define its behavior with the method expect<br>mockDoer := mocks.NewMockDoer(mockCtrl)</pre><h4>Using argument matchers</h4><p>sometimes we dont care about the specific arguments a mock is called with. with <em>GoMock, </em>a parameter can be expected to have a fixed value or it can be xpected to match a predicate, called a <strong>Matcher. </strong>Matcher is used to represent range of expected arguments to a mocked method. The following matchers are pre-defined in Gomock :</p><ul><li>gomock.Any() : matches any value (any type)</li><li>gomock.Eq(x) : uses reflection to match values that are DeepEqual to x</li><li>gomock.Nil() : matches nil</li></ul><p>uzer/user_test.go<br>so, our unit test will be like this.</p><pre>package uzer</pre><pre>import (<br> &quot;fmt&quot;<br> &quot;testing&quot;</pre><pre> &quot;github.com/golang/mock/gomock&quot;<br> &quot;gomock_test/mocks&quot;<br>)</pre><pre>func TestUse(t *testing.T) {<br> //core of gomock<br> mockCtrl := gomock.NewController(t)</pre><pre>//used to trigger final assertions. if its ignored, mocking assertions will never fail<br> defer mockCtrl.Finish()</pre><pre>// create a new mock object, passing the controller instance as parameter<br> // for a newly created mock object it will accept any input and outpuite<br> // need to define its behavior with the method expect<br> mockDoer := mocks.NewMockDoer(mockCtrl)<br> testUser := &amp;User{Doer: mockDoer}</pre><pre>//<br> // Expect Do to be called once with 123 and &quot;Hello GoMock&quot; as parameters, and return nil from the mocked call.<br> mockDoer.EXPECT().DoSomething(123, &quot;Hello GoMock&quot;).Return(nil).Times(1)</pre><pre>fmt.Println(testUser.Use())<br> fmt.Println()<br>}</pre><pre>func TestUser_SaySomething(t *testing.T) {</pre><pre> mockCtrl := gomock.NewController(t)<br> defer mockCtrl.Finish()</pre><pre> mockDoer := mocks.NewMockDoer(mockCtrl)<br> user := User{<br>  Doer: mockDoer,<br> }</pre><pre>type args struct {<br>  num int<br> }<br> tests := []struct {<br>  name    string<br>  args    args<br>  want    string<br>  expect  func()<br>  wantErr bool<br> }{<br>  {<br>   name: &quot;Positive test case 1&quot;,<br>   expect: func() {<br>    mockDoer.EXPECT().SaySomething(&quot;spam&quot;).Return(&quot;bad&quot;)<br>   },<br>   args:    args{num: 3},<br>   wantErr: false,<br>   want:    &quot;bad&quot;,<br>  },<br> }<br> for _, tt := range tests {<br>  t.Run(tt.name, func(t *testing.T) {<br>   tt.expect()<br>   if got := user.SaySomething(tt.args.num); (got != tt.want) != tt.wantErr {<br>    fmt.Println(&quot;gott :&quot;, got)<br>    t.Errorf(&quot;User.SaySomething() = %v, want %v&quot;, got, tt.want)<br>   }<br>  })<br> }<br>}</pre><p>and the unit test result will be like this:</p><pre>=== RUN   TestUser_SaySomething<br>=== RUN   TestUser_SaySomething/Positive_test_case_1<br>--- PASS: TestUser_SaySomething (0.00s)<br>    --- PASS: TestUser_SaySomething/Positive_test_case_1 (0.00s)<br>PASS<br>ok      github.com/tokopedia/go_learning/udemy/pzn/gomock_test/uzer     1.100s</pre><h3>Takeaways</h3><p>It’s possible to do unit test without calling external dependencies. Using mocking framework helps us in many ways, build clean and lightweight unit tests. Combined with interface and dependency injection.</p><h3>Reference</h3><ol><li><a href="https://www.myhatchpad.com/insight/mocking-techniques-for-go/">https://www.myhatchpad.com/insight/mocking-techniques-for-go/</a></li><li><a href="https://blog.codecentric.de/en/2017/08/gomock-tutorial/">https://blog.codecentric.de/en/2017/08/gomock-tutorial/</a></li><li><a href="https://betterprogramming.pub/a-gomock-quick-start-guide-71bee4b3a6f1">https://betterprogramming.pub/a-gomock-quick-start-guide-71bee4b3a6f1</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7d48e86f7673" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[NSQ Example in Golang]]></title>
            <link>https://towardsdev.com/nsq-example-in-golang-f69d38e1475c?source=rss-e82a348689f5------2</link>
            <guid isPermaLink="false">https://medium.com/p/f69d38e1475c</guid>
            <category><![CDATA[message-queue]]></category>
            <category><![CDATA[go]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[nsq]]></category>
            <dc:creator><![CDATA[Muhamad Alfarisy]]></dc:creator>
            <pubDate>Tue, 22 Mar 2022 10:04:04 GMT</pubDate>
            <atom:updated>2022-06-28T21:54:30.744Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Xg0ZPnaNvgXwGFbhp1gvZQ.jpeg" /></figure><p>Message queue provides a new asynchronous way for services to communicate with each other. Compared to an API, a message queue has many advantages, such as :</p><ul><li><strong>Optimize Performance</strong></li></ul><blockquote>The producer doesn’t need to wait for the consumer to finish their jobs thus optimizing the performance</blockquote><ul><li><strong>Reliability</strong></li></ul><blockquote>the level of persistence in messaging queue helps to minimalize the data loss when part of the system goes down</blockquote><ul><li><strong>Scalability</strong></li></ul><blockquote>Scaling the producer and consumer separately to meet needs</blockquote><h3><strong>Introduction</strong></h3><p>NSQ (<em>New Simple Queue</em>) is a real time distributed messaging platform written in Go. The core component of the NSQ is consist of :</p><ul><li><strong><em>nsqd</em></strong> is the daemon that receives, queues, and delivers messages to clients</li><li><strong><em>nsqlookupd</em></strong> is the daemon that manages <strong>topology information</strong>. Clients query nsqlookupd to discover nsqd producers for a specific topic and nsqd nodes broadcast topics and channel information</li><li><strong><em>nsqadmin </em></strong>is a web UI to view aggregated cluster stats in real-time and perform various administrative tasks.</li></ul><p>A single nsqd instance is designed to handle multiple streams of data at once. Streams called “topic” and a topic has 1 or more “channel”. Each channel receives a copy of all the messages for a topic.</p><p>Both topics and channels are not pre-configured. <em>Topics</em> are created <strong>on first publish</strong> on the named topic or by <strong>subscribing channel</strong> on the named topic. <em>Channels</em> are created on the first use of subscribing to the named channel, and both buffer data independently of each other.</p><p>A channel generally does have multiple clients connected and each message will be delivered to a random client</p><h3><strong>Session 1 : Quick Start Example</strong></h3><p>The following steps will run a small NSQ cluster on your local machine and walk through publish, consuming and archiving message to disk.</p><ul><li>open a terminal, start <strong>nsqlookupd</strong></li></ul><pre>nsqlookupd</pre><ul><li>open other shell, start <strong>nsqd</strong></li></ul><pre>nsqd --lookupd-tcp-address=127.0.0.1:4160 --broadcast-address=127.0.0.1</pre><ul><li>in other shell, start <strong>nsqadmin</strong></li></ul><pre>nsqadmin --lookupd-http-address=127.0.0.1:4161</pre><ul><li><strong>publish</strong> an initial message (it will create the topic in the cluster too)</li></ul><pre>curl -d &#39;hello world 1&#39; &#39;http://127.0.0.1:4151/pub?topic=test&#39;</pre><ul><li>to <strong>verify</strong> things worked as expected, in a web browser open http://127.0.0.1:4171 or localhost:4171 to view the nsqadmin UI and see statistics</li></ul><h3><strong>Session 2 : Getting our hand dirty</strong></h3><p><strong>Step 1 : creating producer file</strong></p><p>create file producer.go</p><pre>package main</pre><pre>import (<br> &quot;encoding/json&quot;<br> &quot;log&quot;<br> &quot;time&quot;</pre><pre>&quot;github.com/nsqio/go-nsq&quot;<br>)</pre><pre>type Message struct {<br> Name      string `json:&quot;name&quot;`<br> Content   string `json:&quot;content&quot;`<br> Timestamp string `json:&quot;time_stamp&quot;`<br>}</pre><pre>const (<br> addr       = &quot;127.0.0.1:4150&quot;<br> FirstTopic = &quot;nsq_send&quot;<br>)</pre><pre>func main() {<br> //instantiate the config<br> config := nsq.NewConfig()</pre><pre>//creating the producer using nsqd addres<br> producer, err := nsq.NewProducer(addr, config)<br> if err != nil {<br>  log.Fatal(err)<br> }</pre><pre>//init topic name and message<br> msg := Message{<br>  Name:      &quot;Message Name example&quot;,<br>  Content:   &quot;faris ganteng 1&quot;,<br>  Timestamp: time.Now().String(),<br> }</pre><pre>//convert message as []byte<br> payload, err := json.Marshal(msg)<br> if err != nil {<br>  log.Println(err)<br> }</pre><pre>//publish message<br> err = producer.Publish(FirstTopic, payload)<br> if err != nil {<br>  log.Println(err)<br> }</pre><pre>defer producer.Stop()<br>}</pre><p>run this file go run producer.go and listenthe topic through nsq_tail -topic nsq_send -nsqd-tcp-address 127.0.0.1:4150</p><p>the result would be :</p><pre>{&quot;name&quot;:&quot;Message Name example&quot;,&quot;content&quot;:&quot;Content&quot;,&quot;Timestamp&quot;:&quot;2022-03-22 15:12:29.074724 +0700 WIB m=+0.000928418&quot;}</pre><p><strong>Step 2: creating consumer file</strong></p><pre>package main</pre><pre>import (<br> &quot;encoding/json&quot;<br> &quot;fmt&quot;<br> &quot;log&quot;<br> &quot;os&quot;<br> &quot;os/signal&quot;<br> &quot;syscall&quot;<br> &quot;time&quot;</pre><pre>&quot;github.com/nsqio/go-nsq&quot;<br>)</pre><pre>type (<br> messageHandler struct{}<br> Message        struct {<br>  Name      string `json:&quot;name&quot;`<br>  Content   string `json:&quot;content&quot;`<br>  Timestamp string `json:&quot;time_stamp&quot;`<br> }<br>)</pre><pre>func main() {<br> //instantiate config<br> config := nsq.NewConfig()</pre><pre>//tweak several common setup the config<br> //max number of times this consumer will attempt to process a message before giving up<br> config.MaxAttempts = 10</pre><pre>//max number of messages to allow in flight<br> config.MaxInFlight = 5</pre><pre>//maximum duration when Requeueing<br> config.MaxRequeueDelay = time.Second * 900<br> config.DefaultRequeueDelay = time.Second * 0</pre><pre>//init topic name and channel<br> topic := &quot;nsq_send&quot;<br> channel := &quot;channel_example&quot;</pre><pre>//creating consumer<br> consumer, err := nsq.NewConsumer(topic, channel, config)<br> if err != nil {<br>  log.Fatal(err)<br> }</pre><pre>//Set the handler for message received by this consumer.<br> consumer.AddHandler(&amp;messageHandler{})</pre><pre>//use nsqlookupd to find nsqd instances<br> consumer.ConnectToNSQLookupd(&quot;127.0.0.1:4161&quot;)</pre><pre>//wait for signal to exit<br> sigChan := make(chan os.Signal, 1)<br> signal.Notify(sigChan, syscall.SIGINT, syscall.SIGTERM)<br> &lt;-sigChan</pre><pre>//gracefully stop the consumer<br> defer consumer.Stop()</pre><pre>}</pre><pre>// HandleMessage implements the Handler interface.<br>func (h *messageHandler) HandleMessage(m *nsq.Message) error {</pre><pre>//process the message<br> var request Message<br> if err := json.Unmarshal(m.Body, &amp;request); err != nil {<br>  log.Println(err)<br>  return err<br> }</pre><pre>//print the message<br> log.Println(&quot;Name :&quot;, request.Name)<br> log.Println(request)</pre><pre>//log body<br> fmt.Println(&quot;bod&quot;)<br> log.Println(string(m.Body))<br> return nil<br>}</pre><p>Notes: The consumer will need to sometimes to query the <em>nsqlookupd</em></p><h3><strong>Conclusion</strong></h3><p>NSQ or message queue can be used in Golang with using package github.com/nsqio/go-nsq which golang provide.</p><h3><strong>Reference</strong></h3><ol><li><a href="https://levelup.gitconnected.com/implementing-messaging-queue-nsq-in-golang-using-docker-99b402293b12">https://levelup.gitconnected.com/implementing-messaging-queue-nsq-in-golang-using-docker-99b402293b12</a></li><li><a href="https://nsq.io/overview/design.html">https://nsq.io/overview/design.html</a></li><li><a href="https://pkg.go.dev/github.com/nsqio/go-nsq#section-readme">https://pkg.go.dev/github.com/nsqio/go-nsq#section-readme</a></li><li><a href="https://medium.com/@jawadahmadd/nsq-with-go-77ca1b69c4ec">https://medium.com/@jawadahmadd/nsq-with-go-77ca1b69c4ec</a></li><li><a href="https://nsq.io/overview/quick_start.html">https://nsq.io/overview/quick_start.html</a></li><li><a href="https://pkg.go.dev/github.com/nsqio/go-nsq">https://pkg.go.dev/github.com/nsqio/go-nsq</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f69d38e1475c" width="1" height="1" alt=""><hr><p><a href="https://towardsdev.com/nsq-example-in-golang-f69d38e1475c">NSQ Example in Golang</a> was originally published in <a href="https://towardsdev.com/">Towards Dev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Decode and Encode JSON Data in Golang]]></title>
            <link>https://medium.com/@muhamadalfarisy98/decode-and-encode-json-data-in-golang-1202e9d900?source=rss-e82a348689f5------2</link>
            <guid isPermaLink="false">https://medium.com/p/1202e9d900</guid>
            <category><![CDATA[api]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[json]]></category>
            <dc:creator><![CDATA[Muhamad Alfarisy]]></dc:creator>
            <pubDate>Sat, 19 Mar 2022 12:42:12 GMT</pubDate>
            <atom:updated>2022-03-19T12:42:12.475Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Mdpyrlc0TEznXwfQHdat2A.png" /></figure><p><strong>JSON</strong> or <em>Javascript Object Notation</em> is a standard notation which is used as data communication in web and also a subset of javascript. Go provides encoding/json package that we can use for JSON operation.</p><h3><strong>Introduction</strong></h3><p>In Go, JSON data written as a string . we can convert it become an object in go using json.Unmarshal</p><h3><strong>Decode JSON Into Variable Object Struct</strong></h3><p><strong>Step 1 : Import package and prepare for struct object</strong></p><pre>package main</pre><pre>import &quot;encoding/json&quot;<br>import &quot;fmt&quot;</pre><pre>type User struct {<br>  FullName string `json:&quot;Name&quot;`<br>  Age int<br>}</pre><p>Later, we will use User struct for creating a new stored variable from result of decode json string. For decoding process we use function json.Unmarshal()</p><p><strong>Step 2 : Setup main function</strong></p><pre>func main() {<br>  var jsonString = `{&quot;Name&quot;: &quot;john doe&quot;, &quot;Age&quot;: 27}`<br>  var jsonData = []byte(jsonString)<br>  var data User<br>  <br>  var err = json.Unmarshal(jsonData, &amp;data)<br>  if err != nil {<br>    fmt.Println(err.Error())<br>    return<br>  }</pre><pre>  fmt.Println(&quot;user :&quot;, data.FullName)<br>  fmt.Println(&quot;age  :&quot;, data.Age)<br>}</pre><p>Function unmarshal only accept json data type []byte so we need to cast it first before unmarshaling.</p><p>If we see at User struct, FullName field has tag json:&quot;Name&quot; . This tag is usde for mapping json information to the related field . Parsed Json data have 2 field which Name and Age . Fortunately, field Age has the same name as json data.</p><p>By adding json tag, fields of the struct will automatically stored json data property.</p><h3><strong>Decode JSON into map[string]interface{} &amp; interface{}</strong></h3><p>not only having object struct but also can be converted into map[string]interface{} type.</p><pre>var data1 map[string]interface{}<br>err := json.Unmarshal(jsonData, &amp;data1)</pre><pre>//checking err</pre><pre>fmt.Println(&quot;user :&quot;, data1[&quot;Name&quot;])</pre><p>interface{} type can also be used. as if we want to access the value of property we need to cast it first into map[string]interface{}</p><pre>var data2 interface{}<br>err := json.Unmarshal(jsonData, &amp;data2)</pre><pre>//checking err</pre><pre>var decodedData = data2.(map[string]interface{})<br>fmt.Println(decodedData[&quot;Name&quot;])</pre><h3><strong>Decode Array of JSON into Array of Object</strong></h3><p>still using the same way but we must prepare data type slice of struct first.</p><pre>var jsonString = `[<br>    {&quot;Name&quot;: &quot;john doe&quot;, &quot;Age&quot;: 27},<br>    {&quot;Name&quot;: &quot;doe john&quot;, &quot;Age&quot;: 32}<br>]`</pre><pre>var data []User</pre><pre>var err = json.Unmarshal([]byte(jsonString), &amp;data)<br>if err != nil {<br>    fmt.Println(err.Error())<br>    return<br>}</pre><pre>fmt.Println(&quot;user 1:&quot;, data[0].FullName)<br>fmt.Println(&quot;user 2:&quot;, data[1].FullName)</pre><h3><strong>Encode Object Into JSON String</strong></h3><p>function json.Marshal() is used to encode data into json string. source data can be from struct or map[string]interface{} or slice.</p><p>result of conversion is []byte so if we want to know the real value we need to cast it first into type string</p><pre>var object = []User{{&quot;Jhon&quot;, 26},{&quot;doe john&quot;, 32}}<br>var jsonData, err = json.Marshal(object)<br>if err != nil {<br>  fmt.Println(err)<br>  return<br>}</pre><pre>var jsonString = string(jsonData)<br>fmt.Println(jsonString)</pre><h3>Conclusion</h3><p>Encode and Decode JSON data in Golang can be done using package encoding/json which golang provide. Hope this articles give you enough information.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1202e9d900" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Connect PostgreSQL Database with Golang]]></title>
            <link>https://medium.com/@muhamadalfarisy98/how-to-connect-postgresql-database-with-golang-fd4bb70906a5?source=rss-e82a348689f5------2</link>
            <guid isPermaLink="false">https://medium.com/p/fd4bb70906a5</guid>
            <category><![CDATA[postgresql]]></category>
            <category><![CDATA[go]]></category>
            <dc:creator><![CDATA[Muhamad Alfarisy]]></dc:creator>
            <pubDate>Wed, 16 Mar 2022 13:56:45 GMT</pubDate>
            <atom:updated>2022-10-18T01:35:04.321Z</atom:updated>
            <content:encoded><![CDATA[<p>connect postgresql database with go lang</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*6FJBkqooZ5UZ0RNqPUpUaQ.png" /></figure><h3>Introduction</h3><p>This article will demonstrate you how to connect postgres DB with Golang. Go provides database/sql package which helps us to interact with our database.</p><p><strong>Step 1 : Install package </strong><strong>lib/pq as Database driver for postgres</strong></p><pre>go get -u github.com/lib/pq</pre><p><strong>Step 2 : Define Postgresql Credential details</strong></p><pre>const (<br>   host     = &quot;localhost&quot;<br>   port     = 5432<br>   user     = &quot;muhamad.alfarisy&quot;<br>   password = &quot;postgres&quot; <br>   dbname   = &quot;go_psql_db&quot;<br>)</pre><p>and import these below packages</p><pre>import (<br>&quot;database/sql&quot;<br>&quot;flag&quot;<br>&quot;fmt&quot;<br>&quot;log&quot;<br>&quot;time&quot;<br>_ &quot;github.com/lib/pq&quot;<br>)</pre><p><strong>Step 3 : Create a function to open db connection</strong></p><pre>func <strong>openDbConnection</strong>() (*sql.DB, error) {</pre><pre> log.Println(&quot;Open db connection&quot;)</pre><pre> connString := fmt.Sprintf(&quot;host=%s port=%d user=%s &quot;+&quot;password=%s                  dbname=%s sslmode=disable&quot;,<br>  host, port, user, password, dbname)</pre><pre> db, err := sql.Open(&quot;postgres&quot;, connString)</pre><pre> checkErr(err)</pre><pre> return db, nil<br>}</pre><p><strong>Step 4 : Call the function in main</strong></p><pre>func main() {<br> db, err := openDbConnection()<br> checkErr(err)</pre><pre> //close db at the of function<br> defer db.Close()</pre><pre> //test our connection<br> err = db.Ping()<br> checkErr(err)<br> fmt.Println(&quot;DB connected&quot;)</pre><pre>}</pre><pre>func checkErr(err error) {<br> if err != nil {<br>  panic(err)<br> }<br>}</pre><p>we can use Ping() method on sql.DB object to test our connection. db.Ping() will force open a database connection to confirm if we are succesfully connected to the database.</p><p>so the main.go file will look like this :</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7c90ca3182e1664634623f7331d65c3b/href">https://medium.com/media/7c90ca3182e1664634623f7331d65c3b/href</a></iframe><h3>Conclusion</h3><p>Interacting Psql database can be done with GoLang using database/sql package.</p><p><strong>Reference</strong></p><ol><li><a href="https://data-nerd.blog/2020/04/11/connecting-to-postgresql-from-go-lang-project/">https://data-nerd.blog/2020/04/11/connecting-to-postgresql-from-go-lang-project/</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fd4bb70906a5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Read a CSV file in Golang]]></title>
            <link>https://medium.com/@muhamadalfarisy98/read-a-csv-file-in-golang-30edc1bea265?source=rss-e82a348689f5------2</link>
            <guid isPermaLink="false">https://medium.com/p/30edc1bea265</guid>
            <category><![CDATA[go]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[csv]]></category>
            <dc:creator><![CDATA[Muhamad Alfarisy]]></dc:creator>
            <pubDate>Thu, 03 Mar 2022 09:07:05 GMT</pubDate>
            <atom:updated>2022-03-03T09:07:05.878Z</atom:updated>
            <content:encoded><![CDATA[<p>parse your csv files in go</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/563/1*P70dmgcIUC869wScp2_wOw.png" /></figure><p>CSV files are widely used in web applications to export or import dynamic data. Go provides encoding/csv package to read CSV file. Here is the example how to implement it.</p><p><strong>Step 1 : Prepare csv file</strong></p><p>create or generate csv file with format .csv (for this example query.csv) and we will use it for sample reading data.</p><pre>&quot;product_id&quot;,&quot;parent_id&quot;,&quot;weight&quot;,&quot;weight_unit&quot;<br>15381388,15381386,0,0<br>15381399,15381397,0,0<br>15381410,15381408,0,0<br>15381421,15381419,0,0<br>15381432,15381430,0,0<br>15381443,15381441,0,0<br>15437593,15381700,0,0<br>15437594,15381700,0,0<br>15438433,15432697,0,0<br>15438434,15432697,0,0<br>15438435,15432697,0,0</pre><p><strong>Step 2: Create main.go</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a41b5ef69a1c8b7178f03353085063f8/href">https://medium.com/media/a41b5ef69a1c8b7178f03353085063f8/href</a></iframe><p>let’s break some part to clearly define what is code doing. the first part is about Go try to open csv file using os packageand close the file at the end of function. If the file is failed to open, it will print the error message <strong>no such file or directory.</strong></p><pre>csvFile , err := os.Open(&quot;query.csv&quot;)<br>if err != nil { <br>   fmt.Println(err)<br>}<br>defer csvFile.Close()</pre><p>Next, we jump into parsing data process using ReadAll() method</p><pre>csvLines, err := csv.NewReader(csvFile).ReadAll()<br>if err != nil {<br>  fmt.Println(err)<br>}</pre><p>then we have to loop over the csvLines in order to read the data line by line.</p><pre>for i, line := range csvLines {<br>  //omit header line<br>  if i &gt; 0 {<br>     Variant := queryVariant{<br>        ProductID:  line[0],<br>        ParentID:   line[1],<br>        Weight:     line[2],<br>        WeightUnit: line[3],<br>     }</pre><pre>  fmt.Println(Variant.ProductID, &quot;| &quot;, Variant.ParentID, &quot;| &quot;,        Variant.Weight, &quot;| &quot;, Variant.WeightUnit)<br>  }<br>}</pre><p>Finally, the outputs are :</p><pre>Succesfully open file</pre><pre>15381388 |  15381386 |  0 |  0 <br>15381399 |  15381397 |  0 |  0 <br>15381410 |  15381408 |  0 |  0<br>15381421 |  15381419 |  0 |  0 <br>15381432 |  15381430 |  0 |  0 <br>15381443 |  15381441 |  0 |  0 <br>15437593 |  15381700 |  0 |  0 <br>15437594 |  15381700 |  0 |  0 <br>15438433 |  15432697 |  0 |  0 <br>15438434 |  15432697 |  0 |  0 <br>15438435 |  15432697 |  0 |  0 <br>15438436 |  15432697 |  0 |  0</pre><p>We successfully parsed csv file using golang. if you want to compare the time taken to parse using golang and other programming languages. you can set t:= time.Now() before read csv file and print time.Since(t).String() after parsing data and compare with other language time taken.</p><pre>time taken to parsed (go) : 1.4405ms</pre><pre>time taken to parsed (python) : 0.0015721321106s</pre><h3><strong>Conclusion</strong></h3><p>Parsing csv file using golang can be done using package encoding/csv which golang provide. You can scale up the data structure you want to process. Hope this articles helps.</p><p><strong>Reference</strong></p><ol><li><a href="https://webdamn.com/how-to-read-csv-file-using-golang/">https://webdamn.com/how-to-read-csv-file-using-golang/</a></li><li><a href="https://gosamples.dev/read-csv/">https://gosamples.dev/read-csv/</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=30edc1bea265" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Pointer in Golang]]></title>
            <link>https://medium.com/@muhamadalfarisy98/pointer-in-golang-8422317b0648?source=rss-e82a348689f5------2</link>
            <guid isPermaLink="false">https://medium.com/p/8422317b0648</guid>
            <category><![CDATA[it]]></category>
            <category><![CDATA[go]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Muhamad Alfarisy]]></dc:creator>
            <pubDate>Fri, 25 Feb 2022 03:57:35 GMT</pubDate>
            <atom:updated>2022-03-03T09:20:12.803Z</atom:updated>
            <content:encoded><![CDATA[<h4>elaborates more about pointer in golang</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/474/1*fEvBQ0wqRsz4H3v-BxsexA.jpeg" /></figure><p>Pointer is an address value memory on a variable. there are 2 operators in pointer :</p><blockquote><strong>&amp;</strong> (ampersand symbol), <em>is used to return the address of a variabel/function, if we put it infront of a named variable, it will return the address of a variable</em></blockquote><blockquote><strong>* </strong>(asterisk symbol), <em>is used to return the data at an address, if we put in front of a pointer or infront of the address it will return the value</em></blockquote><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8c84c0edb151ad831c597c4e486d8c1b/href">https://medium.com/media/8c84c0edb151ad831c597c4e486d8c1b/href</a></iframe><h3><strong>New</strong></h3><p>is alternate way to create a variable and returns a pointer to the variable</p><pre>ptr := new(int)<br>fmt.Printf(&quot;%T\n&quot;, ptr)<br>*ptr = 3<br>fmt.Println(ptr)<br>fmt.Println(*ptr)</pre><h3><strong>Deallocating Memory</strong></h3><p>once we declare a variable and our code is running your space needs to be allocated somewhere in memory for that variable. When we done using it, it should be deallocated. this can cause memory leak (eat a space quickly)</p><p>How space deallocated?</p><p>There are 2 big of memory that relevant to us ( <em>stack and heap). </em><strong><em>Stack</em></strong><em> </em>is an area of memory that is dedicated to function calls (primarily), one of the things is stored in the stack are the <strong>local variables</strong> for a function de-allocated automatically when the function is completed.</p><pre>x ...<br>func() {<br>   x := ...</pre><pre>}</pre><p>normally, stack is the area of these local variables where the function is done, the variables are deallocated automatically.</p><h3><strong><em>Heap</em></strong></h3><p>is persistent, we have to deallocated in manually</p><pre>func() {</pre><pre>x...<br>}<br>//usually in c lang<br>x = malloc(32);<br>free(x);</pre><p>error prone, easy to make a mistake in allocation or deallocation memory but fast.</p><h3><strong>Garbage Collection</strong></h3><p>deallocation is a complicated things so one way to dealing with that is using a garbage collection. Garbage collection is an automatic tool that deals with deallocation so programmer doesn’t give a f*ck about deallocating the memory.</p><p>Go is different , go is a compiled language which enables garbage collection. implementation fast, compiler determines stack &amp; heap.</p><pre>func foo() * int {</pre><pre>x := 1</pre><pre>return &amp;x</pre><pre>}</pre><pre>func main(){</pre><pre>var y *int</pre><pre>y = foo()</pre><pre>fmt.Println(*y)</pre><pre>}</pre><h3><strong>Conclusion</strong></h3><p>go provides pointer, which can be used to access data on the variable address. Go also enables garbage collection which is an automatic tool that deals with deallocation.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8422317b0648" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Unit Test — Benchmark in Golang]]></title>
            <link>https://medium.com/@muhamadalfarisy98/unit-test-in-golang-67f21021acc1?source=rss-e82a348689f5------2</link>
            <guid isPermaLink="false">https://medium.com/p/67f21021acc1</guid>
            <category><![CDATA[unit-testing]]></category>
            <category><![CDATA[unittest]]></category>
            <category><![CDATA[golang]]></category>
            <dc:creator><![CDATA[Muhamad Alfarisy]]></dc:creator>
            <pubDate>Wed, 12 Jan 2022 16:23:17 GMT</pubDate>
            <atom:updated>2022-11-03T05:29:51.091Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/570/1*qqD-porP5jDTPFSl2YXZpw.jpeg" /></figure><p>Unit testing is a function that tests a specific piece of code from a program or package. The job of unit test is to check the correctness of an application, and it’s a crucial part of the Go programming language.</p><h3>Example<strong> isPrime</strong></h3><p><strong>Step 1</strong> : <strong>create file tdd.go</strong></p><p>create a simple function isPrime</p><pre>package main</pre><pre>import &quot;math&quot;</pre><pre>// isPrime - checks whether the input is a prime number or not<br>func isPrime(num int) bool {</pre><pre>  sqroot := math.Sqrt(float64(num))<br>  switch num {<br>   case 0, 1:<br>     return false<br>  }</pre><pre>  for j := 2; j &lt;= int(sqroot); j++ {<br>    if num % j == 0 {<br>      return false<br>    }<br>  }</pre><pre> return true<br>}</pre><pre>// let it empty<br>func main() {}</pre><p><strong>Step 2</strong> : <strong>Generate tdd_test.go</strong><br>hover to function name, right click, generate unit test , and <strong>tdd_test.go</strong> automatically generated.</p><pre>package main</pre><pre>import (<br>  &quot;reflect&quot;<br>  &quot;testing&quot;<br>)</pre><pre>func Test_isPrime(t *testing.T) {</pre><pre> tests := []struct {<br>   name string<br>   num  int<br>   want bool<br> }{<br>   // TODO: Add test cases.<br>  {&quot;1&quot;, 1, false},<br>  {&quot;13&quot;, 13, true},<br>  {&quot;100&quot;, 100, false},<br>  {&quot;24&quot;, 24, false},<br> }</pre><pre> for _, tt := range tests {<br>   t.Run(tt.name, func(t *testing.T) {<br>     if got := isPrime(tt.num); got != tt.want {<br>         t.Errorf(&quot;isPrime(%v) = %v, want %v&quot;, tt.num, got, tt.want)<br>     }<br>   })<br> }<br>}</pre><p><strong>Step</strong> <strong>3 :</strong> <strong>run test</strong></p><p>in your editor like vscode it will show test tab, and you just click `run` the unit test or type a command like.</p><pre>go test ./... -v</pre><h3>Example isPalindrome</h3><blockquote>in this section we will try to improve our algorithm several times, but to ensure we have an improvement without guessing or manual testing we can use benchmark.</blockquote><p><strong>first solution:</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7c8272ad5e6429a47fc319a131f40e2d/href">https://medium.com/media/7c8272ad5e6429a47fc319a131f40e2d/href</a></iframe><p><strong>unit test :</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fe5db398a23c045a7963a5a360aab63f/href">https://medium.com/media/fe5db398a23c045a7963a5a360aab63f/href</a></iframe><p>benchmark test :</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e5cc013e52347fdf48d88bd827af5719/href">https://medium.com/media/e5cc013e52347fdf48d88bd827af5719/href</a></iframe><p>b.N specifies the number of iterations, value is not fixed but dynamically allocated, ensuring the benchmark runs at least one second by default.</p><p>to run benchmark in Go we can use this command:</p><pre>go test -v -bench=. -benchtime=2s -count=5</pre><p>the result shown like this, -8 suffix denotes the number of CPUs used to run benchmark. The function ran <em>7932556</em> times, each call took an average 149.7 ns/op to complete.</p><pre>BenchmarkIsPalindrom-8     7932556           149.7 ns/op        40 B/op          9 allocs/op</pre><p>we will try to decrease average call operation by improving our logic.</p><p><strong>second solution</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e701c50d713c8de7c811d0dc46712d3d/href">https://medium.com/media/e701c50d713c8de7c811d0dc46712d3d/href</a></iframe><pre>BenchmarkIsPalindrom-8       28716463            40.67 ns/op        0 B/op          0 allocs/op</pre><p>looks like there is an improvement, we will try to do the improvement again.</p><p><strong>third solution</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fe7928716de5c5a9f76432841abbb6ef/href">https://medium.com/media/fe7928716de5c5a9f76432841abbb6ef/href</a></iframe><pre>BenchmarkIsPalindrom-8       71886237            16.16 ns/op        0 B/op          0 allocs/op</pre><p>seems it our fastest implementation, by decreasing from 149.7 ns/op to 16.16 ns/op.</p><pre>BenchmarkIsPalindrom-8          72003237                16.29 ns/op<br>BenchmarkIsPalindrom-8          73050278                16.15 ns/op<br>BenchmarkIsPalindrom-8          73929942                16.34 ns/op<br>BenchmarkIsPalindrom-8          71888571                16.80 ns/op<br>BenchmarkIsPalindrom-8          73505391                16.30 ns/op<br>BenchmarkIsPalindrom-8          72919328                16.20 ns/op<br>BenchmarkIsPalindrom-8          72977163                16.10 ns/op<br>BenchmarkIsPalindrom-8          73909260                16.01 ns/op<br>BenchmarkIsPalindrom-8          72277365                16.19 ns/op<br>BenchmarkIsPalindrom-8          72886483                16.06 ns/op</pre><h3><strong>Conclusion</strong></h3><p>Unit test is really important when you develop a feature, and it ensures your function work fine before pushing to staging or production environment. Benchmark can be used to test our code improvement by executing a code segment multiple times and compares each output with the standard — accessing code’s overall performance level.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=67f21021acc1" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>