<?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 Saurabh Kumar on Medium]]></title>
        <description><![CDATA[Stories by Saurabh Kumar on Medium]]></description>
        <link>https://medium.com/@krsaurabh.dev?source=rss-6becbc0a3ee9------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*D4aky7Bi36koGHaYKqfe4w.jpeg</url>
            <title>Stories by Saurabh Kumar on Medium</title>
            <link>https://medium.com/@krsaurabh.dev?source=rss-6becbc0a3ee9------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 22 Nov 2026 21:27:53 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@krsaurabh.dev/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[Understanding Arrays and Slices in Go]]></title>
            <link>https://medium.com/@krsaurabh.dev/understanding-arrays-and-slices-in-go-48915eb275ed?source=rss-6becbc0a3ee9------2</link>
            <guid isPermaLink="false">https://medium.com/p/48915eb275ed</guid>
            <category><![CDATA[arrays]]></category>
            <category><![CDATA[go]]></category>
            <dc:creator><![CDATA[Saurabh Kumar]]></dc:creator>
            <pubDate>Thu, 25 Jan 2024 16:10:37 GMT</pubDate>
            <atom:updated>2024-01-25T16:10:37.209Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*50SoecXRXP147XEL" /><figcaption>Photo by <a href="https://unsplash.com/@marcusurbenz?utm_source=medium&amp;utm_medium=referral">Marcus Urbenz</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Go provides two ways of storing sequential data in your code: Arrays and Slices.</p><p>Arrays are the main primitives for storing sequential data, while Slices act as interfaces on top of arrays.</p><p>As someone coming from Java, I’ve discovered some interesting aspects about how these types work, which make them fundamentally different from how Java deals with arrays.</p><p>Here are a few of my learnings.</p><h4>Arrays are fixed size</h4><p>Arrays size is fixed when they are instantiated and cannot change during run time</p><pre>ints := [4]int{1, 2, 3, 4}<br>// Not allowed as arrays are fixed size and append only works on slices <br>ints = append(ints, 4)<br>fmt.Println(ints)</pre><h4>Array size is part of its type</h4><p>Array size is part of an arrays size and makes them distinct. Even slices of the same size do not count towards the type of a given array size.</p><pre>func main() {<br> intArray4 := [4]int{1, 2, 3, 4}<br> fmt.Println(reflect.TypeOf(intArray4)) // [4]int<br> AcceptsArray4(intArray4)               // Prints [1, 2, 3, 4]<br><br> intArray5 := [5]int{1, 2, 3, 4, 5}<br> fmt.Println(reflect.TypeOf(intArray5)) // [5]int<br> AcceptsArray4(intArray5[:4])           // Not allowed, even though the Slice is of size 4 its not of type [4]int<br>}<br><br>func AcceptsArray4(arr [4]int) {<br> fmt.Println(arr)<br>}</pre><h4>Use the “make” function to initialise arrays at run time</h4><p>Go requires that array size is fixed at compile time. However if you don’t know the array size at compile time then you can use the make function to dynamically allocate memory to an array at run time.</p><pre>n := 3<br>var arr [n]int // Not allowed as array size must be constant a compile time<br><br>arr := make([]int, n) // Use make to allocate memory at run time</pre><h4>Arrays are values and copy over when assigned</h4><p>When assigning one array to another, Go will copy the entire array and make a new instance of the array.</p><pre> array1 := [4]int{1, 2, 3, 4}<br> array2 := array1<br><br> fmt.Println(&amp;array1 == &amp;array2) // False, since array 2 is a completely new array</pre><h4>You can still link them together by using pointers</h4><p>If you want to mutate the original array you can pass its address via a pointer.</p><pre>array1 := [4]int{1, 2, 3, 4}<br>arrayPtr2 := &amp;array1 // Assign the address<br><br>fmt.Println(&amp;array1 == arrayPtr2) // True<br><br>array1[0] = 10<br>fmt.Println(arrayPtr2[0]) // Returns 10</pre><p>One thing that confused me was how fmt.Println(arrayPtr2[0]) works without explicitly dereferencing the pointer. arrayPtr2 holds the address of the original array, and ideally, we should access the elements like this: (*arrayPtr2)[0].</p><p>The reason this works is because Go understands that you are working with an array pointer and implicitly handles the dereferencing for you.</p><h4>Arrays copy values when using index assignment</h4><p>Even when values are assigned to a single index of an array, it will copy the value into that index.</p><pre>x := 1<br>array1 := [4]int{1, 2, 3, 4}<br><br>array1[0] = x<br>x = 4               // Will not mutate the orignal array<br>fmt.Println(array1) // [1, 2, 3, 4]</pre><h4>Use an array of pointers if you want to mutate the individual values</h4><p>There may be times when you have to mutate the original values stored in your array or vice versa. In this case you can use an array of pointers which will maintain this mutability.</p><pre> var array1 [2]*int<br> x1 := 1<br> x2 := 2<br><br> array1[0] = &amp;x1<br> array1[1] = &amp;x2<br><br> for _, x := range array1 {<br>  fmt.Println(*x) // Prints 1, 2<br> }<br><br> x1 = 3<br> x2 = 4<br><br> for _, x := range array1 {<br>  fmt.Println(*x) // Prints 3, 4<br> }</pre><h4>Slices modify the underlying array</h4><p>Slices made on an array will mutate the original array*. The updates on the original array will reflect to the slice as well.</p><blockquote>* : Until they are reallocated</blockquote><pre>array1 := [4]int{1, 2, 3, 4}<br>slice1 := array1[:2]<br>slice2 := array1[:2]<br><br>slice1[0] = 0<br><br>fmt.Println(array1[0]) // Prints 0<br>fmt.Println(slice1[0]) // Prints 0<br>fmt.Println(slice2[0]) // Prints 0</pre><h4>Slices can expand to utilise the full capacity of an array</h4><p>When appending elements to a Slice, it will take over the unused capacity in the underlying array. Be careful as this can mutate other slices pointing to the same array.</p><pre>array1 := [4]int{1, 2, 3, 4}<br>slice1 := array1[:2]<br>slice2 := array1[2:]<br><br>fmt.Println(slice1) // [1, 2]<br>fmt.Println(slice2) // [3, 4]<br><br>slice1 = append(slice1, 5)<br><br>fmt.Println(slice1) // [1, 2, 5]<br>fmt.Println(slice2) // [5, 4], slice 1 over flows and mutates the [2] index in the array</pre><h4>Slices can expand beyond the original array by reallocating to larger array</h4><p>When the slice has used the full capacity of the underlying array, it will need to reallocate to a new larger array in order to append more elements. This is done since arrays are fixed size and you cannot increase the capacity once they are allocated.</p><pre>array1 := [4]int{1, 2, 3, 4}<br>slice1 := array1[:]<br><br>/*<br>  This append operation requires more data than the maximum capacity<br>  of the underlying array. This will cause the slice to reallocate <br>  to a new array of a larger size.<br>*/<br>slice1 = append(slice1, 5)<br>slice1[0] = 10<br><br>fmt.Println(array1[0]) // Prints 1 since the slice is no longer pointing to array1</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=48915eb275ed" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a Simple JDK manager in go]]></title>
            <link>https://medium.com/@krsaurabh.dev/building-a-simple-jdk-manager-in-go-01247d41adfd?source=rss-6becbc0a3ee9------2</link>
            <guid isPermaLink="false">https://medium.com/p/01247d41adfd</guid>
            <category><![CDATA[jdk]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[go]]></category>
            <dc:creator><![CDATA[Saurabh Kumar]]></dc:creator>
            <pubDate>Mon, 22 Jan 2024 18:17:42 GMT</pubDate>
            <atom:updated>2024-01-22T18:19:05.628Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*a3BbkwCP5TEXGv-B" /><figcaption>Photo by <a href="https://unsplash.com/@markusspiske?utm_source=medium&amp;utm_medium=referral">Markus Spiske</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><blockquote>This blog defines a toy JDK manager built using go. The intent is to become comfortable with the go syntax and its tooling, not to write clean or idiomatic go.</blockquote><h3>Background</h3><p>JDK management is a common challenge for many Java developers. While I may not be a java developer anymore, the horrors of JDK management still haunt me.</p><p>So I tried to build a simple JDK manager using Go lang to solve the problem. You can check out the code <a href="https://github.com/saurabh-ku/go-jdk-manager">here</a>.</p><p>The manager follows a straightforward workflow:</p><ol><li>Download the tar.gz package</li><li>Unzips the file</li><li>Set up the symlink to the downloaded path</li></ol><p>The current implementation overrides the same symlink each time, ensuring that as long as JAVA_HOME is set to the JDK directory, the java command will always reflect the latest JDK switched by the manager.</p><p>It’s worth noting that the manager currently only supports arm-based Macs and exclusively downloads the Amazon Corretto distributions of the JDK.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-jxpPxG06JVHWqYVYL__aQ.gif" /></figure><h3>Features</h3><h4>List</h4><p>Show a selection of available JDK versions</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WtvppvCBBsAdcrgk2e7yfw.png" /></figure><h4>Download</h4><p>The manager will automatically download the selected JDK version and set up a symlink to it in the jdk link. By setting JAVA_HOME=jdk in the bash profile, the manager can change the underlying JDK version without requiring the user to manually update the bash profile.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2Tnfpvz-ll_5aN7JbGIPIQ.png" /></figure><h4>Switch</h4><p>Switching is supported for previously downloaded JDK versions. The manager will simply update the symlink to the selected version.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Zh7uVqiTEs__wSLGKRo94w.png" /></figure><h3>Learnings</h3><h4>Writing the response of a http call to file</h4><pre>// Call the URL<br>response, _:= http.Get(url)<br><br>// Create the file to write to<br>file, _ := os.Create(outputFile)<br>defer file.Close()<br><br>// Copy the content from response to file<br>_, err = io.Copy(file, response.Body)</pre><h4>Unzipping files using the gzip and tar library</h4><pre>// Open the gzip Reader<br>gzipReader, _ := gzip.NewReader(file)<br><br>// Open the tar Reader<br>tarReader := tar.NewReader(gzipReader)<br><br>// Loop over the tar files and copy them into the respective target path<br>// Special handling for directories is omited from this snipet<br>for {<br>  header, _ := tarReader.Next()<br>  targetPath := filepath.Join(outputDir, header.Name)<br>  targetFile, _ := os.Create(targetPath)<br>  defer targetFile.Close()<br>  _, err = io.Copy(targetFile, tarReader)<br>}</pre><h4>Setup Symlinks</h4><pre>// Remove the old Symlink<br>os.Remove(&quot;jdk&quot;)<br><br>// Create the new Symlink<br>os.Symlink(targetPath, &quot;jdk&quot;)</pre><p>I’ve learned quite a lot about the os module in Go, working with directories, files, and zips. While the final script is far from being production-ready, it serves as a valuable exercise in Go syntax.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=01247d41adfd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building developer CLI tools with go]]></title>
            <link>https://medium.com/@krsaurabh.dev/building-developer-cli-tools-with-go-0be86204ca7d?source=rss-6becbc0a3ee9------2</link>
            <guid isPermaLink="false">https://medium.com/p/0be86204ca7d</guid>
            <category><![CDATA[cli]]></category>
            <category><![CDATA[prompt-ui]]></category>
            <category><![CDATA[go]]></category>
            <dc:creator><![CDATA[Saurabh Kumar]]></dc:creator>
            <pubDate>Fri, 19 Jan 2024 15:10:24 GMT</pubDate>
            <atom:updated>2024-01-19T15:10:24.616Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RTPM4LlOZ33KbiRGR74Xgg.png" /></figure><p>I recently came across a Go CLI tool that automates the setup of the entire local development environment on your Mac. It installs all dependencies, from language compilers to databases, and even sets up your GitHub SSH keys for you. It’s a very effective tool that simplifies what is normally a tedious process.</p><p>One thing that caught my eye was that, even though it was a CLI app, it had a UI to interact with the various functions that the tool provided. I have long thought about how developers built the dynamic UIs that we see in most modern CLI applications today. My curiosity led me to explore the codebase to figure out how they accomplished it.</p><p>There is a myriad of libraries used to build the entire UI; however, only two really mattered:</p><ol><li><a href="https://github.com/manifoldco/promptui">promptui</a></li><li><a href="https://github.com/fatih/color">color</a></li></ol><p>Just these two simple libraries, along with the built-in ones, are enough to build a great CLI application for automating almost any task.</p><h3>Building a simple UI with promptui</h3><p>promptui makes it very easy to build selection and prompt-based UI. I built a CLI application that lists a few Git repos as a selection and allows the user to choose which one they want to clone. Not a very useful application, but good enough to understand the API.</p><p>You can check out the code <a href="https://github.com/saurabh-ku/go-prompt">here</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*Rk7ifh5DtdGeQJWV64rxHw.gif" /></figure><p>The core of the code is just these few lines:</p><pre>prompt := promptui.Select{<br>  Label: &quot;Select Repo to clone&quot;,<br>  Items: []string{&quot;Python&quot;, &quot;Go&quot;, &quot;Ruby&quot;},<br> }<br><br> _, result, err := prompt.Run()</pre><p>The extremely simple API makes it easy to integrate into any existing script that does selection via flags or argument inputs.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0be86204ca7d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Compiling Protobuf Issue on M1 Mac: Unsupported platform error with protoc-3.11.4]]></title>
            <link>https://medium.com/@krsaurabh.dev/compiling-protobuf-issue-on-m1-mac-unsupported-platform-error-with-protoc-3-11-4-78d2b9f201f2?source=rss-6becbc0a3ee9------2</link>
            <guid isPermaLink="false">https://medium.com/p/78d2b9f201f2</guid>
            <category><![CDATA[protobuf]]></category>
            <category><![CDATA[maven]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Saurabh Kumar]]></dc:creator>
            <pubDate>Wed, 29 Nov 2023 06:48:04 GMT</pubDate>
            <atom:updated>2023-11-29T13:44:47.659Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*MvxtfyCCbRQLfkUU.png" /></figure><p>If you are working with protobuf’s in your Java project then you might have come across this issue while compiling your project.</p><pre>Unsupported platform: protoc-3.11.4-osx-aarch_64.exe</pre><p>This is an issue specific to M1 Macs and can be quite frustrating since none of your colleague’s face this issue on their older Intel Macs.</p><p>Fortunately there is an easy solution to this.</p><p>Configure you <strong><em>protoc</em></strong> plugin like this</p><pre>&lt;plugin&gt;<br>    &lt;groupId&gt;com.github.os72&lt;/groupId&gt;<br>    &lt;artifactId&gt;protoc-jar-maven-plugin&lt;/artifactId&gt;<br>    &lt;!-- 1. Version should be 3.11.4 --&gt;<br>    &lt;version&gt;3.11.4&lt;/version&gt;<br>    &lt;executions&gt;<br>        &lt;execution&gt;<br>            &lt;phase&gt;generate-sources&lt;/phase&gt;<br>            &lt;goals&gt;<br>                &lt;goal&gt;run&lt;/goal&gt;<br>            &lt;/goals&gt;<br>            &lt;configuration&gt;<br>                &lt;!-- 2. Specify the Proto artifact --&gt;<br>                &lt;protocArtifact&gt;com.google.protobuf:protoc:3.21.1&lt;/protocArtifact&gt;<br>                ... Other Config<br>            &lt;/configuration&gt;<br>        &lt;/execution&gt;<br>    &lt;/executions&gt;<br>&lt;/plugin&gt;</pre><ol><li>Specify the version to &gt;= 3.11.4</li><li>Specify the <strong><em>protocArtifact</em></strong>, this is a custom compile provided by google which contains the capability to compile protobuf’s on M1 Mac</li></ol><p>Rebuild you project and It should successfully compile your protobuf’s on your M1 Mac!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=78d2b9f201f2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Custom deserialiser module with Jackson Objectmapper]]></title>
            <link>https://medium.com/@krsaurabh.dev/custom-deserialiser-module-with-jackson-objectmapper-1e4a1673148f?source=rss-6becbc0a3ee9------2</link>
            <guid isPermaLink="false">https://medium.com/p/1e4a1673148f</guid>
            <category><![CDATA[tech]]></category>
            <category><![CDATA[spring]]></category>
            <category><![CDATA[jackson]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[objectmapper]]></category>
            <dc:creator><![CDATA[Saurabh Kumar]]></dc:creator>
            <pubDate>Sat, 04 Nov 2023 13:51:27 GMT</pubDate>
            <atom:updated>2023-11-04T20:57:51.403Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*IUUHvkk7RYl_i0mi" /><figcaption>Photo by <a href="https://unsplash.com/@anniespratt?utm_source=medium&amp;utm_medium=referral">Annie Spratt</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Jackson is one of the most popular json parsing library in Java with capabilities to make custom deserialiser’s for complex objects.</p><p>Crafting custom deserialiser’s is a powerful technique that can streamline the JSON data handling process, especially when dealing with non-standard or complex data formats.</p><h3>Why we need custom deserialiser’s</h3><p>I recently found use for a it while dealing with a third party service which returned data in encrypted format.</p><pre>{<br>  &quot;request_id&quot; : &quot;f18icR1SULfZe5yc9M6LUG0X&quot;<br>  &quot;type&quot; : &quot;ORDER&quot;,<br>  &quot;details&quot; : &quot;BMmwJNL5GN5rnV4eqn/....&quot;<br>}</pre><p>The third party was retuning the details of the order in encrypted Base64 format. This was done as a security measure since the details contain PII information about the client.</p><p>The easier way to deal with this is to map the response into an intermediate object which treats the details as a String object and then maps it into the final object with the decrypted order details.</p><pre>record EncryptedOrderResonse(String requestId, String type, String details)<br><br>record OrderResonse(String requestId, String type, OrderDetails details)<br><br><br>var orderDetails = mapper.readValue(<br>                        encryptor.decrypt(encryptedOrderResonse.details()),<br>                        OrderDetails.class);<br><br>var orderResponse = new OrderResonse(encryptedOrderResonse.requestId(),<br>                                     encryptedOrderResonse.type(),<br>                                     orderDetails);<br>                                       </pre><p>However this makes the code harder to read. Due to the addition of the intermediate object any new fields added in the response will require changes in both the classes and the mapping between them.</p><p>It also adds the decryption right into the business logic which can make the code harder to read.</p><p>This is where custom deserialiser’s come in. By using a custom deserialiser we can create the decrypted order response directly by doing the decryption while the object is being mapped.</p><p>This requires the implementing the StdDeserializer and registering it via the Jackson module system.</p><h3>Building a custom deserialiser’s</h3><p>First we must implement the StdDeserializer which specifies how to deserialise the json</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/28df374cc999b324d36553c65138ca7e/href">https://medium.com/media/28df374cc999b324d36553c65138ca7e/href</a></iframe><p>This deserialiser picks the contents from the json body and then puts them directly into the OrderReponse object and decrypts the details in the process.</p><p>Now we need to register this into our objectmapper.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/132083af2e619a703ea675d3a30c6788/href">https://medium.com/media/132083af2e619a703ea675d3a30c6788/href</a></iframe><p>Now our objectmapper will be able to use this custom module to deserialise any instance of OrderResponse class that it comes across. No need to make any intermediate objects.</p><pre>OrderResponse orderResponse = mapper.readValue(response, OrderResponse.class)</pre><h3>Applications of Custom Deserializers</h3><ol><li>If you are using Spring, then you can mark this instance of the objectmapper as the primary bean. This will allow Spring to use your custom deserialisers while mapping the request objects coming into your controllers.</li><li>Can be used as the mapper for Kafak consumer configuration allowing you to send data in encrypted or compressed format via the publisher directly map it into a useable object on the consumer side.</li><li>Can be as the deserialiser in feign configuration.</li></ol><h3>Conclusion</h3><p>Custom deserialiser allow you to beef up your objectmapper and localise all the custom deserialisation logic to one place. It provides a convenient pay to abstract away the complexity of dealing with non-standard json.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1e4a1673148f" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>