<?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 Lokesh Nanda on Medium]]></title>
        <description><![CDATA[Stories by Lokesh Nanda on Medium]]></description>
        <link>https://medium.com/@nlokesh?source=rss-5ddc6f53c4db------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*fja-K_NeuAZGCXO0</url>
            <title>Stories by Lokesh Nanda on Medium</title>
            <link>https://medium.com/@nlokesh?source=rss-5ddc6f53c4db------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 22 Nov 2026 22:07:38 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@nlokesh/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[How Github Action Workflows can be exposed as APIs?]]></title>
            <link>https://nlokesh.medium.com/how-github-action-workflows-can-be-exposed-as-apis-aaedef0514a6?source=rss-5ddc6f53c4db------2</link>
            <guid isPermaLink="false">https://medium.com/p/aaedef0514a6</guid>
            <category><![CDATA[github-actions]]></category>
            <category><![CDATA[cicd]]></category>
            <category><![CDATA[continuous-integration]]></category>
            <category><![CDATA[github]]></category>
            <category><![CDATA[continuosdelivery]]></category>
            <dc:creator><![CDATA[Lokesh Nanda]]></dc:creator>
            <pubDate>Tue, 07 Oct 2025 16:58:47 GMT</pubDate>
            <atom:updated>2025-10-14T10:04:58.415Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Lfffzq3tZ3DRF_sejx81Mg.png" /><figcaption><strong>GHA as an API</strong></figcaption></figure><p>GitHub Action has emerged as a highly popular choice for Continuous Integration/Continuous Delivery (CI/CD) pipelines. Its widespread adoption is due to its seamless integration directly within the GitHub platform, making it easily accessible and convenient for the software development community. The platform offers a straightforward and easy approach to creating and customizing workflows, including the ability to build and utilize reusable workflows across projects.</p><h3>About Continuous Integration</h3><p>Continuous Integration (CI) is a process that helps in quickly running builds and tests automatically to quickly detect and fix issues in the code. This continuous integration needs to be run as soon as a Pull Request (PR) is merged, so that issues can be detected faster and remediated. Github Action (GHA) is a very popular tool which seamlessly integrates within Github workflows which helps in significantly enhancing the developer productivity.</p><h3>Writing Github Action Workflows</h3><p>It is very easy to write a Github Action Workflow. Here is a sample Workflow that gets triggered when a Pull Request (PR) is opened. This workflow has “run_job” which checksout the code from githib and then simply runs the test. <br><em>Note</em>: For easier understanding commands to run tests have been stripped off.</p><pre>name: PR Open Actions<br>on:<br>  pull_request:<br>    types: [opened]<br>    branches:<br>      - main<br>      <br>jobs:<br>  run_job:<br>    name: Run when PR is opened<br>    runs-on: ubuntu-latest<br>    <br>     steps:<br>      - name: Checkout Code <br>        uses: actions/checkout@v4<br>        <br>      - name: Run Test<br><br>        run: |<br>          echo &quot;✅ Running Tests!.....&quot;<br><br></pre><h3>Github Action Workflows as APIs</h3><p>Now coming to the crux of this article, where we want to use the Github Action Workflows as APIs. In this case, we had a use case where we own a Github Action Workflow and we want other internal teams to trigger and use this workflow. Our initial reaction was why not give the complete Github Action Workflow code to the internal teams which they can use it as part of their workflow, but this has couple of issues,</p><ol><li>How to update the shared GHA workflow in case of any issues or updates?</li><li>How to share the credentials of our internal systems which this GHA workflow access?</li></ol><p>Considering the above issues, it became easier to share the GHA workflow as API rather than GHA Workflow code.</p><p>Here comes workflow_dispatch!,</p><p>The workflow_dispatch event in GitHub Actions allows for manually triggering a workflow, providing the capability to run workflows on demand. Additionally, you can customize input parameters for the workflow_dispatch event which provides flexibility in running your workflows based on the internal teams input configuration.</p><p>Sample workflow_dispatch event and GHA is shown below. Here the workflow accepts “id” as input and also the “task” job simply prints the input “id” value.</p><p><strong><em>Sample-workflow-dispatch-action.yml</em></strong></p><pre>name: Sample workflow dispatch action<br><br>on:<br>  workflow_dispatch:<br>    inputs:<br>      id:<br>        description: &#39;Id as input&#39;<br>        required: true<br>        default: &#39;sample-id&#39;<br><br>jobs:<br>  task:<br>    runs-on: ubuntu-latest<br>    steps:<br>      - name: Print the id<br>        run: |<br>          echo &quot;Starting the task...&quot;<br>          echo &quot;The specified id is: ${{ inputs.id }}&quot;<br>          echo &quot;Task completed successfully.&quot;</pre><p>Now we will see how the workflow_dispatch GHA can be called from the downstream Github Actions as an API. In this upstream workflow, which gets triggered when Pull Request (PR) is opened, and a job is run to trigger the downstream target workflow.</p><pre>name: Run Upstream Action<br><br>on:<br>  pull_request:<br>    types: [opened]<br>    branches:<br>      - main<br><br>jobs:<br>  run_after_pr_open:<br>    runs-on: ubuntu<br>    steps:<br>      - name: Trigger Target Workflow<br>        env:<br>          PAT_TOKEN: ${{ secrets.PAT_TOKEN }}<br>          <br>        run: |<br>          curl -L \<br>            -X POST \<br>            -H &quot;Accept: application/vnd.github.v3+json&quot; \<br>            -H &quot;Authorization: Bearer $PAT_TOKEN&quot; \<br>            -H &quot;X-GitHub-Api-Version: 2022-11-28&quot; \<br>&quot;https://api.github.com/repos/test/workflow/actions/workflows/Sample-workflow-dispatch-action.yml/dispatches&quot; \<br>            -d &#39;{&quot;ref&quot;:&quot;test-branch&quot;, &quot;inputs&quot;:{&quot;id&quot;:&quot;test_id&quot;}}&#39;</pre><p>The api is very straightforward and lets break it down,</p><p><strong><em>API</em></strong>: https://api.github.com/repos/&lt;repo-name&gt;/workflow/actions/workflows/&lt;wokflow-file-name&gt;.yml/dispatches</p><p><strong><em>ref</em></strong>: Indicates the branch name where the workflow exists. For example, “test-branch”</p><p><strong><em>inputs</em></strong>: Indicates the input to be passed to the workflow. For example, “id” is an input property.</p><p>Also, the API needs Github Personal Access Token to trigger the workflow which is added as a repository secret.</p><p>That’s all I have! Help me improve by adding comments &amp; feedback.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=aaedef0514a6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Performance Test as a Service using Locust;]]></title>
            <link>https://nlokesh.medium.com/performance-test-as-a-service-using-locust-be9e1ad2a92b?source=rss-5ddc6f53c4db------2</link>
            <guid isPermaLink="false">https://medium.com/p/be9e1ad2a92b</guid>
            <category><![CDATA[performance-testing]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[locust]]></category>
            <category><![CDATA[performance]]></category>
            <category><![CDATA[testing]]></category>
            <dc:creator><![CDATA[Lokesh Nanda]]></dc:creator>
            <pubDate>Tue, 15 Jul 2025 08:12:45 GMT</pubDate>
            <atom:updated>2025-07-15T14:23:33.766Z</atom:updated>
            <content:encoded><![CDATA[<p>This article explores how to run performance tests for your services using Locust, a widely used and popular tool.</p><h3>Introduction to Locust</h3><p><a href="https://locust.io/">Locust</a> is an open-source tool for performance testing, with a commercial license available for those needing additional support and cloud-based testing capabilities.</p><p>A key advantage of Locust is that all tests are written in Python, making it highly developer-friendly. I’ve personally found Locust to meet all my specific needs, and its live test update feature is truly impressive.</p><h3><strong>Locust’s Strengths</strong></h3><p>The key Locust’s strengths are captured below,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/900/0*ZCBU4Yu6ghxBichi" /></figure><h3>Writing a Locust Test</h3><p>A basic Locust test, defined in a `User.py` file, looks like this:</p><p>Python Code:</p><pre>class User(HttpUser):<br><br>  @task<br>  def testResourceApis(self):<br>  self.client.get(&quot;/api/resource/resourceA&quot;)<br><br>  @task<br>  def testMetadataApis(self):<br>  self.client.get(&quot;/api/metadata&quot;)</pre><p>For a single user, this test will execute both `testResourceApis` and `testMetadataApis`, making API calls to “/api/resource/resourceA” and “/api/metadata” respectively.</p><p><strong>Customizing Test Lifecycles: `on_start` and `on_stop`</strong></p><p>Locust offers customization options for test initialization and cleanup using `on_start` and `on_stop` methods. These are useful for tasks like setting up proxy configurations before requests begin:</p><pre>class User(HttpUser):<br>  # … (other code)<br>  #...<br>  #...<br><br>  def on_start(self):<br>    print(f&quot;Starting API testing for the host: {self.host}&quot;)<br>    # Additional proxy settings if required<br><br>  def on_stop(self):<br>    print(f&quot;Stopping API testing for the host: {self.host}&quot;)</pre><p><strong>Configuring Locust with `locust.conf`</strong></p><p>Locust uses a configuration file (e.g., `locust.conf`) to define test run parameters. Here’s an example with basic descriptions:</p><pre># Main test file<br>locustfile = User.py<br><br># Set to true to disable the Web UI<br>headless = false<br><br># Total number of concurrent users<br>users = 500<br><br># Number of users to spawn per second<br>spawn-rate = 20<br><br># Total duration of the test run (e.g., 10 minutes)<br>run-time = 10m<br><br># Target host for the tests<br>host = https://api.service.com<br><br># Prefix for CSV statistics files<br>csv = api_load_test_report<br><br># Name for the HTML report file<br>html = api_load_test_report.html<br><br># Web UI host (if headless is false)<br>web-host = localhost<br><br># Web UI port (if headless is false)<br>web-port = 8443</pre><p>The `headless` property is particularly important for controlling the Locust UI when running tests as a service in a remote environment. It’s a key factor in leveraging Locust for “Performance Tests as a Service.”</p><h3>Performance Test as a Service</h3><p>Running performance test as a service provides significant benefits:</p><ol><li><strong>Isolated Environment:</strong> The performance test client operates within a dedicated, isolated environment.</li><li><strong>Scalability:</strong> You can easily scale the performance test client to meet varying demands.</li></ol><p>To run these tests as a service within a Docker container, the following `Dockerfile` can be used:</p><pre>FROM python:3.10-slim-bullseye<br><br>WORKDIR /app<br><br>COPY requirements.txt .<br><br>RUN pip install - no-cache-dir - upgrade pip &amp;&amp; \<br><br>pip install - no-cache-dir -r requirements.txt<br><br>COPY . .<br><br>EXPOSE 8443<br><br>CMD [&quot;locust&quot;, &quot; - config&quot;, &quot;locust.conf&quot;]</pre><p>The following design shows how the Performance Test as a Service fits into the overall scheme of things along with the actual service to be tested.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xRkVM2LozZVrXBcYF2CxeQ.png" /><figcaption>Design of how Performance Test as a Service fits in the overall scheme</figcaption></figure><h3><strong>Advanced Locust Configurations</strong></h3><p>The following are the advanced Locust configurations,</p><ol><li><strong>Scalability:</strong> Locust offers robust scalability, supporting master-worker architectures for distributed testing. While not personally utilized yet, detailed information is available in the <a href="https://docs.locust.io/en/stable/running-distributed.html">Locust documentation on distributed testing</a>.</li><li><strong>Custom Load Shapes:</strong> You can define custom load patterns by extending the `LoadTestShape` class, allowing for dynamic adjustments of spawn rates and user counts over time.</li><li><strong>Debug Mode:</strong> Tests can be run in a debug mode using the `run_single_user` method.</li><li><strong>Custom Event Hooks:</strong> Locust provides event hooks for implementing custom behaviors and integrations. More details can be found in the <a href="https://docs.locust.io/en/stable/extending-locust.html">extending Locust documentation</a>.</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=be9e1ad2a92b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ES Modules in NodeJs;]]></title>
            <link>https://nlokesh.medium.com/es-modules-in-nodejs-e6b8c28e2ba?source=rss-5ddc6f53c4db------2</link>
            <guid isPermaLink="false">https://medium.com/p/e6b8c28e2ba</guid>
            <category><![CDATA[esm]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[commonjs]]></category>
            <dc:creator><![CDATA[Lokesh Nanda]]></dc:creator>
            <pubDate>Sat, 09 Sep 2023 17:49:18 GMT</pubDate>
            <atom:updated>2023-11-02T00:48:09.397Z</atom:updated>
            <content:encoded><![CDATA[<p>In the following article, we will learn about ES modules, its predecessor CommonJs and advantages of ES modules(ESM is short form for ECMA Script Modules) in NodeJs backend applications.</p><h3>Introduction</h3><p>Modules represent the way the javascript files are organized and used in a Nodejs application. ES modules follow the ECMA script standard which was introduced in 2015. ES modules provide a standard and unified way to package and use javascript files in both client and server. The single unified way attracts a lot of attention among the developers, as there is one common way to use javascript in both the client-side browser scripts and in server-side NodeJs application.</p><h3>CommonJs</h3><p>Before proceeding further, lets learn a little bit about ESM’s predecessor, which is CommonJs.</p><p>Till NodeJs 13, CommonJs was the standard format used in NodeJs applications for organizing javascript files. There are couple of noteworthy things in CommonJs format which we ourselves used in building the NodeJs application,</p><ol><li>CommonJs is synchronous in a way that it loads the modules. Even though it can cause performance issues, synchronous loading adds more predictability.</li><li>require(‘path’) can be used anywhere in the code. Since CommonJs loads the modules only during runtime, we can add and load any module using require(..) in any part of the code. We found this particulary useful in loading a module based on a condition in our project.</li><li>All the older libraries uses CommonJs, so there is no compatibility issues.</li><li>No direct support for top-level await.</li></ol><h3>Newer ESM</h3><p>Given the background about CommonJs modules and its uses, there is a shift towards the ES Modules which is becoming the common standard for both Client and Server side javascript development.</p><p>Although NodeJs supports both CommonJs and ESM formats, there are a lot of advantages and newer features in ESM modules which makes it one of the most interesting and futuristic in my opinion.</p><p>Some of the advantages include,</p><ol><li>ES Modules are asynchronous.</li><li>Direct support for top-level-await.</li><li>Modules can be loaded directly from the internet using an url.</li><li>Extendable loaders</li><li>Common standard for both client and server NodeJs applications.</li></ol><p>We will go in depth into the above sections in a while.</p><h3>Asynchronous</h3><p>Asynchronous and dynamic nature of ES modules support loading of a huge number of modules and it is best suited for larger projects which have a lot of modules to load. Due to its async nature of loading the modules, it is not allowed to import modules anywhere in the code like in ‘require’ and all the imports are by default hoisted to the top of the code.</p><p>Eventhough, by default we can’t import a module anywhere in the code like require, ES Modules provides an alternative for this using dynamic imports function,</p><pre>const dynamicImport = await import(‘path’)</pre><h3>Top-level Await</h3><p>ES Modules supports top-level await and any other modules which import them have to wait for the top-level await to finish before starting the evaluation of their own code.</p><p>Top-level await is extremely useful, when there is a need to load the dependent resources in the code. For example,</p><pre>await bootstrapResources(..)</pre><blockquote>We usually use an IIFE to call a top-level await function in CommonJs</blockquote><p>If a top-level await never resolves, then the Node process will exit with an error code.</p><h3>Load modules using an url</h3><p>ES Modules allows loading a module using an url. Although this adds a lot of flexibility, dependending on an external url may cause stability and security issues while loading a module.</p><p>This is an experimental feature and it is not enabled by default.</p><h3>Extendable loaders</h3><p>ES Module resolution can be extended using the custom loaders. The custom loader provides a set of hooks which gets called in the list of available loaders chain. We can add multiple loaders in the chain and each of the loader will get called according to the opposite sequence of registration.<br>For example,</p><pre>node --experimental-loader loader1 --experimental-loader loader2</pre><p>In the above example, loader2 will get called first followed by loader1 and so on.</p><p>Here is the api for the custom loaders,</p><ol><li>initialize() — runs when a loader is initialized.</li><li>resolve() — used to determine where to load the file or a module from.</li><li>load() — loads the actual file or a module.</li></ol><p>This is an experimental feature and it is not enabled by default.</p><h3>Common standard for client and server applications</h3><p>Finally, the common standard for the client and server applications makes ES Modules more popular and it is widely being used in all the newer libraries and packages. This makes it one of the compelling reasons to migrate any of the older CommonJs based applications to use ES Modules.</p><p>Also, a library using CommonJs modules can’t use any packages which are using ES Module format, but an ES Module can use CommonJs modules as its dependencies. Since most of the newer versions of the packages are written in ESM, it makes sense to move any of the older libraries from CommonJs to ESM.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e6b8c28e2ba" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Type casting in Golang;]]></title>
            <link>https://nlokesh.medium.com/type-casting-in-golang-8105520a8cbb?source=rss-5ddc6f53c4db------2</link>
            <guid isPermaLink="false">https://medium.com/p/8105520a8cbb</guid>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[typecast]]></category>
            <dc:creator><![CDATA[Lokesh Nanda]]></dc:creator>
            <pubDate>Sat, 06 Aug 2022 07:03:55 GMT</pubDate>
            <atom:updated>2022-08-06T11:58:34.536Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>Type casting refers to changing the value of one data type to another.</blockquote><h3>Type casting for Primitives</h3><p>Primitive type casting is simple and easy when you follow the below pattern,</p><blockquote>TypeToCastTo(Value)</blockquote><p>For example, consider the below program where we cast an int type to float32 type,</p><pre>func TypeCast() {</pre><pre>  var intType int = 32</pre><pre>  var float32Type float32 = float32(intType)</pre><pre>  fmt.Println(float32Type)</pre><pre>}</pre><h3>Type casting for Objects</h3><p>Sometimes you may need to type cast an object when you get their value, say from a Map. The following scenario illustrates adding different data type values to a map and then retrieving it and typecasting to read the object values,</p><pre>type Sample struct {</pre><pre>  name string</pre><pre>}</pre><pre>func TypeCast() {</pre><pre>  var myMap = make(map[string]interface{})</pre><pre>  myMap[&quot;Key1&quot;] = &quot;Value1&quot;</pre><pre>  myMap[&quot;Key2&quot;] = &amp;Sample{</pre><pre>   name: &quot;Value2&quot;,</pre><pre>  }<br></pre><pre>  for k, _ := range myMap {</pre><pre>    if typeVal, ok := findType(myMap[k]); ok {</pre><pre>      fmt.Println(typeVal)</pre><pre>    }</pre><pre>  }</pre><pre>}</pre><pre>func findType(val interface{}) (typeVal string, ok bool) {</pre><pre>  switch val.(type) {</pre><pre>  case string:</pre><pre>    return &quot;String&quot;, true</pre><pre>  case *Sample:</pre><pre>    return &quot;Sample&quot;, true</pre><pre>  }</pre><pre>  return &quot;&quot;, false</pre><pre>}</pre><p>In the above code, I have a map of type map[stringinterface{}, which can store value of any type. I have stored a stringas well as Sample structtype in the map.</p><p>findType(val interface{}) (typeVal string, ok bool)method determines the type of the value stored in the map by using a simple switchstatement. Note that we can use the direct string type in the case for comparing the string data type, but for the struct * it is a pointer.</p><p>These typecasting techniques are very useful while writing code in golang. Hope they are helpful.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8105520a8cbb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Defer functions in Golang;]]></title>
            <link>https://nlokesh.medium.com/defer-functions-in-golang-9bff15fa7eb0?source=rss-5ddc6f53c4db------2</link>
            <guid isPermaLink="false">https://medium.com/p/9bff15fa7eb0</guid>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[defer]]></category>
            <dc:creator><![CDATA[Lokesh Nanda]]></dc:creator>
            <pubDate>Sun, 24 Jul 2022 14:29:03 GMT</pubDate>
            <atom:updated>2025-07-15T10:03:25.435Z</atom:updated>
            <content:encoded><![CDATA[<p>Let’s take a look at the definition of defer functions from the docs,</p><blockquote>“A “defer” statement invokes a function whose execution is deferred to the moment the surrounding function returns, either because the surrounding function executed a <a href="https://go.dev/ref/spec#Return_statements">return statement</a>, reached the end of its <a href="https://go.dev/ref/spec#Function_declarations">function body</a>, or because the corresponding goroutine is <a href="https://go.dev/ref/spec#Handling_panics">panicking</a>.”</blockquote><p>Basically, defer functions are,</p><ol><li>Executed before the return or the end of the function (or)</li><li>Executed when there is a panic thrown in the function.</li></ol><p>Some Defer function examples,</p><p><strong>Example 1:</strong></p><pre>func DeferTest() {</pre><pre> defer func() {</pre><pre>  fmt.Println(“In defer”)</pre><pre> }()</pre><pre> fmt.Println(“In function”)</pre><pre> fmt.Println(“After function”)</pre><pre>}</pre><p>Here, the defer function is executed before the end of the function. The above function prints,</p><p><em>In function</em></p><p><em>After function</em></p><p><em>In defer</em></p><p><strong>Example 2:</strong></p><pre>func MultiDeferTest() {</pre><pre> defer fmt.Println(“3”)</pre><pre> defer fmt.Println(“2”)</pre><pre> defer fmt.Println(“1”)</pre><pre>}</pre><p>If you watch closely, all the defer functions goes into stack so they are executed in the opposite order of their call. The above function prints,</p><p><em>1</em></p><p><em>2</em></p><p><em>3</em></p><h3>What can a defer function access in Golang?</h3><p>Now the question comes like, what can defer access access within its outer function in Golang and the answer is it can access all of its variables declared in the outer function scope and the compiler doesn’t throw an error.</p><p>Let’s try to access and modify a variable inside the defer function,</p><pre>func DeferAccess() string {</pre><pre> var test string = “Hello”</pre><pre> fmt.Println(test)</pre><pre> defer func() {</pre><pre>  test = “World”</pre><pre> }()</pre><pre>return test</pre><pre>}</pre><p>What do you think will be the return value of this function?</p><p>… and the answer is,</p><p><em>Hello</em></p><h3>Can defer re-assign an object property after it is set?</h3><p>Yes, this is possible with pointers. This concept can be used to recover from a panic and reset the object value to say a default value.</p><pre>type myStruct struct {</pre><pre> Value *valStruct</pre><pre>}</pre><pre>type valStruct struct {</pre><pre> Value int</pre><pre>}</pre><pre>func DeferAccessWithRecover() (retVal *myStruct) {</pre><pre> retVal = &amp;myStruct{Value: &amp;valStruct{Value: 100}}</pre><pre> defer func() {</pre><pre>  if r := recover(); r != nil {</pre><pre>   retVal.Value.Value = 1000</pre><pre>   fmt.Println(&quot;Recover&quot;, r)</pre><pre>  }</pre><pre> }()</pre><pre>panic(&quot;Error&quot;)</pre><pre>return retVal</pre><pre>}</pre><pre>func main() {</pre><pre> my := DeferAccessWithRecover()</pre><pre> fmt.Println(my.Value.Value)</pre><pre>}</pre><p>The above code will print,</p><p><em>Recover Error</em></p><p><em>1000</em></p><p>Hope the above examples are helpful in understanding of <em>defer functions.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9bff15fa7eb0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Pointers and Immutability in Golang;]]></title>
            <link>https://nlokesh.medium.com/gos-default-immutability-7e2e44742592?source=rss-5ddc6f53c4db------2</link>
            <guid isPermaLink="false">https://medium.com/p/7e2e44742592</guid>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[pointers]]></category>
            <dc:creator><![CDATA[Lokesh Nanda]]></dc:creator>
            <pubDate>Sun, 15 May 2022 13:14:30 GMT</pubDate>
            <atom:updated>2022-07-15T05:28:47.057Z</atom:updated>
            <content:encoded><![CDATA[<p>Google’s Golang has multiple in-built features for developing server side applications. One of the features that caught my eye is pointers and immutability of the Struct types.</p><h3>## Pass by Value</h3><p>In Golang, when you pass a variable to a function, it is passed by value by default. That is, a new temporary location will be allocated for the variables inside the function and the variable values are copied to the temporary location.</p><p>Sample immutable object code below,</p><pre>type ImmutableStruct struct {<br>   value int64<br>}</pre><pre>func NewImmutableObject() *ImmutableTest {</pre><pre>  return &amp;ImmutableTest{</pre><pre>    value: 10,</pre><pre>  }</pre><pre>}</pre><pre>func ModifyObject(obj ImmutableTest) {</pre><pre>  obj.value = 100</pre><pre>}</pre><p>Let’s see the main function below,</p><pre>func main() {</pre><pre>  immutableObject := NewImmutableObject()</pre><pre>  ModifyObject(immutableObject)<br>  fmt.Println(immutableObject.value) // Prints 10</pre><pre>}</pre><p>The above Println function will print the value as “10”, reason being all the function variables are passed by value, so there is a temporary object created inside the function which is assigned the value “100” and the outer “immutableObject” still has value “10”. Inorder to change the value of the same outer “immutableObject”, we should know a little bit about the pointers.</p><h3>## Basics of Pointers</h3><p>Going back to land of “C”, where I have learnt initially about pointers, and way it is used in Golang makes it one of the important features in Go.</p><ul><li>*- Is used as dereferencing operator and to get the value of a variable or an object at a particular address in memory.</li><li>&amp;- Is used to refer an address of a variable or an object.</li></ul><p>To pass a variable by reference, we need to use the pointer of the object when passed to a function as shown below,</p><pre>func ModifyObject(obj *ImmutableTest) {</pre><pre>  obj.value = 100</pre><pre>}</pre><p>Let’s see the same main function (which prints the modified result) below,</p><pre>func main() {</pre><pre>  immutableObject := NewImmutableObject()</pre><pre>  ModifyObject(immutableObject)<br>  fmt.Println(immutableObject.value) // Prints 100</pre><pre>}</pre><p>The above main will print the value as “100”, because this time “ModifyObject” function takes in a variable by its reference using pointers.</p><p>This functionality or the feature makes objects immutable by default if used in the correct sense.</p><p>Also, there are couple of other steps that we have to follow to make an Object completely immutable,</p><ol><li>Variables inside struct should be declared in lowercase to make it private by default.</li><li>All the variables should be accessible only using Getters.</li><li>Create a deep copy of arrays/ objects when returning the values from the public functions.</li><li>Return an interface containing only the functions instead of returning the struct where the variables are hidden.</li></ol><p>These are some of the high level things that I could think about. Happy coding;</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7e2e44742592" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Quick and Practical GraphQL;]]></title>
            <link>https://nlokesh.medium.com/a-quick-and-practical-graphql-ea17c23ca837?source=rss-5ddc6f53c4db------2</link>
            <guid isPermaLink="false">https://medium.com/p/ea17c23ca837</guid>
            <category><![CDATA[graphql-schema]]></category>
            <category><![CDATA[graphql-apollo-server]]></category>
            <category><![CDATA[graphql]]></category>
            <category><![CDATA[graphql-vs-rest]]></category>
            <dc:creator><![CDATA[Lokesh Nanda]]></dc:creator>
            <pubDate>Sat, 24 Jul 2021 14:04:22 GMT</pubDate>
            <atom:updated>2022-05-05T03:50:09.209Z</atom:updated>
            <content:encoded><![CDATA[<p>Today I will talk about how to implement and use GraphQL practically.</p><h4>Prereqs;</h4><p>This module needs a couple of prereqs,</p><ol><li>NodeJs</li><li>Javascript</li></ol><p>We will use “apollo-server” package which has the implementation of GraphQL specification.</p><h4>What is GraphQL?</h4><p>In the prereqs section, as I gave an hint, GraphQL is a specification and apollo-server is one of the implementations of the GraphQL specification.</p><p>GraphQL as I see consists of two parts,</p><ol><li>Client side GraphQL language used for querying.</li><li>Server side GraphQL runtime and the schema.</li></ol><p>GraphQL is the query language used for querying multiple resources as opposed to the REST API which pertains to a single resource.</p><p>In REST API,</p><ol><li>Clients have to make one API call per resource</li><li>Clients cannot pick and choose the fields</li></ol><p>This creates a problem especially in a low resource, low network environments and typically leads to slowness in the response and slowness in the UI.</p><p>GraphQL avoids these problems by using a query language where clients can choose what resources and fields they need in a single request.</p><h4>GraphQL Architecture</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/627/1*uZzIAWR46yupkbjoFooXzQ.png" /></figure><h4>A Sample implementation;</h4><p>Now we will implement a sample GraphQL runtime using apollo-server.</p><p><em>Schema:</em></p><pre>const {gql} = require(‘apollo-server’);</pre><pre>const schema = gql`</pre><pre>type Customer {</pre><pre>id: ID!,</pre><pre>name: String,</pre><pre>age: Int</pre><pre>}</pre><pre>type Query {</pre><pre>getAllCustomers: [customer]</pre><pre>}`;</pre><p>In schema, we define types for fields and queries and will show how to resolve these fields and queries in the following section.</p><p><em>Schema Resolvers:</em></p><pre>const resolvers = {</pre><pre>  Query: {</pre><pre>    getAllCustomers: (parent, args, context, info) =&gt; {</pre><pre>    // use the context to set the dataSources for fetching the customer data, for simplicity I will return a list of customer data</pre><pre>    return [</pre><pre>      { &quot;id&quot;: &quot;1&quot;, &quot;name&quot;: &quot;Rahul&quot;, &quot;age&quot;: 40},</pre><pre>      {&quot;id&quot;: &quot;2&quot;, &quot;name&quot;: &quot;Ranjith&quot;, &quot;age&quot;: 38}</pre><pre>    ];</pre><pre>    }</pre><pre>  }</pre><pre>}</pre><p>Resolvers are mechanism for fetching the data related to a field or a query in schema. In the above same, we have defined a resolver for the Query type in the schema.</p><p><em>Setup Apollo GraphQL server:</em></p><pre>const {ApolloServer} = require(‘apollo-server’);</pre><pre>const server = new ApolloServer({</pre><pre>schema,</pre><pre>resolvers,</pre><pre>dataSources</pre><pre>});</pre><pre>server.listen({port: process.env.port || 4000});</pre><p>Apollo server implementation take in the schema, resolvers and optional datasources that you want to use in the resolver function.</p><p>This is one of the sample implementations that I want to share to show how easy it is to use GraphQL, but its capabilities are enormous. Typically it is run as a wrapper in front of multiple data sources or REST APIs, where the resolver function queries these multiple sources and returns a single response to the client.</p><p>The advantages are,</p><ol><li>Clients reduce the number of requests to the server.</li><li>Clients get what they want in a single response.</li></ol><p>Finally I want to show how to query a GraphQLAPI using Postman,</p><p>All GraphQL APIs are POST request by default, we can make a POST request with the corresponding request body as mentioned below,</p><p>POST: <a href="http://localhost:4000/">http://localhost:4000</a></p><p>JSON Body:</p><p>{“query”: “{ getAllCustomers(id: \”1\”){ name age } }”}</p><p>Thats all for now;</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ea17c23ca837" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mutation Observers;]]></title>
            <link>https://nlokesh.medium.com/mutation-observers-459c551c3a28?source=rss-5ddc6f53c4db------2</link>
            <guid isPermaLink="false">https://medium.com/p/459c551c3a28</guid>
            <category><![CDATA[mutation]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[html]]></category>
            <dc:creator><![CDATA[Lokesh Nanda]]></dc:creator>
            <pubDate>Fri, 14 May 2021 09:10:04 GMT</pubDate>
            <atom:updated>2021-07-24T14:02:01.393Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Introduction</strong></p><p>Mutation Observers observes any DOM changes and delivers the changes as a list of mutation records to the observers. Mutation Observers have a very simple api,</p><p>// Creation of a mutation observer with a callback function containing the mutations.</p><p>const mutationObserver = new MutationObserver((mutationRecords) =&gt; {</p><p>….</p><p>});</p><p>mutationRecords — represents an array of mutations grouped together containing the type of the mutation, node lists which are added or removed and the target node which is mutated.</p><p>// Register the observer to a DomNode with a set of options</p><p>mutationObserver.observe(domNode, { options });</p><p>Options are,</p><ol><li>attributes : boolean — To observe changes in attributes.</li><li>childList : boolean — To observe any addition or deletion of child nodes.</li><li>subTree: boolean — To observe the subtree of the domNode.</li><li>characterData: boolean — To observe changes to the character data.</li></ol><p>// To de-register the observer</p><p>mutationObserver.disconnect()</p><p><strong>History</strong></p><p>Mutation Observers are preceded by Mutation Events. I won’t go into details on how to define a mutation event as it is deprecated now, but will cover on why it is deprecated.</p><p>Mutation Events are deprecated for the following reasons,</p><ol><li>Mutation Events are not cancelable.</li><li>Mutation Events don’t group the mutations, instead send them as individual mutation events.</li><li>Mutation Events are inconsistent. Mutation events get fired even before the DOM has been changed.</li><li>Mutation Events seriously impact the performance of any DOM changes. Primarily it takes time to fire every event individually and also creation of the event object requires serializing some of the dom nodes which is also time consuming. You could imagine a scenario where there are 100’s of new node additions and firing each of these events individually is time consuming.</li></ol><p>Considering all the disadvantages and problems associated with Mutation Events, W3C standards came forward with a new Mutation Observer for observing mutations in DOM. Mutation Observer overcomes the disadvantages of Mutation Events and also is very efficient when it comes to performance.</p><p><strong>Advantages</strong></p><ol><li>Mutation Observer events are grouped and fired together.</li><li>Mutation Observer events are fired only after the changes are rendered in the DOM.</li><li>Mutation Observers are consistent and stable.</li></ol><p><strong>Uses</strong></p><p>Now talking about its actual use case, as it is not common in day-to-day scenario where we want to listen for mutations in DOM. One place where I found it useful is in Chrome extensions, where if you want to listen for DOM changes of a particular node in a page and say want to send notifications dependending on when a node is added or removed. This scenario can be easily achieved with Mutation Observers. Mutation Observers are also typically used in frameworks where we want to take actions based on DOM changes.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=459c551c3a28" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>