<?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 Kiran Adhikari on Medium]]></title>
        <description><![CDATA[Stories by Kiran Adhikari on Medium]]></description>
        <link>https://medium.com/@kiruu1238?source=rss-b0ae211f548d------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*E8362QV-lqqfko0oHGe38A.jpeg</url>
            <title>Stories by Kiran Adhikari on Medium</title>
            <link>https://medium.com/@kiruu1238?source=rss-b0ae211f548d------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 20 Nov 2026 11:07:39 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@kiruu1238/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[I Built SAML SSO the IAM Way: Okta, Keycloak, and Real-World Application Flow]]></title>
            <link>https://medium.com/@kiruu1238/i-built-saml-sso-the-iam-way-okta-keycloak-and-real-world-application-flow-8c2feba86812?source=rss-b0ae211f548d------2</link>
            <guid isPermaLink="false">https://medium.com/p/8c2feba86812</guid>
            <category><![CDATA[ami]]></category>
            <category><![CDATA[keycloak]]></category>
            <category><![CDATA[okta]]></category>
            <category><![CDATA[aml]]></category>
            <category><![CDATA[sso]]></category>
            <dc:creator><![CDATA[Kiran Adhikari]]></dc:creator>
            <pubDate>Sat, 11 Apr 2026 03:40:49 GMT</pubDate>
            <atom:updated>2026-04-11T04:06:43.332Z</atom:updated>
            <content:encoded><![CDATA[<p>Suppose you are an employee working at a big corporate company, and you are onboarded on day one. To do your job, you need access to different applications such as GitHub to write code, Jira to check assigned tickets, ServiceNow to raise service requests, Figma for sketches or diagrams, Slack for messaging, email, and other internal systems for payments or business operations. Without SSO, SCIM, and IAM, you would have to manually go to different websites, fill out forms, and create separate accounts for each service. You would also need to remember a different username and password for each of those accounts.</p><p>To reduce that pain, organizations use SCIM and SSO together. We will discuss SCIM in more detail in a different blog post. At a high level, when you join a company, your record is first created in the HR system. Then, through automated provisioning using SCIM and joiner-mover-leaver lifecycle management, your accounts are provisioned into the required downstream applications. This is often called birthright access, meaning you automatically receive access based on your department and job role. For example, if you are a developer, automated systems may provision your accounts to GitHub, Jira, Slack, email, Figma, and other tools you need from day one.</p><p>With those applications integrated into an application catalog or end-user dashboard in Okta or Entra, you can simply click the application from the portal and sign in using a single set of credentials. This improves productivity, but it also improves security. Each application may enforce security differently, and not all of them support strong controls such as MFA, adaptive risk checks, Conditional Access, or risk-based policies. By centralizing access through identity and access management platforms such as Okta or Entra, organizations can apply consistent policies across applications. As a result, access to company resources is not only easier for the user but also more controlled and aligned with organizational security policies.</p><p>It solves trust delegation, where applications no longer need to authenticate users directly or manage passwords themselves. Instead, they delegate authentication to an identity provider they trust and rely on signed assertions or tokens to verify the user’s identity. In addition, SSO enables session propagation across applications. Because browsers enforce the same-origin policy, applications cannot simply share cookies or local sessions with one another. To overcome this, federated protocols such as SAML and OAuth 2.0/OIDC use tokens or assertions to carry authentication context between trusted systems. As a result, users can move across applications without being repeatedly prompted to sign in.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ax5x4zyuP0cQ66_edm5IxA.png" /><figcaption>SSO Trust Boundaries</figcaption></figure><p>In this tutorial, we are going to explain <strong>SAML (Security Assertion Markup Language)</strong> as the protocol of choice for demonstrating single sign-on. In SSO, there are two common flows: Identity Provider-initiated(IdP) SSO and Service Provider-initiated(SP) SSO.</p><p>Let’s explain them with an example. If a user browses the application catalog in Okta and clicks an application to sign in, that is Identity Provider-initiated SSO, because the login flow starts from the identity provider side.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*t5DOFDcQaKd3HjFsKC87Jg.png" /><figcaption>IdP initiated flow</figcaption></figure><p>On the other hand, if the user first goes to an application such as GitHub and clicks sign in, the application redirects the user to the identity provider for authentication. That is called Service Provider-initiated SSO. Some applications support both IdP-initiated and SP-initiated SSO, while others support only one of the two. In this tutorial, we will demonstrate both Identity Provider-initiated and Service Provider-initiated SSO using the SAML protocol.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Os02cx-RuiVOSesttkKiqA.png" /><figcaption>sP initiated flow</figcaption></figure><p>Before going deeper into SAML, I would like to explain some common terms that will help us understand it better.</p><ul><li><strong>An Identity Provider (IdP)</strong> is the system that authenticates users and acts as the central identity system, such as Entra or Okta.</li><li><strong>A Service Provider (SP)</strong> is the application the user wants to access. For example, if I want to sign in to GitHub, then GitHub is the service provider in that case.</li><li><strong>A SAML Request</strong>, also called a SAML Authentication Request, is sent from the service provider to the identity provider. It is basically the service provider saying, “A user is trying to access my application, please authenticate this user on my behalf.” After the user is authenticated, the identity provider sends a SAML Response back to the service provider.</li><li><strong>SAML response</strong> contains a <strong>SAML Assertion</strong>, which is a statement about the authenticated user and may include identity attributes, authentication details, and other claims.SAML assertions are usually signed using XML Digital Signature (XML DSig).</li><li><strong>XML DSig,</strong> signature is important because the service provider must be able to verify that the assertion really came from the trusted identity provider and was not modified in transit. If assertions are not properly signed and validated, an attacker may be able to abuse the flow through replay attacks, assertion tampering, or other trust-related weaknesses.</li><li><strong>Assertion Consumer Service (ACS)</strong>, which is the endpoint on the service provider that receives the SAML response and validates the assertion.</li><li>There are also supporting parameters, such as <strong>RelayState</strong>, which help preserve application state and return the user to the correct location after authentication.</li><li><strong>SAML trust</strong> is established through exchanged metadata, certificates, and entity IDs, which together create the trust relationship between the service provider and the identity provider. This trust allows the service provider to verify that SAML responses and assertions are coming from a legitimate identity provider.</li><li><strong>Metadata</strong> helps automate or simplify the configuration between the service provider and identity provider. By using metadata, we usually do not need to manually copy and paste settings such as certificates, ACS URLs, entity IDs, and other SAML endpoints one by one.</li></ul><p>Let’s understand the SAML,</p><pre>&lt;saml2p:Response xmlns:saml2p=&quot;urn:oasis:names:tc:SAML:2.0:protocol&quot;<br>                 Destination=&quot;http://neobank.local:3000/saml/login&quot;<br>                 ID=&quot;id73312612258629479471008239055&quot;<br>                 IssueInstant=&quot;2026-04-11T01:53:23.028Z&quot;<br>                 Version=&quot;2.0&quot;<br>                 &gt;</pre><p>In the SAML2 Response, we have a few key fields that matter for validation and processing. The <strong>Destination</strong> is the endpoint on the Service Provider side where the response is supposed to be posted, usually the <strong>ACS URL</strong> where the SAML login flow continues. The <strong>ID</strong> uniquely identifies this response. The <strong>IssueInstant</strong> is the timestamp showing when the response was generated by the Identity Provider. Together, these fields help the Service Provider confirm that the response is valid, fresh, and intended for the correct application.</p><pre> &lt;saml2:Issuer xmlns:saml2=&quot;urn:oasis:names:tc:SAML:2.0:assertion&quot;<br>                  Format=&quot;urn:oasis:names:tc:SAML:2.0:nameid-format:entity&quot;<br>                  &gt;http://www.okta.com/{$okta_tenant_id}&lt;/saml2:Issuer&gt;</pre><p>In the <strong>SAML Response</strong>, the <strong>Issuer</strong> identifies the <strong>Identity Provider (IdP)</strong> that generated and signed the response. It is typically a unique <strong>entity ID</strong> that represents the IdP in the trust relationship. The Service Provider uses this value to verify that the response is coming from a <strong>trusted IdP</strong>, as configured during metadata exchange.</p><p>The Issuer corresponds to the Okta tenant’s entity ID, and it must match exactly with what the Service Provider has configured. If it doesn’t match, the response should be rejected.</p><pre> &lt;saml2:Assertion xmlns:saml2=&quot;urn:oasis:names:tc:SAML:2.0:assertion&quot;<br>                     ID=&quot;id-2456336233478875441921127974&quot;<br>                     IssueInstant=&quot;2026-04-11T01:53:23.028Z&quot;<br>                     Version=&quot;2.0&quot;<br>                     &gt;<br>        &lt;saml2:Issuer xmlns:saml2=&quot;urn:oasis:names:tc:SAML:2.0:assertion&quot;<br>                      Format=&quot;urn:oasis:names:tc:SAML:2.0:nameid-format:entity&quot;<br>                      &gt;http://www.okta.com/{$okta_tenant_id}&lt;/saml2:Issuer&gt;<br>        <br>        &lt;saml2:Subject xmlns:saml2=&quot;urn:oasis:names:tc:SAML:2.0:assertion&quot;&gt;<br>            &lt;saml2:NameID Format=&quot;urn:oasis:names:tc:SAML:1.1:nameid-format:unspecified&quot;&gt;xyz@gmail.com&lt;/saml2:NameID&gt;<br>            &lt;saml2:SubjectConfirmation Method=&quot;urn:oasis:names:tc:SAML:2.0:cm:bearer&quot;&gt;<br>                &lt;saml2:SubjectConfirmationData NotOnOrAfter=&quot;2026-04-11T01:58:23.028Z&quot;<br>                                               Recipient=&quot;http://neobank.local:3000/saml/login&quot;<br>                                               /&gt;<br>            &lt;/saml2:SubjectConfirmation&gt;<br>        &lt;/saml2:Subject&gt;<br>        &lt;saml2:Conditions xmlns:saml2=&quot;urn:oasis:names:tc:SAML:2.0:assertion&quot;<br>                          NotBefore=&quot;2026-04-11T01:48:23.028Z&quot;<br>                          NotOnOrAfter=&quot;2026-04-11T01:58:23.028Z&quot;<br>                          &gt;<br>            &lt;saml2:AudienceRestriction&gt;<br>                &lt;saml2:Audience&gt;http://neobank.local:3000&lt;/saml2:Audience&gt;<br>            &lt;/saml2:AudienceRestriction&gt;<br>        &lt;/saml2:Conditions&gt;<br>        &lt;saml2:AuthnStatement xmlns:saml2=&quot;urn:oasis:names:tc:SAML:2.0:assertion&quot;<br>                              AuthnInstant=&quot;2026-04-11T01:52:46.881Z&quot;<br>                              SessionIndex=&quot;id1775872402889.152017821&quot;<br>                              &gt;<br>            &lt;saml2:AuthnContext&gt;<br>                &lt;saml2:AuthnContextClassRef&gt;urn:oasis:names:tc:SAML:2.0:ac:classes:PasswordProtectedTransport&lt;/saml2:AuthnContextClassRef&gt;<br>            &lt;/saml2:AuthnContext&gt;<br>        &lt;/saml2:AuthnStatement&gt;<br>    &lt;/saml2:Assertion&gt;</pre><p>A <strong>SAML Assertion</strong> is the signed security statement inside the SAML Response that tells the Service Provider who the user is, when they authenticated, and under what conditions the assertion is valid. It contains its own <strong>ID</strong>, <strong>IssueInstant</strong>, and <strong>Issuer</strong>, along with a <strong>digital signature</strong> that must be verified using the IdP’s certificate.</p><p>The <strong>Subject</strong> section identifies the user, where the <strong>NameID</strong> is often mapped to an email or username, and <strong>SubjectConfirmation</strong> ensures the assertion is being presented to the correct ACS endpoint within a limited time window.</p><p>The <strong>Conditions</strong> section enforces validity through time bounds and <strong>AudienceRestriction</strong>, which prevents the assertion from being accepted by the wrong application. Finally, the <strong>AuthnStatement</strong> records the actual login event, including when authentication occurred, the IdP session identifier, and the authentication method used.</p><p>In an SP-initiated SSO flow, the application first creates a SAML AuthnRequest. That request carries the version, request ID, destination, ACS URL, and the Issuer of the Service Provider. It may also define the expected NameID format, which in my case is email, matching the identifier configured in Okta.</p><pre>&lt;samlp:AuthnRequest xmlns:samlp=&quot;urn:oasis:names:tc:SAML:2.0:protocol&quot;<br>                    ID=&quot;_dcfe36db956d95b09ef9d5efca0f61049fd46371&quot;<br>                    Version=&quot;2.0&quot;<br>                    IssueInstant=&quot;2026-04-11T03:20:52.958Z&quot;<br>                    ProtocolBinding=&quot;urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST&quot;<br>                    Destination=&quot;https://okta.com/app/org_neobank_1/tenantId/sso/saml&quot;<br>                    AssertionConsumerServiceURL=&quot;http://neobank.local:3000/saml/acs&quot;<br>                    &gt;<br>    &lt;saml:Issuer xmlns:saml=&quot;urn:oasis:names:tc:SAML:2.0:assertion&quot;&gt;http://192.168.4.24:3000&lt;/saml:Issuer&gt;<br>    &lt;samlp:NameIDPolicy xmlns:samlp=&quot;urn:oasis:names:tc:SAML:2.0:protocol&quot;<br>                        AllowCreate=&quot;true&quot;<br>                        Format=&quot;urn:oasis:names:tc:SAML:1.1:nameid-format:emailAddress&quot;<br>                        /&gt;<br>&lt;/samlp:AuthnRequest&gt;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tnqOVXz0WU4uRYRrBtvRRA.png" /><figcaption>high level diagram</figcaption></figure><p><strong>Actors</strong></p><ol><li><strong>User:</strong> the person trying to access the Neobank application.</li><li><strong>Okta: </strong>acts as the external <strong>Identity Provider (IdP)</strong> where the user is authenticated.</li><li><strong>Keycloak: </strong>acts as the internal <strong>broker / federation layer</strong> for the Neobank application. It sits between the application and Okta and helps connect external identity to the internal application flow.</li><li><strong>Neobank Application: </strong>acts as the <strong>Service Provider (SP)</strong> that consumes the SAML assertion and grants access to the user.</li><li><strong>Application-side SAML validation layer</strong> : implemented using <strong>Passport</strong> and <strong>passport-saml</strong>, which validates the SAML response, extracts the user identity, and maps that identity into the application.</li></ol><p><strong>User Flow</strong></p><ol><li>The user launches the <strong>Neobank application</strong> from the <strong>Okta application catalog</strong>.</li><li>The Neobank application redirects the authentication flow to <strong>Keycloak</strong>.</li><li>Keycloak then redirects the user to <strong>Okta</strong> for authentication.</li><li>Okta authenticates the user and returns a <strong>SAML assertion</strong> for the login flow.</li><li>The <strong>Neobank application</strong> receives the SAML response and performs SAML validation on the application side using Passport and <strong>passport-saml</strong>.</li><li>After successful validation, the application maps the incoming identity to the appropriate internal user/session context.</li><li>Keycloak participates as the federation or brokering layer, and the user is ultimately granted access to the Neobank application.</li></ol><p>Now that we’ve covered enough theory and protocol-level details, let’s shift focus to the application side.</p><p>In this section, I’ll walk through how everything is actually configured in the real world, from setting up SAML in the application to wiring it with the IdP.</p><p>This is the third part of my series built around Keycloak. I’ll include links to the first two parts, since this one builds directly on them. If you have not read those yet, they will give you the right context for this post.</p><p><a href="https://medium.com/@kiruu1238/oauth-2-0-oidc-explained-like-youre-building-it-keycloak-consent-demo-4c963a38199d">https://medium.com/@kiruu1238/oauth-2-0-oidc-explained-like-youre-building-it-keycloak-consent-demo-4c963a38199d</a></p><p><a href="https://medium.com/@kiruu1238/i-built-rbac-the-iam-way-composite-roles-uma-enforcement-with-keycloak-a21f02afa7dc">https://medium.com/@kiruu1238/i-built-rbac-the-iam-way-composite-roles-uma-enforcement-with-keycloak-a21f02afa7dc</a></p><p>Following least privilege and RBAC, I introduced an Administrator role for users who need elevated access to manage SSO configuration and the broader admin dashboard.</p><p>In Keycloak, roles can be composed of other roles or permissions, which makes them useful for modeling higher-level job functions. For this reason, I created an Administrator composite role and mapped permissions such as admin:dashboard, admin:developer:console, and admin:sso:samlinto it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ztFavAL8n9J042UXDcRPLA.png" /><figcaption>role composition</figcaption></figure><p>Once the roles were in place, I built an administrator dashboard to configure SAML SSO dynamically. The dashboard allows an admin to enter the <br>1. <strong>IdP Login URL:</strong> It is the endpoint where users are redirected for authentication.<br>2. <strong>Service Provider Entity ID: </strong>It<strong> </strong>uniquely identifies the application in the trust relationship<br> 3. <strong>Signing certificate: </strong>It is used to verify the integrity and authenticity of the SAML response.</p><p>This is the trust material the application needs to validate that the response truly came from the expected Identity Provider.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lnIjr7qI6ZLpu93MOEb63w.png" /><figcaption>saml configuration screen</figcaption></figure><p>Beyond configuration, the application exposes /saml/loginto initiate SSO and /saml/acsto handle the SAML Response. The ACS endpoint uses a SAML strategy to validate the response by checking the issuer, verifying the signature with the IdP certificate, and ensuring the response integrity before authenticating the user.</p><p>To create a new SAML application in Okta, first go to Applications and click Create App Integration, then choose SAML 2.0 as the sign-in method.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Al6BbcxFst7Ccyd-mkZ3zw.png" /></figure><p>In the SAML settings, set the Sign-on URL to your application endpoint, which in my case is the local /saml/login route, and set the SP Entity ID to the identifier of your Neobank application. For the application username, choose email address if your app uses email as the primary user identifier.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3_ba4KIOc7_py1BoCqYi8w.png" /></figure><p>In my setup, I created the same user email in both Okta and the Neobank application so the identity could be mapped correctly after authentication. The exact username format can differ based on the application design, but if your app already treats email as the unique identity, using email here keeps the integration simple and consistent.</p><p>To support post-login authorization, I created a new Keycloak client called User Lookup. This client uses a service account with permissions like view-users, view-clients, and query-users, so the application can call Keycloak during the SAML flow and verify whether the incoming user exists. After that lookup, the application fetches the user’s roles and uses them to decide where the user should land. That way, authentication comes from SSO, but authorization and role-based routing still stay under application control.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*i_9tppGSCuornSFWtN3qgA.png" /><figcaption>service account</figcaption></figure><p>Everything is configured — now it’s time to test.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*20gXgVj6q-bOF7vdN-NyPw.gif" /><figcaption>IdP initiated SSO</figcaption></figure><p>Now let’s flip the flow: SP-initiated SSO.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*8rjEvQkyom4QzFpWpvmdvA.gif" /><figcaption>sP initiated</figcaption></figure><p>The full code for this Neobank SAML setup is available on GitHub.</p><p><a href="https://github.com/ErKiran/keycloak_iam_learning/tree/saml-sso">GitHub - ErKiran/keycloak_iam_learning at saml-sso</a></p><p>Next, I’ll cover a full JML lifecycle with SCIM provisioning, an HR system as the source of truth, and SailPoint + Okta for governance and IAM.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8c2feba86812" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[API Authentication Security: Attack Vectors and Defenses in IAM]]></title>
            <link>https://medium.com/@kiruu1238/api-authentication-security-attack-vectors-and-defenses-in-iam-09131b552747?source=rss-b0ae211f548d------2</link>
            <guid isPermaLink="false">https://medium.com/p/09131b552747</guid>
            <category><![CDATA[authentication]]></category>
            <category><![CDATA[api]]></category>
            <category><![CDATA[ami]]></category>
            <category><![CDATA[api-security]]></category>
            <dc:creator><![CDATA[Kiran Adhikari]]></dc:creator>
            <pubDate>Wed, 25 Mar 2026 22:44:22 GMT</pubDate>
            <atom:updated>2026-03-25T22:44:22.604Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DfyhPMs60LFFCFC1aPA-_A.png" /></figure><p>API authentication security is closely tied to IAM because authentication is the first control that verifies who or what is trying to access an API. IAM provides the foundation for identities, credentials, tokens, session controls, MFA, and authorization decisions used by APIs. When these controls are weak or misconfigured, APIs become a direct attack surface for account takeover, token abuse, and unauthorized access. Understanding API authentication attacks helps connect IAM theory to real-world defensive design.​</p><p><strong>Password Fuzzing: </strong>Sending various passwords against a login endpoint to learn the weak password policy, and perform user enumeration via status code, response time, and error messages for valid and invalid users.</p><p>Password fuzzing and side-channel attacks can be minimized by providing a uniform response and error message regardless of whether the user exists in the system. While some side-channel attacks, such as response time, can be tricky, they can be made statistically indistinguishable by performing the same set of actions, such as user lookup in the DB and hash comparison.​</p><p><strong>Brute Force Attack: </strong>Using a wide range of passwords against an identity to break into the system. API endpoints are exposed through public docs, developer tools on a website, or reverse-engineering of mobile apps. Classic brute force, i.e., trying different passwords against an account, can be blocked by implementing rate limiting, account lockout, CAPTCHA, step-up challenges, or MFA for risky sign-ins. Password spraying can be combined with password fuzzing. A list of valid users can be enumerated based on response time and error codes, and a list of possible passwords can be applied across those accounts, consciously avoiding triggering rate limits or account lockouts.</p><p>Such attacks can evade account lockout and rate limiting, but they can be mitigated when combined with anomaly detection and signals such as <strong>device fingerprinting</strong> and <strong>time correlation</strong>.​</p><p><strong>Token Tampering:</strong> Modifying a token, such as a JWT, to alter claims like role, user ID, or expiry attributes. This attack abuses weak signature validation.<br>It can be prevented by using a strong signing algorithm and validating the token signature before accepting it, following continuous evaluation under the zero-trust principle.​</p><p><strong>MFA Bypass:</strong> Attackers exploit weak MFA flows or fallback mechanisms, such as security questions, which can be OSINTed. If the MFA methods used aren’t phishing-resistant, they can be exploited.​</p><p><strong>Password Reset/Account Takeover Attack:</strong> Password reset attacks can occur if the password reset tokens are weak. Man-in-the-Middle attacks or network sniffing can expose password reset links to an attacker’s possession. Weak security questions, such as <strong>“something you know”</strong> MFA, can be OSINTed.​</p><p><strong>Session Invalidation Failure:</strong> This occurs when an expired token is still able to access resources from the server. This happens when the expiry time isn’t respected and enforced, which increases the risk of token replay attacks.​</p><p><strong>Insecure Token Storage:</strong> Access tokens stored in browser storage (localStorage, sessionStorage) or device files can be stolen. Unencrypted tokens stored in the database, or tokens passed in URLs, can be retrieved from browser history.</p><p>To prevent such flaws, tokens can be stored as HTTP-only cookies in the browser. Using short-lived access tokens and storing refresh tokens in the database as salted hashes can improve security. Forcing storage to be cleared on logout can help prevent insecure token storage.​</p><p><strong>API Key Misuse: </strong>API keys are often checked into source code, which creates an attack surface. Millions of bots scan code repositories hunting for exposed API keys. API keys can also leak through secrets, logs, and CI/CD pipelines.</p><p>To prevent the API Key leakage, strict code review and pre-commit hooks can be implemented to detect such leakage.​</p><p><strong>Oauth/OIDC misconfiguration:</strong> If the redirection URL isn’t properly validated, an attacker can exploit it through an open redirector or register a malicious URL. If using the implicit flow, the authorization code isn’t in the scope, which exposes the access token in the redirect URI.</p><p>For the SPA and mobile app, this can be fixed by using PCKE, and for the backend, using an authorization code flow.​</p><p><strong>Consent or Scope Abuse:</strong> Scope abuse occurs when an app requests excessive consent beyond what is needed. Sometimes a malicious app misuses granted scopes to access unauthorized data.<br>This can be mitigated by educating developers and end users to understand the scopes being requested and to consent thoughtfully.</p><p>​</p><p>​</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=09131b552747" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[I Built RBAC the “IAM Way”: Composite Roles + UMA Enforcement with Keycloak]]></title>
            <link>https://medium.com/@kiruu1238/i-built-rbac-the-iam-way-composite-roles-uma-enforcement-with-keycloak-a21f02afa7dc?source=rss-b0ae211f548d------2</link>
            <guid isPermaLink="false">https://medium.com/p/a21f02afa7dc</guid>
            <category><![CDATA[ami]]></category>
            <category><![CDATA[rbac]]></category>
            <category><![CDATA[oauth2]]></category>
            <category><![CDATA[keycloak]]></category>
            <dc:creator><![CDATA[Kiran Adhikari]]></dc:creator>
            <pubDate>Thu, 19 Feb 2026 00:00:45 GMT</pubDate>
            <atom:updated>2026-02-19T00:00:45.824Z</atom:updated>
            <content:encoded><![CDATA[<p>In a Neobank, users have different roles and access rights. A customer should be able to transfer money; a teller should be able to view customer balances — but <strong>never</strong> transfer on a customer’s behalf.</p><p>Most modern web apps implement some form of RBAC. Sometimes that means a completely separate portal per role; other times it’s a single portal with different dashboards/views depending on who you are.</p><p>For our NeoBank demo, we’ll keep it simple:</p><p><strong>Customer</strong></p><ul><li>Read your <strong>own</strong> balance</li><li>Transfer money</li></ul><p><strong>Teller</strong></p><ul><li>View customer list</li><li>View customer balances</li><li><strong>No</strong> money transfer 🛡️</li></ul><h3>Authentication (AuthN) vs Authorization (AuthZ)</h3><ul><li><strong>Authentication</strong> answers: <em>“Who are you?”</em></li><li><strong>Authorization</strong> answers: <em>“What are you allowed to do?”</em></li></ul><p>From Part 1:</p><ul><li><strong>OIDC ⇒ Authentication</strong> (who the user is, session/identity)</li><li><strong>OAuth 2.0 ⇒ Authorization</strong> (delegated access, access tokens)</li></ul><p>In <a href="https://medium.com/@kiruu1238/oauth-2-0-oidc-explained-like-youre-building-it-keycloak-consent-demo-4c963a38199d">Part 1</a>,</p><p><a href="https://medium.com/@kiruu1238/oauth-2-0-oidc-explained-like-youre-building-it-keycloak-consent-demo-4c963a38199d">https://medium.com/@kiruu1238/oauth-2-0-oidc-explained-like-youre-building-it-keycloak-consent-demo-4c963a38199d</a></p><p>we implemented the login-and-token flow (AuthN + delegated AuthZ). In this part, we’ll go deeper into <strong>authorization</strong> and focus on the most common access-control model you’ll see in real systems: <strong>RBAC</strong>.</p><p>We got the tokens. Now the real question is:</p><blockquote><em>What do we do with them so the bank doesn’t get robbed?</em></blockquote><h3>RBAC: Role-Based Access Control</h3><p><strong>RBAC</strong> authorizes access to systems, applications, and data based on a user’s predefined role.</p><p>A solid high-level explanation is here:<br><a href="https://www.ibm.com/think/topics/rbac">https://www.ibm.com/think/topics/rbac</a></p><p>In practice, RBAC is simple — but people mess it up:</p><p><strong>Users → Roles</strong><br><strong>Roles → Permissions</strong></p><p>And the critical rule:</p><blockquote><em>The </em><strong><em>API must check permissions before executing the action</em></strong><em>.</em></blockquote><p>Tokens don’t enforce themselves. A token is just a signed statement carrying claims (identity + roles/permissions). If your backend doesn’t enforce those claims, your “RBAC” is basically a UI feature.</p><h3>Why is the backend the security boundary</h3><p>A common mistake: implementing “RBAC” only in the UI.</p><p>For example, you can hide the <strong>Transfer</strong> button for a teller. That might look secure in a demo — but it’s not security. Browser code is transparent and easy to manipulate.</p><p>A teller can still:</p><ul><li>Call your transfer endpoint directly using DevTools / network replay</li><li>Intercept and replay requests via a proxy</li><li>Use curl/Postman with a valid token and hit the API anyway</li></ul><p>So the rule is:</p><blockquote><strong><em>UI is UX. API is security.</em></strong><em><br>If the API trusts the UI, it’s already broken.</em></blockquote><p>Your UI can <em>help</em> by hiding buttons and guiding the user — but authorization must be enforced where the money moves: the backend.</p><h3>Identity as the source of truth</h3><p>If you want RBAC to scale beyond a toy app, you can’t scatter roles and permission logic across random services or store “role flags” inside the app.</p><p>Centralizing identity and authorization metadata in an IdP (like <strong>Keycloak</strong>) solves the real-world headaches:</p><ul><li>A clear view of who has what role/permission</li><li>Changes happen once in a central place and apply everywhere (<strong>single source of truth</strong>)</li><li>Easier to audit: <strong>who got what access, when, and why</strong></li><li>Consistency across apps: permissions don’t drift into different meanings per system</li><li>Tokens carry the authorization context — you don’t need a separate role database for every app</li></ul><p>The app shouldn’t <strong>invent</strong> roles. It should <strong>consume</strong> them from the IdP and <strong>enforce</strong> them at the API boundary.</p><p><strong>Talk Is Cheap, Show Me the Code: RBAC in Keycloak + Node.js</strong></p><p>We’ll continue exactly where <a href="https://medium.com/@kiruu1238/oauth-2-0-oidc-explained-like-youre-building-it-keycloak-consent-demo-4c963a38199d">Part 1</a> ended. We already have login + tokens working. Now we’re going to turn those tokens into <strong>real authorization.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5tifTYetPi9aUOF5D9C5KQ.png" /><figcaption>client business role</figcaption></figure><h3>Realm roles vs Client roles (Keycloak)</h3><p>In Keycloak, you’ll see two role types:</p><p><strong>Realm roles</strong> — global across the realm<br> Think: “org-wide roles” that multiple apps might care about.</p><p>Example in the Microsoft world: a directory-wide role in Microsoft Entra ID applies across the tenant, not just one app.</p><p><strong>Client roles</strong> — scoped to a specific application/client<br> Think: “roles for <em>this</em> app”.</p><p>For this series, we’ll use <strong>client roles</strong> because we’re building RBAC for a specific NeoBank application, and we want the roles to live close to the resource server context.</p><h3>Business roles vs Permission roles (RBAC that scales)</h3><p>RBAC roles can be split into two categories:</p><h3>1) Business roles (coarse-grained)</h3><p>These are human-friendly labels like:</p><ul><li>customer</li><li>teller</li></ul><p>They’re easy for admins to understand — but they’re not always ideal for enforcement logic, especially when the system grows.</p><h3>2) Permission roles (fine-grained)</h3><p>These map directly to actions or API capabilities like:</p><ul><li>balance:read</li><li>transfer:write</li><li>userlist:view</li></ul><p>Permission roles scale better because:</p><ul><li>You can <strong>reuse</strong> permissions across different business roles</li><li>auditing is cleaner (“who has transfer:write?”)</li><li>Your API checks become consistent and granular</li></ul><p>A simple mental model:</p><blockquote><strong><em>Roles describe who you are. Permissions describe what you can do.</em></strong></blockquote><p><strong>Start simple: business roles in the token</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*u80AGt3ErtRd6EjCs2Q3ng.png" /><figcaption>Frank as teller</figcaption></figure><p>Once you assign a business role (say, teller) to a user, you’ll see it in the access token under:</p><pre>&quot;resource_access&quot;: {<br>  &quot;web-app&quot;: {<br>    &quot;roles&quot;: [&quot;teller&quot;]<br>  }<br>}</pre><p>Now that the role is in the token, the API can enforce guardrails based on that claim.</p><p>Here’s the simplest enforcement pattern:</p><pre> const roles = jwt.decode(token)?.resource_access?.[KEYCLOAK_CLIENT_ID]?.roles || <br><br>  if (!roles.includes(&quot;customer&quot;)) {<br>    return res.status(403).json({ error: &quot;INSUFFICIENT_ROLE&quot; });<br>  }</pre><p>That blocks anyone except customer from transferring money.</p><h4>Quick security note</h4><p>jwt.decode() only reads claims. It does <strong>not</strong> verify the token signature. In a real API, you should verify JWTs using Keycloak’s JWKS and validate iss + aud.</p><p>Our enforcement goal for the demo is:</p><p>If the user is a <strong>customer</strong>:</p><ul><li>land on the customer dashboard</li><li>can transfer money</li></ul><p>If the user is a <strong>teller</strong>:</p><ul><li>land on the teller dashboard</li><li>can view customer list + balances</li><li><strong>cannot</strong> transfer money</li></ul><p>You can enforce this at the routing level (UX + structure), but remember: <strong>this is not your security boundary</strong>. It’s just a clean portal experience.</p><p>Example: redirect teller to the teller portal:</p><pre>if (roles.includes(&quot;teller&quot;) &amp;&amp; !req.query.user) {<br>  return res.redirect(&quot;/teller&quot;);<br>}<br><br>// allow customer + teller to view the dashboard UI<br>if (!roles.includes(&quot;customer&quot;) &amp;&amp; !roles.includes(&quot;teller&quot;)) {<br>  return res.status(403).render(&quot;unauthorized&quot;);<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LdiB03giMqLuKYvfj_EVmg.gif" /><figcaption>Teller Transfer Block</figcaption></figure><p>A teller has read access to customer lists and balances, but has no permission to perform transfers on behalf of a customer.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*Gd4tyMhWLgHJ4bjdXwKw2A.gif" /><figcaption>Customer Transfer Success</figcaption></figure><p>A customer has read access to their own balance and is authorized to initiate transfers from their account.</p><h3>Make RBAC “IAM-ready”: permission roles + composite roles</h3><p>Now we evolve the model.</p><p>Instead of enforcing everything with just customer and teller, We introduce <strong>permission roles</strong> and map them into business roles using Keycloak’s <strong>composite roles</strong> (role composition).</p><h3>Our mapping</h3><p><strong>Customer</strong></p><ul><li>balance:read</li><li>transfer:write</li></ul><p><strong>Teller</strong></p><ul><li>userlist:view</li><li>balance:read</li></ul><p>Permission roles in KeyCloak</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*M3PT4QCcgSUlR87Hi1R5_Q.png" /><figcaption>permission roles</figcaption></figure><p>Role composition</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WSCkNwydIo2ouXhOiNdEVA.png" /></figure><p>In Keycloak, this means:</p><ul><li>Create permission roles as client roles</li><li>make the business roles composite</li><li>customer includes balance:read and transfer:write</li><li>teller includes userlist:view and balance:read</li></ul><p>Once you do that, the access token typically includes both the composite role name and the permission roles:</p><pre>&quot;resource_access&quot;: {<br>  &quot;web-app&quot;: {<br>    &quot;roles&quot;: [<br>      &quot;balance:read&quot;,<br>      &quot;transfer:write&quot;,<br>      &quot;customer&quot;<br>    ]<br>  }<br>}</pre><h3>Why composite roles are a real upgrade</h3><p>With only business roles, enforcement often becomes “role chaining”:</p><ul><li>If role is customer → allow A, B, C</li><li>If role is teller → allow D, E</li><li>plus special cases…</li></ul><p>That becomes painful fast.</p><p>Composite roles fix this by shifting complexity into IAM design:</p><ul><li>The IdP becomes the source of truth for “what this role implies.”</li><li>The API checks only what it needs — the exact permission</li></ul><p>Your API checks become clean and endpoint-aligned:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9xz0DjjSeDJ38xGzB0ra7g.png" /><figcaption>composite</figcaption></figure><p>This scales much better. With 50 business roles and 1000 permissions, you don’t want your API to hardcode a giant role matrix. You want the matrix to live in Keycloak, and the API to enforce permissions consistently.</p><p>This concludes the composite RBAC implementation. The diagram below summarizes the end-to-end flow from OIDC login to API-side permission enforcement using token claims.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7LkwvcrMPar4Cm1E1oJR-A.png" /><figcaption>RBAC flow</figcaption></figure><p>You can find the implementation code and my working notes for the baseline (token-claims) RBAC model <a href="https://github.com/ErKiran/keycloak_iam_learning/tree/simple-rbac">here</a>.</p><p><a href="https://github.com/ErKiran/keycloak_iam_learning/tree/simple-rbac">GitHub - ErKiran/keycloak_iam_learning at simple-rbac</a></p><p>In <strong>JWT-based RBAC</strong>, Keycloak issues roles/permissions as token claims, and the API enforces access by validating the token and checking those claims.</p><p>With <strong>User-Managed Access (UMA)</strong>, Keycloak becomes the <strong>Policy Decision Point (PDP)</strong>. Instead of relying only on local claim checks, the API asks Keycloak at runtime: <strong>“permit or deny?”</strong> for a specific resource and scope.</p><p>Keycloak still doesn’t automatically protect your API endpoints. The API remains the <strong>Policy Enforcement Point (PEP)</strong> — it must call UMA (or validate an RPT) and enforce Keycloak’s decision. UMA moves <strong>policy logic</strong> to Keycloak, but it does <strong>not</strong> move enforcement out of the API.</p><p><strong>Key UMA Concepts in Keycloak</strong></p><ul><li><strong>Resource (the thing being protected):</strong> transfer, balance, users</li><li><strong>Scope (the action on that resource):</strong> transfer:write, balance:read, userlist:view</li><li><strong>Policy (who is allowed):</strong> customer, teller</li><li><strong>Permission (the binding rule):</strong> <em>A </em><em>customer is permitted to perform </em><em>transfer:write on the </em><em>transfer resource.</em></li></ul><p>Let’s get into some action.</p><p>To use UMA (Authorization Services) in Keycloak, your resource server<strong> </strong>client should be a confidential client (client authentication enabled). Once that’s configured, Keycloak will expose the Authorization tab for defining resources, scopes, policies, and permissions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Rbs6ysghrN9JfOkEmc4A3A.png" /></figure><p><strong>Add Authorization Scopes</strong></p><p>Next, define authorization scopes for the client. Scopes represent the actions your API supports and are later referenced when creating permissions.</p><p>Create a scope named transfer:write — We’ll use it to define a permission that controls who is allowed to initiate transfers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HRd7HdYq9tM7ogkF0sC2EA.png" /><figcaption>transfer:write</figcaption></figure><p>Next, create a <strong>resource </strong>and attach the relevant scopes to it. In this model, the resource server client (your API client) is the owner/manager of the resource definition.</p><p>For each resource, you’ll:</p><ul><li>define the resource name (e.g., transfer)</li><li>associate one or more URIs (e.g., /transfer)</li><li>Attach the applicable authorization scopes (e.g., transfer:write)</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sUfIPn33QlyjapPQteaKWQ.png" /><figcaption>resource scope</figcaption></figure><p>Next, wire up a <strong>role-based policy</strong>. In this step, you choose which role(s) the policy evaluates (e.g., transfer:write) and explicitly set whether the policy is <strong>positive</strong> (allow when the role is present) or <strong>negative</strong> (deny when the role is present).</p><p>For example:</p><ul><li><strong>Positive: </strong>The policy returns <em>true</em> when the role is present</li><li><strong>Negative: </strong>The policy returns <em>false</em> when the role is present</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EhOlFsAne15Ezo3iBSweUg.png" /><figcaption>role based policy</figcaption></figure><p><strong>A scope-based permission</strong> is the final piece of the puzzle. This is where everything gets bound together: the resource created earlier, the authorization scopes defined for that resource, and the policy that decides <em>who</em> is allowed.</p><p>In this step, a permission is created by:</p><ul><li>selecting the target resource (e.g., transfer)</li><li>attaching the relevant scope(s) (e.g., transfer:write)</li><li>applying one or more policies (e.g., CustomerPolicy)</li></ul><p>Keycloak also lets you choose a decision strategy:</p><ul><li><strong>Unanimous</strong> → all associated policies must evaluate to <em>true</em></li><li><strong>Affirmative</strong> → at least one policy must evaluate to <em>true</em></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4zbQl3so_ZhM3ECOdryOGQ.png" /><figcaption>scope-based permission</figcaption></figure><p>High level workflow of UMA with the exisiting system</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Wnk7YIiAGU6PrH5-R0NzFQ.png" /><figcaption>UMA FLow</figcaption></figure><p>If the policies match, the user is granted access (<strong>Permit</strong>); otherwise, access is <strong>Denied</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hWpkZNAulSjNKVD75Jiuyw.gif" /><figcaption>Customer Permitted</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AtyK94aD5wiI4VhKdgOsFQ.gif" /><figcaption>Teller Denied Transfer</figcaption></figure><p>From the API side, this is a clean integration: wire in the middleware as the enforcement point and gate each endpoint with the required scope/permission.</p><pre>  // const roles = getUserRoles(req);<br>  // if (!roles.includes(TRANSFER)) {<br>  //   return res.status(403).json({ error: &quot;UNAUTHORIZED_ACTION&quot; });<br>  // }<br><br>  const allowed = await umaDecision(req, &quot;transfer&quot;, TRANSFER);<br><br>  if (!allowed) {<br>    return res.status(403).json({ error: &quot;UNAUTHORIZED_ACTION&quot; });<br>  }</pre><p>There is one downside to UMA: it introduces <strong>an extra network hop</strong> for authorization.</p><p>With JWT-based RBAC, the API can make a decision locally by checking token claims. With UMA, the API typically has to call Keycloak at runtime to get a <strong>permit/deny</strong> decision (or to obtain an RPT), which adds overhead.</p><p>That overhead usually shows up as:</p><ul><li><strong>Latency:</strong> Every protected action may require an additional request to Keycloak</li><li><strong>Throughput impact:</strong> more calls under load (API → Keycloak)</li><li><strong>Availability coupling:</strong> if the policy decision service is slow/down, authorization becomes slow/fails unless you design fallbacks</li></ul><p>Common mitigations:</p><ul><li><strong>Cache decisions</strong> for a short TTL (e.g., 30–60 seconds) keyed by (user, resource, scope)</li><li>Prefer <strong>RPT-based enforcement</strong> (request an RPT once, then reuse it until it expires) instead of calling “decision mode” on every request</li><li>Apply UMA primarily to <strong>high-risk actions</strong> (e.g., transfers) while using local checks for low-risk reads, depending on your threat model and performance goals</li></ul><p>Code and rough notes for the UMA flow are available here: <br><a href="https://github.com/ErKiran/keycloak_iam_learning/tree/uma-rbac">https://github.com/ErKiran/keycloak_iam_learning/tree/uma-rbac</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a21f02afa7dc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[OAuth 2.0 & OIDC, Explained Like You’re Building It (Keycloak + Consent Demo)]]></title>
            <link>https://medium.com/@kiruu1238/oauth-2-0-oidc-explained-like-youre-building-it-keycloak-consent-demo-4c963a38199d?source=rss-b0ae211f548d------2</link>
            <guid isPermaLink="false">https://medium.com/p/4c963a38199d</guid>
            <category><![CDATA[oidc]]></category>
            <category><![CDATA[oauth2]]></category>
            <category><![CDATA[cybersecurity]]></category>
            <dc:creator><![CDATA[Kiran Adhikari]]></dc:creator>
            <pubDate>Sun, 15 Feb 2026 07:36:04 GMT</pubDate>
            <atom:updated>2026-02-15T07:36:04.223Z</atom:updated>
            <content:encoded><![CDATA[<p>If you are reading this story, you’ve probably encountered “Login with X” at least once — not <strong>X (formerly Twitter)</strong>, but any “Login with Google/GitHub/Microsoft”-style button. That experience is often <em>powered by OAuth 2.0 + OpenID Connect (OIDC)</em>, but it’s important to separate what each protocol is actually meant to do.</p><p><strong>OAuth 2.0 is not a login protocol.</strong> It was designed for <strong>delegated authorization</strong> — letting an application access specific resources (APIs) on a user’s behalf, without the user handing over their password to that application.</p><p>In the early 2010s, many companies started using OAuth 2.0 flows as a shortcut for authentication (“log the user in”) by treating access tokens like proof of identity. In practice, teams built wrappers and conventions around OAuth to make it <em>act</em> like a login. This worked “well enough” for basic apps, but it also created widespread confusion between <strong>OAuth 2.0</strong> and <strong>OIDC</strong> — and, in some cases, introduced security mistakes (like validating the wrong thing or using the wrong token for identity).</p><p>In this tutorial, I’m going to go deep — <strong>introduce, implement, and clearly differentiate OAuth 2.0 and OIDC</strong>, two widely used (and commonly misunderstood) protocols that show up everywhere in modern IAM.</p><h3>Why do we need OAuth in the first place?</h3><p>Before OAuth, third-party apps didn’t have a standard, safe way to access a user’s data that lived in another service. That gap led to messy custom integrations — and sometimes the worst practice of all: <strong>password sharing</strong>.</p><p>Imagine you’re using a “shiny” calendar app that promises to unify your schedule across multiple ecosystems — <strong>Google Calendar</strong>, <strong>Microsoft Outlook/Calendar</strong>, <strong>Apple Calendar</strong>, and more — so you can see everything in one place without constant context switching.</p><p>In a pre-OAuth world, you might have been forced to hand over the usernames and passwords for those accounts to the third-party app so it could log in “as you” and pull your calendar data. That’s a huge trust and security problem:</p><ul><li>You’re giving a third party full access to your account, not just the calendar.</li><li>You can’t easily limit what the app can do (read vs. edit vs. delete).</li><li>If the third-party app gets breached, <strong>your accounts could be exposed</strong>.</li><li>Revoking access is painful (often requires changing your password everywhere).</li></ul><p>OAuth was introduced to solve this exact problem by enabling <strong>delegated authorization</strong>:<br> You can grant a third-party app <strong>limited access</strong> to specific resources <strong>without sharing your password</strong>, and you can revoke that access later.</p><p><strong>OAuth 2.0 Authorization Code Flow (Standard OAuth)</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pzRrECxzVoS_68-TDgRkDw.png" /><figcaption>Oauth 2.0 Flow</figcaption></figure><p>Let’s explain the flow with the same example we used earlier: <strong>Calendy</strong>, a calendar aggregator.</p><p>A user wants the Calendy app to access their <strong>Google Calendar</strong>. The <strong>client (Calendy)</strong> sends an authorization request to <strong>Google’s Authorization Server</strong> with a client_id and the requested scope (for example, calendar.read). The user is then shown a <strong>consent screen</strong>. Once the user approves the consent, the authorization server responds with an <strong>authorization code</strong> (a one-time code).</p><p>Next, Calendy exchanges that authorization code by sending a request to Google’s <strong>token endpoint</strong> to obtain tokens. Google then returns an <strong>access token</strong> (and sometimes a refresh token). Calendy uses the access token to call the <strong>Google Calendar API</strong> and read the user’s calendar data.</p><p><strong>Where OAuth Falls Short for Authentication</strong></p><p>OAuth was originally designed for authorization (granting an app permission to access an API), not for authentication (proving who the user is). That’s why OAuth doesn’t define an ID token.</p><p>With OAuth, you may get an access token, but user identity information inside access tokens is not standardized (and in many cases it isn’t included at all). Before OIDC, different providers placed user claims in different locations, used different formats, and followed different conventions. That lack of consistency forced developers into hacky, provider-specific implementations just to figure out who the user actually is.</p><p>OIDC (OpenID Connect) fixes the common “OAuth-as-login” mistake by adding an <strong>identity layer</strong> on top of OAuth 2.0.</p><p>With OIDC, the client includes the <strong>openid</strong> scope in the authorization request. That tells the Authorization Server: <em>“I’m not only asking for API access — I also need proof of who the user is.”</em></p><p>In response, the client receives an <strong>ID token</strong>, which is a standardized token that contains information about the <strong>resource owner (the user)</strong>.</p><h4>Key components of the ID Token</h4><ul><li><strong>iss (Issuer)</strong> — Who issued the token (the identity provider).<br> This matters because your app should only trust tokens coming from the <strong>expected</strong> issuer, not from anywhere else.</li><li><strong>aud (Audience)</strong> — Who the token is meant for (your app’s <strong>client_id</strong>).<br> This prevents a token issued for one app from being reused in a different app.</li><li><strong>sub (Subject)</strong> — The user’s unique identifier.<br> This is the stable “user ID” you should rely on for identifying the user.</li><li><strong>exp (Expiration)</strong> — When the token expires.<br> This limits how long the token can be used and reduces risk if it’s ever leaked.</li></ul><h4>Initial Lab Setup:</h4><p>For the initial lab setup, we can spin up a Keycloak server with Docker.</p><p><a href="https://www.keycloak.org/getting-started/getting-started-docker">Docker</a></p><pre>docker run -p 127.0.0.1:8080:8080 -e KC_BOOTSTRAP_ADMIN_USERNAME=admin -e KC_BOOTSTRAP_ADMIN_PASSWORD=admin quay.io/keycloak/keycloak:26.5.3 start-dev</pre><p>In order to test the OAuth 2.0 Flow, we need to set up a client.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MWFVP588wRE7_h5eHbjyzw.png" /><figcaption>Client Setup!</figcaption></figure><p>The client ID is important — it’s the client’s unique identifier, and whatever actions we perform in the OAuth flow are tied to that client ID. We’ll use it client_id in all subsequent requests later.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BeBY6Yk26hQZaZgsjs1XDg.png" /><figcaption>redirect-setup</figcaption></figure><p>An important piece of information in this image is the <strong>redirect URL</strong>, which must be configured correctly. When we hit the <strong>/authorize (auth)</strong> endpoint, the authorization server redirects the user back to this redirect URL with an <strong>authorization code</strong>. We then use that code to exchange it for tokens at the <strong>token endpoint</strong>. The authorization code is <strong>one-time use</strong>, and we’ll walk through the full flow later.</p><p>OAuth was originally built for <strong>authorization</strong>, but its adoption grew so quickly that many companies started using it for <strong>authentication</strong>, often by building their own identity layers on top of OAuth. That led to scattered and sometimes ambiguous implementations. To solve this, <strong>OpenID Connect (OIDC)</strong> was introduced — it extends OAuth and standardizes authentication by adding a proper identity layer (including the <strong>ID token</strong>) in a consistent way.</p><p>That’s enough background. Let’s see the action.</p><p>To keep things simple for now, we’ll create a basic user <strong>without MFA or any extra overhead</strong>. I’ll cover MFA in a separate post.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gHofzN-rQ1RLH1SVDoI3Bw.png" /><figcaption>Keycloak users</figcaption></figure><p>After the user is created, we can set up credentials for that user, which we’ll use during the login process.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*k4rFn5yVHj-lG19CPwqdOA.png" /><figcaption>credentials</figcaption></figure><p>That’s all we need to get started.</p><p>The starting point for the implementation is the <strong>/auth</strong> endpoint.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*86VFuMYhNOgo5Pj8oXpvxw.png" /><figcaption>auth:postman</figcaption></figure><p>Params</p><ul><li><strong>client_id: </strong>Identifies the requesting application. This should match the client that we created in Keycloak.</li><li><strong>response_type:</strong> It accepts the authorization code flow. The authorization server responds with the one-time use authorization code.</li><li><strong>scope:</strong> This makes this flow OIDC (OpenID Connect). “I want authentication (identity) information too,” which enables Keycloak to issue an ID token later.</li><li><strong>redirect_uri: </strong>This is the URL Keycloak will redirect back to after the user logs in and approves consent. The authorization code is delivered through this redirect.</li></ul><p>Once we send this request, Keycloak shows the <strong>login screen</strong> (and a <strong>consent screen</strong> if consent is enabled). After the user approves, Keycloak redirects the browser to:</p><p><a href="http://localhost:3000/callback?code=...">http://localhost:3000/callback?code=...</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*oI-kIEdNiKTFUf7sA9bRpg.gif" /></figure><p>We got this response.</p><pre>{<br>    &quot;access_token&quot;: &quot;eyJhbGciOiJSUzI1NiIsInR5cCIgOiAiSldUIiwia2lkIiA6ICJJQ041R1Rla1Y5akZKS0wxUXA0OXNNbS1XMW8wTEU0c0NGdGZwV1VkTU0wIn0.eyJleHAiOjE3NzEwMzc1MzUsImlhdCI6MTc3MTAzNzIzNSwiYXV0aF90aW1lIjoxNzcxMDM3MjE5LCJqdGkiOiJvbnJ0YWM6ZTAzNjc4NDctODA4My0yYjBlLWQ2NzQtNDMwYmViZWFmOWE5IiwiaXNzIjoiaHR0cDovL2xvY2FsaG9zdDo4MDgwL3JlYWxtcy9taW5pbGFiIiwiYXVkIjoiYWNjb3VudCIsInN1YiI6IjU3MjRlNzNmLTlkZWYtNDEzNS1hNTczLWNkMGM4ZDc4NDUwZiIsInR5cCI6IkJlYXJlciIsImF6cCI6IndlYi1hcHAiLCJzaWQiOiJlMXRyenliaTFyX1NYTmM1YW1QUFk2WloiLCJhY3IiOiIxIiwiYWxsb3dlZC1vcmlnaW5zIjpbImh0dHA6Ly9sb2NhbGhvc3Q6MzAwMCJdLCJyZWFsbV9hY2Nlc3MiOnsicm9sZXMiOlsib2ZmbGluZV9hY2Nlc3MiLCJkZWZhdWx0LXJvbGVzLW1pbmlsYWIiLCJ1bWFfYXV0aG9yaXphdGlvbiJdfSwicmVzb3VyY2VfYWNjZXNzIjp7ImFjY291bnQiOnsicm9sZXMiOlsibWFuYWdlLWFjY291bnQiLCJtYW5hZ2UtYWNjb3VudC1saW5rcyIsInZpZXctcHJvZmlsZSJdfX0sInNjb3BlIjoib3BlbmlkIHByb2ZpbGUgZW1haWwiLCJlbWFpbF92ZXJpZmllZCI6ZmFsc2UsIm5hbWUiOiJUZXN0IFVzZXIiLCJwcmVmZXJyZWRfdXNlcm5hbWUiOiJ0ZXN0dXNlciIsImdpdmVuX25hbWUiOiJUZXN0IiwiZmFtaWx5X25hbWUiOiJVc2VyIiwiZW1haWwiOiJ0ZXN0QHVzZXIuaW8ifQ.ZK26i7KS7GXIUVX27H4wvI8JDYlhSMP0meUO3_LOnKTGPamlQe6Z0NzQz7FhHK6KjrExHLu9JGcl4J4udYfy0DZEO6ENL4L3M_jLgJ4J1-RJxHg2o1xd0R9FAWR31GLKZtFdVmwZP71MUjFQveIQftwmPAUgqzmKjpycZ8Npfj9YIuG2c3n52sn28KTwITspDuFVdKD-M0UBbr1kmkPDHrXHjPXwAV9LlTA9ETV8dZ5CmASeSFLnK8Z2RVBwZiCj3WSe9nvryMbGUaG21IzhstDxrkFh-nZK4w3MTAZx-OhwGJK3b9CT-47VxmFpOd3UbYDAlHr8BFb9c2W5IJEsfw&quot;,<br>    &quot;expires_in&quot;: 299,<br>    &quot;refresh_expires_in&quot;: 1800,<br>    &quot;refresh_token&quot;: &quot;eyJhbGciOiJIUzUxMiIsInR5cCIgOiAiSldUIiwia2lkIiA6ICJiZGEyOWY3Yy03MDc4LTQzOTEtODcyNi1mOTVkY2NlZjViMGUifQ.eyJleHAiOjE3NzEwMzkwMzYsImlhdCI6MTc3MTAzNzIzNiwianRpIjoiNjA1ZDAyNGMtYWE0Ny1jYTA2LWMyNDctZTRjNjBhMzliOGUxIiwiaXNzIjoiaHR0cDovL2xvY2FsaG9zdDo4MDgwL3JlYWxtcy9taW5pbGFiIiwiYXVkIjoiaHR0cDovL2xvY2FsaG9zdDo4MDgwL3JlYWxtcy9taW5pbGFiIiwic3ViIjoiNTcyNGU3M2YtOWRlZi00MTM1LWE1NzMtY2QwYzhkNzg0NTBmIiwidHlwIjoiUmVmcmVzaCIsImF6cCI6IndlYi1hcHAiLCJzaWQiOiJlMXRyenliaTFyX1NYTmM1YW1QUFk2WloiLCJzY29wZSI6Im9wZW5pZCBhY3IgcHJvZmlsZSByb2xlcyBiYXNpYyBlbWFpbCB3ZWItb3JpZ2lucyJ9.qpdNG_seIQ23IE6nJ6-9f-fo3sQMeaBv4BuzdJKCSkeH8xCo9_suSkAfWL1PBHFqPxU3RzsM3IZNNPrZU3Drsg&quot;,<br>    &quot;token_type&quot;: &quot;Bearer&quot;,<br>    &quot;id_token&quot;: &quot;eyJhbGciOiJSUzI1NiIsInR5cCIgOiAiSldUIiwia2lkIiA6ICJJQ041R1Rla1Y5akZKS0wxUXA0OXNNbS1XMW8wTEU0c0NGdGZwV1VkTU0wIn0.eyJleHAiOjE3NzEwMzc1MzUsImlhdCI6MTc3MTAzNzIzNiwiYXV0aF90aW1lIjoxNzcxMDM3MjE5LCJqdGkiOiIwOGIwNWZjZS0zMmM3LTYyNzUtMmQ2Yi0wOGNkMWQ0ZTcyMTkiLCJpc3MiOiJodHRwOi8vbG9jYWxob3N0OjgwODAvcmVhbG1zL21pbmlsYWIiLCJhdWQiOiJ3ZWItYXBwIiwic3ViIjoiNTcyNGU3M2YtOWRlZi00MTM1LWE1NzMtY2QwYzhkNzg0NTBmIiwidHlwIjoiSUQiLCJhenAiOiJ3ZWItYXBwIiwic2lkIjoiZTF0cnp5Ymkxcl9TWE5jNWFtUFBZNlpaIiwiYXRfaGFzaCI6InBFbWVmcTBEdzFuUnNTNWpnSFA4TEEiLCJhY3IiOiIxIiwiZW1haWxfdmVyaWZpZWQiOmZhbHNlLCJuYW1lIjoiVGVzdCBVc2VyIiwicHJlZmVycmVkX3VzZXJuYW1lIjoidGVzdHVzZXIiLCJnaXZlbl9uYW1lIjoiVGVzdCIsImZhbWlseV9uYW1lIjoiVXNlciIsImVtYWlsIjoidGVzdEB1c2VyLmlvIn0.eqFKT_p4Ge35CEDn-P-kD9mMTtO5nq0XAsvGK578Ca2t9jVhE-Gjjaa0CaM2XAIl79Q0HfGy9NJQdGO5VFb6xiI-XxZr4YyOcohsAl8dEJJuNMCPp4RyQem8kgvqzckBl-s6nONHrtXYKeWQ3K5xLUd-g63HWW2o928j9jxQNXXDNdHT4mpnbvpXOsCTcp3Y4GfFQojT32wo_N_RG0nT9iqclt5cSNDhYIM_penjIJIk_xwSZURWibUFhvzYHqgXcrgjd56LibQaRk7NJEroxqYeEXwYYDoFVPHfzJS3niM3enQXFQ4epbfhWz8VS-K2tnLX9jWHbYjfi6ijQnTe5w&quot;,<br>    &quot;not-before-policy&quot;: 0,<br>    &quot;session_state&quot;: &quot;e1trzybi1r_SXNc5amPPY6ZZ&quot;,<br>    &quot;scope&quot;: &quot;openid profile email&quot;<br>}</pre><pre>{<br>  &quot;exp&quot;: 1771037535,<br>  &quot;iat&quot;: 1771037235,<br>  &quot;auth_time&quot;: 1771037219,<br>  &quot;jti&quot;: &quot;onrtac:e0367847-8083-2b0e-d674-430bebeaf9a9&quot;,<br>  &quot;iss&quot;: &quot;http://localhost:8080/realms/minilab&quot;,<br>  &quot;aud&quot;: &quot;account&quot;,<br>  &quot;sub&quot;: &quot;5724e73f-9def-4135-a573-cd0c8d78450f&quot;,<br>  &quot;typ&quot;: &quot;Bearer&quot;,<br>  &quot;azp&quot;: &quot;web-app&quot;,<br>  &quot;sid&quot;: &quot;e1trzybi1r_SXNc5amPPY6ZZ&quot;,<br>  &quot;acr&quot;: &quot;1&quot;,<br>  &quot;allowed-origins&quot;: [<br>    &quot;http://localhost:3000&quot;<br>  ],<br>  &quot;realm_access&quot;: {<br>    &quot;roles&quot;: [<br>      &quot;offline_access&quot;,<br>      &quot;default-roles-minilab&quot;,<br>      &quot;uma_authorization&quot;<br>    ]<br>  },<br>  &quot;resource_access&quot;: {<br>    &quot;account&quot;: {<br>      &quot;roles&quot;: [<br>        &quot;manage-account&quot;,<br>        &quot;manage-account-links&quot;,<br>        &quot;view-profile&quot;<br>      ]<br>    }<br>  },<br>  &quot;scope&quot;: &quot;openid profile email&quot;,<br>  &quot;email_verified&quot;: false,<br>  &quot;name&quot;: &quot;Test User&quot;,<br>  &quot;preferred_username&quot;: &quot;testuser&quot;,<br>  &quot;given_name&quot;: &quot;Test&quot;,<br>  &quot;family_name&quot;: &quot;User&quot;,<br>  &quot;email&quot;: &quot;test@user.io&quot;<br>}</pre><p>An access token is pretty self-explanatory. I’ll briefly explain a few key aspects of the token:</p><ul><li><strong>Access tokens are short-lived.</strong> You can see the time-sensitive fields like exp, iat, and auth_time, which tells you when the token expires, when it was issued, and when the user authenticated.</li><li><strong>iss (issuer) and </strong><strong>aud (audience) Define the trust boundary.</strong> They help the receiver verify <em>who</em> issued the token and <em>who</em> the token is intended for.</li><li><strong>sub (subject) is a stable user identifier.</strong> Profile fields like name and email can change, but sub is typically the safest primary key to use when identifying the user.</li></ul><p>ID Token</p><pre>{<br>  &quot;exp&quot;: 1771037535,<br>  &quot;iat&quot;: 1771037236,<br>  &quot;auth_time&quot;: 1771037219,<br>  &quot;jti&quot;: &quot;08b05fce-32c7-6275-2d6b-08cd1d4e7219&quot;,<br>  &quot;iss&quot;: &quot;http://localhost:8080/realms/minilab&quot;,<br>  &quot;aud&quot;: &quot;web-app&quot;,<br>  &quot;sub&quot;: &quot;5724e73f-9def-4135-a573-cd0c8d78450f&quot;,<br>  &quot;typ&quot;: &quot;ID&quot;,<br>  &quot;azp&quot;: &quot;web-app&quot;,<br>  &quot;sid&quot;: &quot;e1trzybi1r_SXNc5amPPY6ZZ&quot;,<br>  &quot;at_hash&quot;: &quot;pEmefq0Dw1nRsS5jgHP8LA&quot;,<br>  &quot;acr&quot;: &quot;1&quot;,<br>  &quot;email_verified&quot;: false,<br>  &quot;name&quot;: &quot;Test User&quot;,<br>  &quot;preferred_username&quot;: &quot;testuser&quot;,<br>  &quot;given_name&quot;: &quot;Test&quot;,<br>  &quot;family_name&quot;: &quot;User&quot;,<br>  &quot;email&quot;: &quot;test@user.io&quot;<br>}</pre><p>So far, we have the user’s identity credentials and an authorization code to obtain a token.</p><p>Now we’re implementing the heart of OAuth delegation (authorization). For that, we need to create a <strong>client scope</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sgYaH9Nv_r6G4I8M5l1c2g.png" /></figure><p>These client scopes are <strong>global to the realm</strong>, meaning they can be attached to any client within that realm. To actually enforce (or apply) those scopes, we need to add them to the relevant client.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Tz8iXVrVV8JDtZBFHvlXcQ.png" /></figure><p>That’s all we need to worry about for now to make the consent workflow work.</p><p>I built a minimal Node.js server to simulate a mock “transfer money” function and demonstrate the consent workflow.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*SDPTD5pEIFklI7UE-gasDg.gif" /><figcaption>consent workflow</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*PJ93ASoCHMgI3yDF9GZaDA.gif" /><figcaption>consent failure</figcaption></figure><p>This is the “heart” of OAuth/OIDC delegation: the user is explicitly approving (or denying) what an app can do on their behalf, and the system behaves differently depending on that decision.</p><p>Code is available here for anyone who wants to try the flow locally.</p><p><a href="https://github.com/ErKiran/keycloak_iam_learning">GitHub - ErKiran/keycloak_iam_learning: Learning IAM with KeyCloak</a></p><p>I’ll iteratively build on this lab with <strong>RBAC</strong> and <strong>SSO</strong> in the upcoming series. Stay tuned for more <strong>#IAMWithKiran</strong>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4c963a38199d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Identity Life Cycle: Joiner Process]]></title>
            <link>https://medium.com/@kiruu1238/identity-life-cycle-joiner-process-fe4e4a36347d?source=rss-b0ae211f548d------2</link>
            <guid isPermaLink="false">https://medium.com/p/fe4e4a36347d</guid>
            <category><![CDATA[information-security]]></category>
            <category><![CDATA[identity-management]]></category>
            <category><![CDATA[identity]]></category>
            <dc:creator><![CDATA[Kiran Adhikari]]></dc:creator>
            <pubDate>Tue, 10 Feb 2026 04:40:28 GMT</pubDate>
            <atom:updated>2026-02-26T04:26:00.766Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_mnE0gtG_DFJ4_I3ttPDNg.jpeg" /><figcaption>Access Badge</figcaption></figure><p>When I joined a small IT company in Nepal in 2019, the Identity Lifecycle didn’t just lack automation — it didn’t exist.</p><p>Provisioning access for a new employee often took days. To simply start working, a developer needed access to:</p><ul><li>Email</li><li>Communication channels (Slack/Teams)</li><li>Code repositories</li><li>Cloud resources</li><li>Project management tools (Jira, Trello)</li><li>Databases and caches (MySQL, Redis)</li><li>HR and payroll systems</li></ul><p>And the list kept growing.</p><p>There was no documented process.</p><p>Instead, identity management lived inside the head of a senior engineer or DevOps person.</p><p>This works… until it doesn’t.</p><p>What happens when the company grows from 50 people to 500?<br>What happens when the one person who understands access leaves suddenly?</p><p>At that point, onboarding slows down, offboarding fails, privileges accumulate, and security risk increases.</p><p>Remote work, security breaches, <strong>Zero Trust architecture</strong>, and the <strong>principle of least privilege</strong> have made Identity and Access Management more important than ever.</p><h4>Joiner Process</h4><p>When a new employee is onboarded</p><ol><li>HR assigns an immediate manager</li><li>The manager determines the employee’s role</li><li>The role determines required access</li></ol><p>Access should come from a predefined role-based access list</p><p>Without this structure, every onboarding becomes a manual security decision — and humans make inconsistent security decisions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LtI3jZXNZJd7L63T4lt93g.png" /><figcaption>Joiner Workflow</figcaption></figure><p>Let’s explore the pain points and the missing pillars in this Joiner Workflow.</p><p>The approval workflow is missing. The manager directly provisions access to resources, which should be done via an access request, review, and approval cycle. This violates the <strong>segregation of duties (SoD)</strong>. Audit and logging for compliance are missing since there isn’t a proper approval workflow.</p><p>In the real world, a person can be part of multiple projects at the same time. For example, a QA developer might be testing multiple projects for a company since they are the only QA in the company. This creates sprawl and orphaned project access if the access isn’t reviewed in time. Birthright access and project-based entitlements help mitigate such issues.</p><p>Furthermore, <strong>time-bound project access</strong> can be imposed initially and then reviewed later to see if they still need access to the project, which can be done through the access request, review, and approval process.</p><p>The previous workflow breaks for the following reasons:<br>1. When the company scales, identity personnel can’t keep up with provisioning and deprovisioning.<br>2. Knowledge-based IAM works only when everyone knows everyone and is based on a trust model.<br>3. They need to keep up with multiple SaaS apps for productivity.</p><p>A mature IAM process for the Joiner would look something like this</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zALxfU00flQb8u5ubbbmSg.png" /><figcaption>IAM onboarding process</figcaption></figure><p>We have an iterative phase-out of Pre-IAM, or Tribal Knowledge IAM.</p><p>Instead of manual identity creation, we now have HR systems such as Workday as an authoritative source, which create identities with unique identifiers and attributes. These attributes enable attribute-based decision-making in the approval workflow.</p><p>Role-policy mapping ensures consistent access across the team and mitigates the risks of inconsistent and inaccurate roles created by ad-hoc role definitions. Access request and approval workflows introduce segregation of duties, create accountability, and support auditing.</p><p>Automation of provisioning to SaaS applications via <strong>SCIM</strong> and <strong>APIs</strong> enables seamless integration through <strong>SSO</strong>. This not only reduces IT/Help Desk tickets but also enhances user experience, as employees can use a single account to sign in to all the tools they need for work.</p><p>If you’re still reading this far, feel free to provide suggestions on the identity workflow.</p><p>This is the first part of the <strong>“IAM with KIRAN”</strong> series. I will be sharing both technical and theoretical posts on topics related to IAM.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fe4e4a36347d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Evolutions of Firewalls]]></title>
            <link>https://medium.com/@kiruu1238/evolutions-of-firewalls-24c0ae1c1210?source=rss-b0ae211f548d------2</link>
            <guid isPermaLink="false">https://medium.com/p/24c0ae1c1210</guid>
            <category><![CDATA[firewall]]></category>
            <category><![CDATA[cybersecurity]]></category>
            <dc:creator><![CDATA[Kiran Adhikari]]></dc:creator>
            <pubDate>Thu, 06 Nov 2025 00:24:41 GMT</pubDate>
            <atom:updated>2025-11-06T00:24:41.649Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*88khsDQQOqXGVn-mtQjvJg.png" /></figure><h4>1. The OG Packet Filter (late 80s — early 90s)</h4><p>Think of packet filters as that grumpy old security guard at the front gate who only checks your <strong>ID and uniform</strong> — not what’s in your bag. They look at headers only — <strong>source IP, destination IP, protocol, port number.</strong></p><pre>ALLOW TCP FROM 192.168.1.0/24 TO ANY PORT 80</pre><p><strong>Good at:</strong> Basic traffic filtering.</p><p><strong>Terrible at:</strong> Context. They don’t know if a packet is part of a legit session or an attack. They’re basically like:</p><p><em>“Oh, you’ve got port 80 open? Sure, come on in!”</em></p><p><strong>Why they failed:</strong> Hackers realized you could spoof IPs, flood with SYN packets, or just craft packets that look “legit” at the header level. The firewall wouldn’t notice because it didn’t <em>track sessions</em>. It’s like someone flashing a fake badge and walking right in.</p><p><strong>Example attack today:</strong> Drop a DDoS or SYN flood on a packet filter — it’ll choke instantly. It doesn’t know which connections are half-open or malicious.</p><p><strong>How modern firewalls handle it:</strong> Next-Gen firewalls laugh at this. They maintain <em>connection states</em>, <em>application awareness</em>, and <em>rate limiting</em>. That flood wouldn’t even make it past the edge router.</p><h4>2. Stateful Firewalls (mid-90s — 2000s)</h4><p>Now we’re talking <strong>smart bouncers.</strong> They don’t just check the ID; they <strong>remember</strong> who came in and keep a list — a “state table.”</p><p>So when a response packet comes back, it checks:</p><blockquote><em>“Wait — was there a legit request for this connection?”</em></blockquote><p><strong>Good at:</strong> Tracking sessions (TCP handshakes, established states, etc.)</p><p><strong>Bad at:</strong> Understanding application layer stuff. They still don’t know what’s <em>inside</em> the packets. So if someone sent malware over an allowed port (like HTTP/443), the stateful firewall would shrug.</p><p><strong>Why they failed:</strong> Attackers realized that “If I hide my malicious payload in legit traffic (like HTTP), the firewall will wave it through.” So… they started using <strong>port 80 and 443</strong> for everything — malware C2, tunneling, you name it.</p><h4>3. Third-Generation / Application Layer Firewalls (early 2000s)</h4><p>These were the “nerdy” ones — firewalls that started reading the actual <strong>payloads</strong> of packets. They spoke <strong>Layer 7</strong> languages — HTTP, FTP, SMTP — and could say,</p><blockquote><em>“Hey, this isn’t just port 80 traffic. This is someone trying to upload a PHP shell through HTTP POST.”</em></blockquote><p><strong>Good at:</strong> Deep Packet Inspection (DPI), enforcing policies per app.</p><p><strong>Bad at:</strong> Performance (CPU-heavy) and encryption blindness (couldn’t inspect SSL/TLS).</p><p><strong>Why they failed:</strong> Then came <strong>SSL/TLS everywhere</strong>. HTTPS-encrypted payloads, and these firewalls couldn’t decrypt and inspect them easily. Attackers used encryption as camouflage.</p><h4>4. Next-Generation Firewalls (NGFWs) — The Cyber Avengers</h4><p>Fast forward to the 2010s. Networks are insane. Cloud, IoT, VPNs, SaaS apps, encrypted everything — you name it. We needed something that could see through the chaos. So NGFWs arrived — combining all the old-school tricks with threat intel, machine learning, and SSL decryption.</p><p>They can:</p><ul><li>Recognize apps even if they use weird ports</li><li>Decrypt and inspect encrypted traffic</li><li>Tie activity to <em>users</em> and <em>devices</em></li><li>Sandbox suspicious payloads</li><li>Correlate with <strong>threat feeds</strong> in real time</li></ul><p>Basically, they’re not just checking packets — they’re profiling behavior, linking it to users, and matching it against live intel.If a random script on your HR laptop starts beaconing out to Russia over HTTPS, it’ll flag it before you even finish your coffee.</p><h4>Time-Travel Matchups</h4><p><strong>Packet Filter vs Modern Attack:</strong></p><ul><li><em>Attack:</em> Encrypted reverse shell over HTTPS</li><li><em>Result:</em> Packet filter says, “Looks fine. Port 443 allowed.”</li><li><em>NGFW:</em> “Wait, why is Chrome.exe spawning PowerShell making an outbound HTTPS call?” → 🚫 Blocked + Alerted</li></ul><p><strong>Stateful Firewall vs Today’s APT:</strong></p><ul><li><em>Attack:</em> C2 channel over HTTPS with domain fronting</li><li><em>Stateful firewall:</em> “Legit TLS handshake, looks fine.”</li><li><em>NGFW:</em> “That certificate doesn’t match domain behavior. Sandbox test shows malicious pattern.” → Blocked.</li></ul><p><strong>Next-Gen Firewall vs 90s Attacks:</strong></p><ul><li><em>Attack:</em> SYN flood or FTP bounce</li><li><em>NGFW:</em> Rolls eyes, rate-limits, and triggers auto mitigation in seconds. That’s like bringing a wooden sword to a tank fight.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=24c0ae1c1210" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Complete Guide to Logs & Log Analysis: From Developer Desk to SOC Dashboard]]></title>
            <link>https://medium.com/@kiruu1238/the-complete-guide-to-logs-log-analysis-from-developer-desk-to-soc-dashboard-95072556b234?source=rss-b0ae211f548d------2</link>
            <guid isPermaLink="false">https://medium.com/p/95072556b234</guid>
            <category><![CDATA[siem]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[logs]]></category>
            <category><![CDATA[log-analysis]]></category>
            <dc:creator><![CDATA[Kiran Adhikari]]></dc:creator>
            <pubDate>Sat, 30 Aug 2025 05:27:14 GMT</pubDate>
            <atom:updated>2025-08-30T05:27:14.418Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*F7Vw3GorKuNXdJSmqAEsiQ.jpeg" /><figcaption>Panic room</figcaption></figure><h3>Introduction: The $42 Million Heist That Almost Was</h3><p>Thursday, 3:17 AM | QuantumBank SOC, Frankfurt<br>Alarms shrieked as dashboards flashed blood-red.<br><em>Unauthorized wire transfers — $42M — funneled to offshore accounts in 90 seconds.</em></p><p>The CISO froze mid-sentence: “They’re inside our payment rails.”<br>SOC analysts scrambled. Firewalls showed no breaches. Endpoint sensors slept. Fraud systems stayed silent. <em>The intruders were ghosts.</em></p><p>Panic spread: <em>“How? SWIFT logs are clean! Auth logs show zero compromises!”</em><br>Regulatory sirens loomed: GDPR fines, revoked banking licenses, global headlines.</p><p>Then, Elena Kovac, a lead infrastructure engineer, stormed into the SOC.<br><em>“Forget perimeter logs. Pull the</em> <em>Kubernetes audit logs.</em>”</p><p>Eyeballs rolled. <em>Containers? During a heist?</em><br>But Elena knew: modern attackers <em>live</em> in blind spots.</p><p>She tore into the K8s audit trail. <em>There:</em></p><pre>{&quot;timestamp&quot;:&quot;03:15:11.422Z&quot;,&quot;verb&quot;:&quot;create&quot;,&quot;object&quot;:&quot;pod&quot;,  <br>&quot;user&quot;:{&quot;username&quot;:&quot;svc-payment-processor&quot;},  <br>&quot;sourceIPs&quot;:[&quot;10.8.22.107&quot;],  <br>&quot;namespace&quot;:&quot;prod-payments&quot;}  </pre><p>The smoking gun:<br>An attacker hijacked a <em>service account</em> (svc-payment-processor) from a legacy dev namespace. They’d spun up a malicious pod, bypassing all controls.</p><p>Within minutes:</p><ul><li>SOC traced the IP to a hijacked CI/CD server</li><li>Fraud teams reversed transfers</li><li>Engineers severed the attacker’s access</li></ul><p>The bank was saved. The logs? They’d recorded the crime in invisible ink.</p><p><strong>What is a Log?</strong><br> A <em>log</em> is a record of events, activities, or system states generated by software, hardware, or network devices.</p><p>For <strong>developers and sysadmins</strong>, logs are essential for troubleshooting issues, monitoring performance, and debugging applications.</p><p>For <strong>SOC and SIEM analysts</strong>, logs are the foundation for security visibility, threat detection, and regulatory compliance.</p><p><strong>Goal of this Article</strong><br>To explore the <em>full lifecycle of logs</em> — from their generation and collection, through processing and storage, to their transformation into actionable intelligence for SOC and SIEM analysis.</p><h3>Anatomy of Logs</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7cc06d343e2b4eec5d8339dea0dc5551/href">https://medium.com/media/7cc06d343e2b4eec5d8339dea0dc5551/href</a></iframe><h3>Common Log Formats</h3><p>Some of the widely used log formats are</p><h4>1. Plain Text (Unstructured)</h4><p>Plain text logs are human-readable logs, but they are hard to parse at scale. Example: Apache Web Server</p><pre>192.168.1.1 - - [15/May/2024:14:22:03 +0000] &quot;GET /admin.php HTTP/1.1&quot; 404 232</pre><h4>2. JSON (Structured)</h4><p>JSON logs are machine-friendly logs with defined key-value pairs that make them easy to parse. Example: Application Logs</p><pre>{<br>  &quot;timestamp&quot;: &quot;2024-05-15T14:22:03.451Z&quot;,<br>  &quot;service&quot;: &quot;payment-gateway&quot;,<br>  &quot;level&quot;: &quot;ERROR&quot;,<br>  &quot;message&quot;: &quot;Failed to process transaction TXN-8821: Insufficient funds&quot;<br>}</pre><h4>3. Syslog (Standardized for Infrastructure)</h4><p>They are used by firewalls, routers, and Linux systems.</p><pre>&lt;34&gt;1 2024-05-15T14:22:03Z firewall01 %ASA-6-302013: Teardown TCP connection 12345 for dmz:192.168.1.1/443 to internal:10.0.0.2/5567</pre><h3>Real-World Log Examples</h3><h4>Application Logs</h4><p>They are used to debug, monitor applications. <br>Example: A crashing microservice</p><pre>{<br>  &quot;level&quot;: &quot;FATAL&quot;,<br>  &quot;timestamp&quot;: &quot;2024-05-15T14:22:03Z&quot;,<br>  &quot;thread&quot;: &quot;main&quot;,<br>  &quot;logger&quot;: &quot;com.quantumbank.PaymentService&quot;,<br>  &quot;message&quot;: &quot;Database deadlock on account_id=88042&quot;<br>}</pre><h4>Web Server Logs</h4><p>They are used to detect brute force attacks or other server attacks. Example: Nginx Server Logs</p><pre>45.33.12.88 - - [15/May/2024:14:22:03 +0000] &quot;POST /login HTTP/1.1&quot; 401 123 &quot;Mozilla/5.0 (compatible; EvilBot/1.0)&quot;</pre><h4>Security Event Logs</h4><p>They are used to spot the lateral movements in windows.</p><pre>&lt;Event xmlns=&quot;http://schemas.microsoft.com/win/2004/08/events/event&quot;&gt;<br>  &lt;System&gt;<br>    &lt;EventID&gt;4625&lt;/EventID&gt; &lt;!-- Failed login --&gt;<br>    &lt;Computer&gt;DC01.quantumbank.local&lt;/Computer&gt;<br>  &lt;/System&gt;<br>  &lt;EventData&gt;<br>    &lt;Data Name=&quot;TargetUserName&quot;&gt;admin&lt;/Data&gt;<br>    &lt;Data Name=&quot;IpAddress&quot;&gt;192.168.1.45&lt;/Data&gt;<br>  &lt;/EventData&gt;<br>&lt;/Event&gt;</pre><h3>The Log Lifecycle</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*17mlECVJ_w6LblinYcBFgw.png" /><figcaption>Log Lifecycle</figcaption></figure><h3><strong>Stage 1 — Generation</strong></h3><p>Logs are born when an event happens — whether that’s a web request hitting a server, a user logging into a system, or a process executing on a machine. The moment it’s recorded, the <em>log lifecycle</em> begins.</p><p><strong>Developer / Sysadmin Perspective</strong></p><p><strong>What it means:</strong><br> You intentionally add logging to applications, configure logging in operating systems, and enable logging in network devices.</p><p><strong>Why it matters:</strong><br> Helps you <strong>debug issues</strong>, <strong>track performance</strong>, and <strong>understand user behavior</strong>.</p><ul><li><strong>Example:</strong><br>Let’s say you’re running a web application. When a user logs in, the application writes an application log entry.</li></ul><pre>2025-08-15 14:05:22 [INFO] user_login - username=&quot;admin&quot; ip=&quot;203.0.113.45&quot; status=&quot;FAILED&quot;</pre><p><strong>What the developer sees:</strong></p><ul><li>A simple record of a failed login.</li><li>Useful for debugging (e.g., user mistyped password).</li><li>Helps track user activity.</li></ul><p><strong>Why it matters to them:</strong></p><ul><li>If there’s a spike instatus=&quot;FAILED&quot;, it may indicate an application bug or a UX problem.</li></ul><p><strong>SOC / SIEM Analyst Perspective</strong></p><ul><li><strong>What it means:</strong><br> Every log is a <strong>potential clue</strong> in detecting suspicious activity.</li><li><strong>Why it matters:</strong><br> You rely on <em>data sources</em> — logs from applications, servers, and network devices — to <strong>hunt threats</strong> and detect incidents.</li><li><strong>Example:</strong><br>The same login Failed Log from the perspective of a SOC/SIEM Analyst</li></ul><p><strong>SOC analysis:</strong></p><ul><li>Multiple FAILED logins for username=&quot;admin&quot; from the same IP (203.0.113.45) within a short time could indicate a <strong>brute-force attack</strong>.</li></ul><p>The SOC can <strong>correlate</strong> this with other logs:</p><ul><li>Web server logs showing requests from 203.0.113.45</li><li>Firewall logs showing repeated connection attempts</li><li>Windows Event ID 4625 entries for failed logins on backend servers</li></ul><p><strong>What Happens If Developers Don’t Add This Log?</strong></p><p>If the app <em>only</em> logs “Login failed” without the IP, username, or timestamp:</p><pre>Login failed.</pre><p><strong>Developer impact:</strong> Still enough to know something failed, but not enough to diagnose who or where from.</p><p><strong>SOC impact:</strong> The attack goes undetected or can’t be traced back to the source. There is no IP to block, and no account to investigate.</p><h3>Stage 2— Collection</h3><p>Once logs are generated, the next step is <strong>collecting them</strong> so they don’t stay scattered across servers, applications, or devices.</p><p>Log collection can be broadly classified into two main categories</p><h4><strong>1. Manual Collection</strong></h4><p>Manual log collection requires developers or system administrators to physically access servers to inspect log files and the Windows Event Viewer. This approach is inefficient for applications distributed across multiple servers and increases the risk of overlooking critical events. There is also the risk that logs may be overwritten or deleted before they can be reviewed.</p><h4>2. Automated Collection with Log Shippers</h4><p>Log shippers/agents automatically collect and forward logs to a central location. Examples: filebeat, fluentd, winlogbeat.<br><strong>General workflow:</strong></p><ul><li>Application writes the failed login entry</li><li>Filebeat/Fluentd reads the log file</li><li>Ships it in near real-time to Elasticsearch, Logstash, or Splunk</li><li>SOC/SIEM now sees the failed login attempt alongside all other logs.</li></ul><h4>Incident Scenario: Missing Logs in Centralized Collection</h4><h4>Background</h4><p>A company runs a Kubernetes-based application with multiple microservices:</p><ul><li>auth-service → handles logins</li><li>payment-service → handles payments</li><li>notification-service → sends emails/SMS</li><li>reporting-service → generates analytics</li></ul><p>All microservices are configured to ship logs to the central SIEM via Filebeat.</p><p>The <strong><em>reporting-service</em> </strong>team rolled out a new version to Kubernetes, but forgot to configure Filebeat on the new pods. Logs from <strong><em>reporting-service </em></strong>were never collected. Neither the SOC team nor the developers team didn’t noticed immediately because other services were still shipping logs.</p><h4>The Impact</h4><p><strong>From SOC Team Perspective:</strong></p><ul><li>SOC is monitoring <strong>failed login alerts</strong> and <strong>payment anomalies</strong>.</li><li>Attackers try <strong>credential stuffing</strong> targeting reporting dashboards.</li><li>Alerts <strong>did not trigger</strong> because the reporting-service logs were missing.</li><li>SOC only sees partial activity (other services), so the brute-force pattern is <strong>incomplete</strong>.</li><li>Detection was delayed → potential breach risk increased.</li></ul><p><strong>From Developer Team Perspective:</strong></p><ul><li>Users report <strong>reports failing intermittently</strong>.</li><li>Developers check centralized logs:</li><li>Nothing shows in Kibana/Elasticsearch for reporting-service.</li><li>Root Cause Analysis (RCA) is <strong>delayed</strong>.</li><li>Regression or errors are not noticed because developers rely on <strong>central dashboards</strong> for monitoring.</li><li>Developers start investigating the wrong services, wasting time.</li></ul><h4>Discovery and Fix</h4><ul><li>A junior engineer notices that logs for reporting-service <strong>never appear</strong> in Kibana.</li><li>Investigation shows <strong>Filebeat was not deployed on the new pods</strong>.</li><li>They fix the configuration:</li></ul><pre># Filebeat config for reporting-service<br>filebeat.inputs:<br>- type: log<br>  paths:<br>    - /var/log/reporting-service/*.log<br>output.elasticsearch:<br>  hosts: [&quot;http://siem-collector:9200&quot;]</pre><ul><li>Redeploy Filebeat on reporting-service pods.</li><li>Logs now stream into the central SIEM in <strong>real-time</strong>.</li></ul><h4>Outcome After Fix</h4><h4>SOC Team:</h4><ul><li>Previously missed brute-force login attempts are now visible.</li><li>Alerts trigger correctly:</li></ul><pre>ALERT: Brute Force Attempt<br>- IP: 203.0.113.45<br>- Service: reporting-service<br>- Failed logins: 6 in 5 min</pre><ul><li>SOC can correlate events across all microservices and <strong>respond faster</strong>.</li></ul><h4>Developer Team:</h4><ul><li>Developers can see all errors from reporting-service.</li><li>RCA is completed quickly.</li><li>Regression or errors are now <strong>visible in dashboards</strong>, preventing further user impact.</li></ul><h3>Stage 3— Aggregation</h3><p>Once logs are collected from various sources, the next challenge is <strong>bringing them together into a unified system</strong>. This process is known as <strong>log aggregation</strong> — merging logs from multiple services, servers, network devices, and cloud resources into a <strong>centralized data store</strong> for analysis and monitoring.</p><p>Logs are often scattered and inconsistent. Without aggregating them, developers cannot trace a problem across the microservices. SOC teams may miss correlated security events, like an attacker probing multiple services. Compliance reporting becomes fragmented and error-prone. Aggregation provides a single pane of glass for all logs and also provides a foundation for normalization, enrichment, and correlation.</p><h3>Scenario</h3><p>You are tasked with collecting logs from:</p><ol><li><strong>Microservices</strong> running in Kubernetes / Docker</li><li><strong>AWS services</strong> (CloudTrail, CloudWatch, S3, Lambda)</li><li><strong>Windows Servers</strong> (Event Logs, Sysmon)</li><li><strong>Active Directory</strong> (Domain Controller logs, login events)</li></ol><p>Goal: <strong>Aggregate all logs into a central SIEM (Splunk / ELK)</strong> for analysis, correlation, and alerting.</p><p>In order to achieve this, we have to identify log sources and formats. Different sources require different shippers/agents, but the goal is centralization.</p><p>This can be achieved for example</p><p><strong>Microservices (Kubernetes)</strong></p><ul><li>Use <strong>Filebeat or Fluent Bit</strong> to tail /var/log or container stdout.</li><li>Tag logs with service_name, pod_name, and namespace.</li></ul><pre>filebeat.inputs:<br>- type: container<br>  paths:<br>    - /var/lib/docker/containers/*/*.log<br>  tags: [&quot;k8s&quot;, &quot;microservice&quot;]<br>output.logstash:<br>  hosts: [&quot;logstash.company.local:5044&quot;]</pre><p><strong>AWS Logs</strong></p><ul><li>CloudTrail, CloudWatch, and S3 logs shipped using <strong>Fluentd / CloudWatch Agent</strong>.</li><li>Convert to structured JSON and forward to central SIEM.</li></ul><pre>&lt;source&gt;<br>  @type cloudwatch_logs<br>  log_group_name /aws/lambda/*<br>  region us-east-1<br>  tag aws.lambda<br>&lt;/source&gt;<br><br>&lt;match aws.**&gt;<br>  @type forward<br>  &lt;server&gt;<br>    host logstash.company.local<br>    port 5044<br>  &lt;/server&gt;<br>&lt;/match&gt;</pre><p><strong>Windows Servers &amp; Active Directory</strong></p><ul><li>Use <strong>Winlogbeat</strong> to collect Application, Security, and System logs.</li><li>Optional: Sysmon logs for detailed process and network events.</li></ul><pre>winlogbeat.event_logs:<br>  - name: Security<br>    ignore_older: 72h<br>  - name: System<br>  - name: Application<br>output.logstash:<br>  hosts: [&quot;logstash.company.local:5044&quot;]</pre><p><strong>Aggregation Best Practices</strong></p><ol><li><strong>Metadata is Key:</strong> Include service name, host, environment, region, device ID</li><li><strong>Reliable Transport:</strong> Use TCP or message queues (Kafka/RabbitMQ) to prevent log loss</li><li><strong>Structured Logging First:</strong> Wherever possible, log JSON instead of free text</li><li><strong>Buffering:</strong> Enable disk queues in Logstash/Fluentd to handle spikes</li><li><strong>Monitoring:</strong> Set alerts for missing logs or inactive sources</li><li><strong>Security:</strong> Encrypt logs in transit (TLS) and restrict access</li></ol><h3>Stage 4— Normalization</h3><p>This is the process of <strong>parsing logs into a common, structured schema</strong>, so that diverse data can be queried, analyzed, and correlated efficiently.</p><p>Logs from the different sources are different in the format for example:</p><ul><li><strong>Web servers:</strong> Nginx access logs (127.0.0.1 - - [29/Aug/2025:22:00:00] &quot;GET /login HTTP/1.1&quot; 401)</li><li><strong>Application logs:</strong> JSON entries ({&quot;timestamp&quot;:&quot;2025-08-29T22:00:00Z&quot;,&quot;user&quot;:&quot;admin&quot;,&quot;event&quot;:&quot;login_failed&quot;})</li><li><strong>Windows Event Logs:</strong> Event ID 4625, structured differently than Linux logs</li></ul><p>Without normalization:</p><ul><li>SOC analysts cannot <strong>correlate events across systems</strong>.</li><li>Developers cannot <strong>search across microservices consistently</strong>.</li><li>Automated alerts may <strong>miss patterns</strong>, since fields like username, source IP, or event type differ by source.</li></ul><p>Let’s dig deeper into how we can normalize the logs:</p><ol><li><strong>Log Collections</strong></li></ol><p>We have logs from the various sources and in different formats such as <br>a. Web App Log:</p><pre>{<br>  &quot;timestamp&quot;: &quot;2025-08-29T22:05:12Z&quot;,<br>  &quot;user&quot;: &quot;admin&quot;,<br>  &quot;event&quot;: &quot;login_failed&quot;,<br>  &quot;ip&quot;: &quot;203.0.113.45&quot;,<br>  &quot;service&quot;: &quot;auth-service&quot;<br>}</pre><p>b. Nginx Access Log (Plain Text):</p><pre>203.0.113.45 - - [29/Aug/2025:22:05:15 +0000] &quot;POST /login HTTP/1.1&quot; 401 142 &quot;-&quot; &quot;Mozilla/5.0&quot;</pre><p>c. Windows Security Log (Event ID 4625)</p><pre>Date: 29/08/2025<br>Time: 22:05:18<br>EventID: 4625<br>User: admin<br>Source IP: 203.0.113.45<br>Logon Type: 3<br>Failure Reason: Unknown user name or bad password</pre><p>2.<strong> Define a Normalized Schema</strong></p><p>Normalization usually means mapping log fields to a <strong>common, structured format</strong> so that all events share <strong>standardized keys</strong>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/24b4bdda40dbd5341377ba16f03b26ea/href">https://medium.com/media/24b4bdda40dbd5341377ba16f03b26ea/href</a></iframe><p><strong>Step 3: Map Fields from Raw Logs</strong></p><p>For Web Logs</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/dd9890e20d20355915509b3467a80132/href">https://medium.com/media/dd9890e20d20355915509b3467a80132/href</a></iframe><pre>{<br>  &quot;@timestamp&quot;: &quot;2025-08-29T22:05:12Z&quot;,<br>  &quot;event.action&quot;: &quot;login_failed&quot;,<br>  &quot;user.name&quot;: &quot;admin&quot;,<br>  &quot;source.ip&quot;: &quot;203.0.113.45&quot;,<br>  &quot;host.name&quot;: &quot;auth-service&quot;,<br>  &quot;event.type&quot;: &quot;authentication&quot;,<br>  &quot;log.source&quot;: &quot;web_app&quot;<br>}</pre><p>Using Regex: For Nginx Logs</p><pre>(?&lt;source.ip&gt;\d+\.\d+\.\d+\.\d+) - - \[(?&lt;@timestamp&gt;[^\]]+)\] &quot;POST /login HTTP/1.1&quot; 401 .*</pre><pre>{<br>  &quot;@timestamp&quot;: &quot;2025-08-29T22:05:15Z&quot;,<br>  &quot;event.action&quot;: &quot;login_failed&quot;,<br>  &quot;user.name&quot;: &quot;unknown&quot;,<br>  &quot;source.ip&quot;: &quot;203.0.113.45&quot;,<br>  &quot;host.name&quot;: &quot;nginx&quot;,<br>  &quot;event.type&quot;: &quot;authentication&quot;,<br>  &quot;log.source&quot;: &quot;nginx&quot;<br>}</pre><p><strong>Step 4: Send Normalized Logs to Splunk<br></strong>Those normalized logs can be sent to Splunk via Filebeat or Universal Forwarder. They can be later searched like this</p><pre>index=auth_logs event.action=login_failed | stats count by source.ip, user.name, host.name</pre><p>Normalization <strong>turns heterogeneous logs into structured, unified events</strong>. Parsing, mapping, and optional enrichment ensure <strong>cross-system visibility</strong>.</p><h3>Stage 4 — Storage and Retention</h3><p>It’s about balancing accessibility, cost, and compliance.</p><p><strong>1. Storage Types</strong></p><p><strong>Hot Storage (Short-term)</strong></p><p><strong>Purpose:</strong> Immediate access for analysis, monitoring, alerting, and incident response.</p><p><strong>Characteristics:</strong></p><ul><li>High-speed, frequently queried</li><li>Usually indexed for search (e.g., Elasticsearch, Splunk hot/warm buckets)</li><li>Retention: days to weeks, depending on volume and business needs</li></ul><p><strong>Cold Storage (Long-term)</strong></p><ul><li><strong>Purpose:</strong> Archive logs for compliance, historical analysis, and forensic investigations.</li></ul><p><strong>Characteristics:</strong></p><ul><li>Lower-cost storage (e.g., AWS S3 Glacier, Azure Blob Archive)</li><li>Access is slower, optimized for retention rather than speed</li><li>Retention: months to years, depending on regulations</li></ul><p><strong>2. Retention Policies</strong></p><p>Retention is usually <strong>defined by regulatory, organizational, and operational requirements</strong>:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6d2dcdbc558921080ac86dffb0bb9888/href">https://medium.com/media/6d2dcdbc558921080ac86dffb0bb9888/href</a></iframe><p><strong>Examples</strong></p><p>Elasticsearch / OpenSearch (Hot vs Warm/Cold)</p><pre># Hot node: frequent indexing and search<br>node.attr.data: hot<br># Warm/cold node: optimized for cost, slower access<br>node.attr.data: warm<br>node.attr.data: cold</pre><p>AWS S3</p><pre># Lifecycle rule for S3 bucket storing logs<br>Rules:<br>  - ID: &quot;MoveToGlacier&quot;<br>    Status: &quot;Enabled&quot;<br>    Prefix: &quot;logs/&quot;<br>    Transitions:<br>      - Days: 30<br>        StorageClass: GLACIER<br>    Expiration:<br>      Days: 365</pre><p>Key things to consider</p><ul><li>Encryption at rest and encryption in transit</li><li>Log access to logs themselves to meet compliance requirements.</li><li>Only authorized Devs/SOC analysts can query hot or cold storage.</li></ul><h3>Stage 5— Analysis</h3><p>Once logs are stored and accessible, the next step is <strong>extracting actionable insights</strong>. Analysis is where raw data becomes <strong>meaningful intelligence</strong> for both developers and SOC teams.</p><p>1. <strong>Developer / Sysadmin Perspective</strong></p><p><strong>Goal:</strong> Debugging, performance monitoring, and troubleshooting.</p><p><strong>Examples of use cases:</strong></p><ul><li>Identify the root cause of failed login attempts or API errors.</li><li>Monitor latency or throughput across microservices.</li><li>Detect resource bottlenecks (CPU, memory, I/O) using logs from containers or hosts.</li></ul><p><strong>Typical metrics &amp; KPIs:</strong></p><ul><li>Error rates per service (event.action=error)</li><li>Response time distributions for APIs (http.response_time)</li><li>Service availability (host.status=up/down)</li></ul><p><strong>Workflow Example (ELK Stack):</strong></p><ol><li>Query aggregated logs in Kibana:</li></ol><pre>GET /auth-service-*/_search<br>{<br>  &quot;query&quot;: {<br>    &quot;match&quot;: {<br>      &quot;event.action&quot;: &quot;login_failed&quot;<br>    }<br>  }<br>}</pre><p>2. Visualize trends in <strong>dashboards</strong> (failed logins over time per microservice).</p><p>3. Correlate with <strong>performance logs</strong> to see if failures are tied to latency spikes.</p><p><strong>SOC Perspective</strong></p><p><strong>Goal:</strong> Threat detection, incident response, and compliance monitoring.</p><p><strong>Examples of use cases:</strong></p><ul><li>Detect brute-force login attempts across multiple services and systems.</li><li>Spot suspicious lateral movement (Windows + Active Directory events).</li><li>Monitor anomalous activity from POS systems or IoT devices.</li></ul><p><strong>Typical detection techniques:</strong></p><ul><li>Correlate source.ip across web apps, Windows, and AD logs.</li><li>Track user.name attempting logins on multiple endpoints.</li><li>Use anomaly detection or threshold-based alerts.</li></ul><p><strong>Workflow Example (Splunk):</strong></p><ol><li>Run a correlation search:</li></ol><pre>index=auth_logs OR index=windows_logs event.action=login_failed<br>| stats count by source.ip, user.name<br>| where count &gt; 5</pre><p>2. Trigger alerts for <strong>suspicious activity</strong>.</p><p>3. SOC analysts use dashboards to <strong>investigate alerts</strong>, pivot to other correlated logs, and start incident response.</p><p><strong>Scenario:</strong> Failed login attempts on auth-service are observed in hot storage.</p><p><strong>Developer view:</strong></p><ul><li>Kibana dashboard shows an error spike on auth-service pods → root cause: misconfigured load balancer.</li></ul><p><strong>SOC view:</strong></p><ul><li>Splunk search reveals the same source.ip failed login attempts on Windows servers and AD → flagged as potential brute-force attack → alert triggered → incident investigation initiated.</li></ul><h3>Stage 6— Archival &amp; Disposal</h3><p>Once logs have been analyzed and their retention period in hot or cold storage is approaching, the final step is <strong>archival and secure disposal</strong>. This ensures logs are retained <strong>as long as necessary for compliance or auditing</strong> but are securely removed when no longer required.</p><p><strong>1. Archival</strong></p><p><strong>Purpose:</strong> Preserve logs for long-term retention, forensic investigation, and compliance reporting.</p><p><strong>Characteristics of archival storage:</strong></p><ul><li>Cost-effective, low-access storage (e.g., AWS S3 Glacier, Azure Blob Archive)</li><li>Immutable storage options to prevent tampering</li><li>Indexed or tagged for retrieval if required</li></ul><p><strong>2. Secure Disposal / Deletion</strong></p><p><strong>Purpose:</strong> Ensure expired logs are <strong>permanently removed</strong> to comply with data protection laws and minimize security risk.</p><p><strong>Considerations:</strong></p><ul><li>Ensure compliance with regulations (GDPR, HIPAA, PCI DSS).</li><li>Verify that backups or replicated copies are also deleted.</li><li>Audit deletion events for accountability.</li></ul><p><strong>Examples:</strong></p><ul><li><strong>Linux Secure Deletion (shred / srm)</strong></li></ul><pre>shred -u /var/log/old_app_logs.log</pre><ul><li><strong>AWS S3 Secure Deletion (Versioned Bucket with MFA Delete)</strong></li></ul><pre>aws s3api delete-object --bucket my-logs --key logs/old_log.json --version-id &lt;v</pre><p><strong>From Development to SOC — The Overlap</strong></p><p><strong>Developers/sysadmins</strong> and <strong>SOC analysts often view logs differently</strong>, but their goals are intertwined. Better collaboration ensures logs are <strong>useful for both debugging and security monitoring</strong>.</p><p>1<strong>. How Developers / Sysadmins Can Write Better Logs for SOC</strong></p><p>Logs are not just for troubleshooting — they are <strong>critical for detecting and investigating security events</strong>. Developers can improve logs by focusing on the following:</p><h4>a) Include Context</h4><ul><li>Provide <strong>enough information to understand the event</strong> without ambiguity.</li><li>Example: Instead of logging &quot;Login failed&quot;, include:</li></ul><pre>{<br>  &quot;event&quot;: &quot;login_failed&quot;,<br>  &quot;user.name&quot;: &quot;jdoe&quot;,<br>  &quot;source.ip&quot;: &quot;203.0.113.45&quot;,<br>  &quot;service&quot;: &quot;auth-service&quot;,<br>  &quot;reason&quot;: &quot;invalid password&quot;,<br>  &quot;timestamp&quot;: &quot;2025-08-29T22:45:12Z&quot;<br>}</pre><ul><li>SOC benefits: Enables correlation across systems and faster incident investigation.</li></ul><p>b) <strong>Use Structured Formats</strong></p><ul><li>Prefer <strong>JSON, key-value pairs, or CEF/ECS formats</strong> over free-text logs.</li><li>Example:</li></ul><pre>{<br>  &quot;@timestamp&quot;: &quot;2025-08-29T22:46:10Z&quot;,<br>  &quot;event.action&quot;: &quot;file_access&quot;,<br>  &quot;user.name&quot;: &quot;alice&quot;,<br>  &quot;file.path&quot;: &quot;/confidential/data.csv&quot;,<br>  &quot;host.name&quot;: &quot;webserver-01&quot;,<br>  &quot;log.source&quot;: &quot;application&quot;<br>}</pre><ul><li>Structured logs allow SIEMs to <strong>parse, normalize, and correlate efficiently</strong>.</li></ul><p>c) Avoid Sensitive Data Leakage</p><ul><li>Do <strong>not log passwords, tokens, or PII</strong> in plaintext.</li><li>Use anonymization or hashing where necessary:</li></ul><pre>&quot;user.email_hash&quot;: &quot;f1a2c3d4e5...&quot;</pre><ul><li>Protects sensitive information while keeping events useful for SOC.</li></ul><p><strong>How SOC Can Help Developers Understand Logging Importance</strong></p><p>SOC teams can guide developers to produce <strong>actionable, security-friendly logs</strong>:</p><p><strong>Feedback Loops:</strong></p><ul><li>SOC analysts highlight which log fields are most helpful for detecting threats.</li><li>Example: SOC requests source.ip and user.role be added to authentication logs.</li></ul><p><strong>Standardization Guidelines:</strong></p><ul><li>Define <strong>common schemas</strong> for microservices, Windows, and cloud logs (e.g., ECS, CEF).</li></ul><p><strong>Threat Awareness:</strong></p><ul><li>Show developers how missing logs can <strong>hide security incidents</strong> or delay detection.</li><li>Example: Not logging failed API calls across microservices could delay brute-force attack detection.</li></ul><p><strong>Joint Playbooks:</strong></p><p>Developers and SOC create logging <strong>playbooks</strong> that define:</p><ul><li>Which events to log</li><li>Which fields are mandatory</li><li>Retention and sensitivity considerations</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=95072556b234" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Golang Interview: Array]]></title>
            <link>https://medium.com/@kiruu1238/golang-interview-array-d6e0237d0a13?source=rss-b0ae211f548d------2</link>
            <guid isPermaLink="false">https://medium.com/p/d6e0237d0a13</guid>
            <category><![CDATA[golang-tutorial]]></category>
            <category><![CDATA[arrays]]></category>
            <category><![CDATA[interview]]></category>
            <category><![CDATA[go-slices]]></category>
            <category><![CDATA[golang]]></category>
            <dc:creator><![CDATA[Kiran Adhikari]]></dc:creator>
            <pubDate>Sat, 23 Aug 2025 03:18:16 GMT</pubDate>
            <atom:updated>2025-08-23T03:18:16.058Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IS_x9KkyzqVqyxcFvcfEow.png" /></figure><p>In Go, an array is a fixed-size sequence of elements of the same type. The size of an array is part of its type, so you cannot change the size of an array once it is defined. The general syntax for declaring an array is:</p><pre>var arrayName [size]ElementType</pre><p>Here’s a brief explanation of the components:</p><ul><li>arrayName: The name of the array.</li><li>size: The number of elements in the array. This must be a constant expression.</li><li>ElementType: The type of elements that the array will store.</li></ul><p>Here’s an example of declaring and initializing an array:</p><pre>package main<br><br>import &quot;fmt&quot;<br><br>func main() {<br>    // Declare an array of integers with a size of 3<br>    var numbers [3]int<br><br>    // Initialize the elements of the array<br>    numbers[0] = 1<br>    numbers[1] = 2<br>    numbers[2] = 3<br><br>    // Access and print the elements<br>    fmt.Println(&quot;Element 0:&quot;, numbers[0])<br>    fmt.Println(&quot;Element 1:&quot;, numbers[1])<br>    fmt.Println(&quot;Element 2:&quot;, numbers[2])<br>}</pre><p>In this example, we declared an array named numbers with a size of 3 and type int. We then initialized the elements of the array and printed their values.</p><p>Arrays in Go are zero-indexed, meaning the index of the first element is 0, the second element is 1, and so on. The last element’s index is size - 1.</p><p>Arrays can also be initialized during declaration:</p><pre>package main<br><br>import &quot;fmt&quot;<br><br>func main() {<br>    // Declare and initialize an array of integers<br>    numbers := [3]int{1, 2, 3}<br><br>    // Access and print the elements<br>    fmt.Println(&quot;Element 0:&quot;, numbers[0])<br>    fmt.Println(&quot;Element 1:&quot;, numbers[1])<br>    fmt.Println(&quot;Element 2:&quot;, numbers[2])<br>}</pre><p>numbers := [...]int{1, 2, 3, 4, 5}</p><p>In this example, we used a short syntax to declare and initialize the array in a single line.</p><p>One important thing to note is that working with arrays in Go is not as common as working with slices, which are more flexible and dynamic. Arrays are used in situations where a fixed size is known at compile time. If you need a more dynamic data structure, slices are usually preferred.</p><h3>What is the zero value of an array in Go?</h3><p>In Go, the zero value of an array is an array where each element is set to its respective zero value based on the element’s type. The zero value for numeric types (int, float, etc.) is 0; for strings, it is an empty string (&quot;&quot;), and for boolean types it is false.</p><p>Here’s an example:</p><pre>package main<br><br>import &quot;fmt&quot;<br><br>func main() {<br>    // Declare an array without explicitly initializing it<br>    var numbers [5]int<br><br>    // Print the array, showing its zero values<br>    fmt.Println(numbers) // Output: [0 0 0 0 0]<br>}</pre><p>In this example, the numbers array is declared but not explicitly initialized. As a result, each element of the array is set to its zero value, which, in the case of integers, is 0. If the array contained elements of a different type, each element would be set to its corresponding zero value.</p><h3>Can the size of an array be changed after it is declared?</h3><p>No, the size of an array in Go cannot be changed after it is declared. The size of an array is fixed at the time of declaration, and it cannot be resized or modified during the program’s execution.</p><p>For example, consider the following array declaration:</p><pre>var numbers [5]int</pre><p>In this case, the array numbers has a fixed size of 5 integers. You cannot change this size later in the program.</p><p>If dynamic resizing is required, slices are more suitable in Go. Slices are a more flexible and dynamic data structure compared to arrays. Unlike arrays, slices do not have a fixed size, and their size can be dynamically adjusted using built-in functions like append. Slices are often preferred when you need a collection with a variable size.</p><p>Here’s an example of using a slice:</p><pre>package main<br><br>import &quot;fmt&quot;<br><br>func main() {<br>    // Declare a slice<br>    var numbers []int<br><br>    // Append elements to the slice<br>    numbers = append(numbers, 1, 2, 3, 4, 5)<br><br>    // Print the slice<br>    fmt.Println(numbers) // Output: [1 2 3 4 5]<br>}</pre><p>In this example, the slice numbers can dynamically grow or shrink as elements are appended or removed.</p><h3>What is the significance of the array size being part of its type?</h3><p>In Go, the size of an array is considered part of its type, and this has several implications:</p><ol><li><strong>Type Safety:</strong> The size of an array is part of its type, so arrays with different sizes are distinct types. This enhances type safety, preventing inadvertent assignments or operations between arrays of different sizes. For example, [5]int and [10]int are distinct types, and you cannot assign one to the other directly.</li><li><strong>Compile-Time Checks:</strong> The size being part of the type allows the Go compiler to perform size checks at compile time. This helps catch potential errors, such as array index out-of-bounds errors before the program is executed.</li><li><strong>Memory Layout:</strong> The size of an array is used to determine its<em> memory layout</em>. Each element in the array occupies a contiguous block of memory, and the size information is crucial for calculating memory offsets. This results in more efficient memory access, as the compiler can compute the exact memory address of each element based on the size.</li><li><strong>Fixed Memory Footprint:</strong> Arrays have a fixed and known memory footprint at compile time, which contributes to predictable memory usage. The fixed size ensures that the memory required for an array is determined statically, which can be an advantage in resource-constrained environments.</li><li><strong>Performance:</strong> Because the size of an array is known at compile time, the compiler can optimize certain operations and generate more efficient machine code. For instance, loops over arrays can be unrolled, and memory access patterns can be optimized based on the fixed size.</li></ol><p>Here’s an example illustrating the type safety aspect:</p><pre>package main<br><br>import &quot;fmt&quot;<br><br>func main() {<br>    var arr1 [5]int<br>    var arr2 [10]int<br><br>    // This assignment is not allowed because arr1 and arr2 are of different types<br>    // arr1 = arr2 // Compilation error<br><br>    fmt.Println(arr1, arr2)<br>}</pre><p>In this example, attempting to assign arr2 to arr1 results in a compilation error because [5]int and [10]int are distinct types due to their different sizes.</p><h3>Explain the main differences between arrays and slices in Go.</h3><p>Arrays and slices are both composite data types in Go, but they have key differences in terms of size, flexibility, and use cases:</p><ol><li><strong>Size:</strong></li></ol><ul><li><strong>Arrays:</strong> Have a fixed size that is determined at compile time. The size is part of the array’s type, and once declared, it cannot be changed.</li><li><strong>Slices:</strong> Are dynamic and can grow or shrink during runtime. The size of a slice is not fixed and is managed by the underlying array.</li></ul><p><strong>2. Declaration:</strong></p><ul><li><strong>Arrays:</strong> Declared with a fixed size during compile time. For example, [5]int declares an array of integers with size 5.</li><li><strong>Slices:</strong> Declared without specifying a size. For example, []int declares a slice of integers.</li></ul><p><strong>3. Initialization:</strong></p><ul><li><strong>Arrays:</strong> Must be initialized with all elements at the time of declaration. For example, arr := [3]int{1, 2, 3}.</li><li><strong>Slices:</strong> Can be initialized using a slice expression or by converting an array or another slice. For example, s := []int{1, 2, 3}.</li></ul><p><strong>4. Flexibility:</strong></p><ul><li><strong>Arrays:</strong> Have a fixed size, which limits their flexibility. Changing the size requires modifying the source code and may affect other parts of the program.</li><li><strong>Slices:</strong> Are dynamic and provide more flexibility. They can be resized using the append function and can represent a portion of an existing array.</li></ul><p><strong>5. Passing to Functions:</strong></p><ul><li><strong>Arrays:</strong> When passed to a function, the entire array is copied, which can be inefficient for large arrays.</li><li><strong>Slices:</strong> Are more efficient to pass to functions because they are lightweight and only contain a reference to the underlying array.</li></ul><p><strong>6. Underlying Data:</strong></p><ul><li><strong>Arrays:</strong> Directly contain their elements in a contiguous block of memory.</li><li><strong>Slices:</strong> Reference a contiguous section of an underlying array</li></ul><p><strong>7. Length and Capacity:</strong></p><ul><li><strong>Arrays:</strong> Have a fixed length that is part of the type.</li><li><strong>Slices:</strong> Have a length and capacity. The length is the number of elements in the slice, and the capacity is the maximum number of elements it can hold without resizing.</li></ul><h3>When would you choose to use an array over a slice, and vice versa?</h3><p>The choice between using an array or a slice in Go depends on the specific requirements and characteristics of the data structure. Here are some considerations for choosing between arrays and slices:</p><h4>Use Arrays When:</h4><ol><li><strong>Fixed Size:</strong></li></ol><ul><li>When the size of the collection is known and fixed at compile time.</li><li>Example: Storing RGB values for each pixel in an image where the image dimensions are known.</li></ul><p><strong>2. Memory Efficiency:</strong></p><ul><li>When a compact, fixed-size data structure is needed with minimal memory overhead.</li></ul><p><strong>3. Predictable Performance:</strong></p><ul><li>When direct access to elements with fixed indices is crucial and performance is a priority.</li></ul><h4>Use Slices When:</h4><ol><li><strong>Dynamic Size:</strong></li></ol><ul><li>The size of the collection needs to be dynamic and may change during runtime.</li><li>Example: Storing elements in a list that can grow or shrink as needed.</li></ul><p><strong>2. Flexible and Convenient:</strong></p><ul><li>When you want a more flexible, dynamic data structure that can be easily resized.</li><li>Example: Processing variable-length input data.</li></ul><p><strong>3. Function Parameters:</strong></p><ul><li>When passing a portion of a collection to a function without making a full copy is desired.</li><li>Slices are more lightweight and efficient for passing to functions.</li></ul><p><strong>4. Working with Subsets:</strong></p><ul><li>When working with a subset of elements from an existing array or another slice.</li><li>Example: Extracting specific ranges of data from a larger dataset.</li></ul><p><strong>5. Built-in Functions:</strong></p><ul><li>When using built-in functions like append, copy, and len that are specific to slices.</li><li>Slices provide additional functionality compared to arrays.</li></ul><h3>Can you pass an array as a parameter to a function in Go?</h3><p>Yes, you can pass an array as a parameter to a function in Go. When you pass an array to a function, you can specify the array’s type and size in the function signature. Here’s an example:</p><pre>package main<br><br>import &quot;fmt&quot;<br><br>func main() {<br>    // Example array<br>    numbers := [5]int{1, 2, 3, 4, 5}<br><br>    // Call the function and pass the array<br>    modifyArray(numbers)<br><br>    // Print the array after modification<br>    fmt.Println(&quot;Array after modification in main:&quot;, numbers)<br>}<br><br>// Function that modifies the array<br>func modifyArray(arr [5]int) {<br>    for i := 0; i &lt; len(arr); i++ {<br>        arr[i] *= 2<br>    }<br>    fmt.Println(&quot;Array modified in function:&quot;, arr)<br>}</pre><p>In this example, the modifyArray function takes an array of integers [5]int as a parameter. When you pass the numbers array to this function, a copy of the array is made, and modifications made within the function do not affect the original array in the main function.</p><p>It’s important to note that passing an array to a function creates a copy of the array, which may have implications for performance and memory usage, especially with large arrays. If you need to modify the original array, you can pass a pointer to the array instead. This allows the function to work with the original array directly. When working with arrays as function parameters in Go, there are several considerations to keep in mind:</p><ol><li><strong>Passing by Value:</strong> When you pass an array to a function, it is passed by value, meaning that a copy of the entire array is made. This can impact performance and memory usage, particularly for large arrays. If modification of the original array is required, consider passing a pointer to the array.</li></ol><pre>// Passing by value<br>func modifyArray(arr [5]int) {<br>    // Changes here won&#39;t affect the original array<br>}<br><br>// Passing by reference (using a pointer)<br>func modifyArrayByReference(arr *[5]int) {<br>    // Changes here will affect the original array<br>}</pre><p><strong>2. Array Size:</strong> The size of the array is part of its type. This means that functions that operate on arrays are limited to arrays of a specific size. If you want a function to accept arrays of different sizes, you’ll need to define multiple functions or use slices.</p><pre>// Functions for different array sizes<br>func processArrayOfSize5(arr [5]int) {<br>    // ...<br>}<br><br>func processArrayOfSize10(arr [10]int) {<br>    // ...<br>}</pre><ol><li><strong>Slice vs. Array:</strong> If the size of the array is not known at compile time or if you need a dynamic data structure, consider using slices instead of arrays. Slices are more flexible and are often preferred in Go for variable-sized collections.</li><li><strong>Pointer vs. Value:</strong> Decide whether you want to pass the array by value or by reference (using a pointer). Passing by value avoids unintentional modifications, but it incurs the overhead of copying the array. Passing by reference allows modifications but requires careful handling to avoid unintended side effects.</li><li><strong>Performance Considerations:</strong> For large arrays, consider the performance implications of copying the entire array. In some cases, passing a slice or a pointer to the array may be more efficient.</li></ol><h3>How can you create a copy of an array in Go?</h3><p>In Go, you can create a copy of an array by assigning the values of one array to another. Here’s an example:</p><pre>package main<br><br>import &quot;fmt&quot;<br><br>func main() {<br>    // Original array<br>    originalArray := [5]int{1, 2, 3, 4, 5}<br><br>    // Create a copy of the array<br>    copiedArray := originalArray<br><br>    // Modify the copied array<br>    copiedArray[0] = 10<br><br>    // Print both arrays<br>    fmt.Println(&quot;Original Array:&quot;, originalArray)<br>    fmt.Println(&quot;Copied Array:&quot;, copiedArray)<br>}</pre><p>In this example, copiedArray is assigned the values of originalArray, creating a copy. However, it&#39;s important to note that this creates a shallow copy, meaning that the elements themselves are still the same. If the array contains references to other data structures (e.g., arrays, slices), modifications to those elements will be reflected in both the original and copied arrays.</p><p>If you need a deep copy (i.e., completely independent copies of the elements), you may need to iterate through the elements and create new instances or use specific methods/libraries designed for deep copying.</p><p>Keep in mind that for slices, the copy function is commonly used to create a copy. However, for arrays, simple assignment as shown in the example is sufficient due to their fixed size. When copying arrays in Go, there are some considerations and challenges to be aware of:</p><ol><li><strong>Shallow Copy:</strong> Simple assignment (=) creates a shallow copy of the array. If the array contains elements that are references (e.g., slices or other arrays), modifications to those elements will be reflected in both the original and copied arrays. To achieve a deep copy, you may need to manually create new instances of the elements.</li></ol><pre>originalArray := [3][]int{{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}<br>copiedArray := originalArray // Shallow copy</pre><p><strong>2. Fixed Size:</strong> Arrays in Go have a fixed size, and the size is part of their type. When copying arrays, both the original and copied arrays must have the same size. If you need to work with arrays of different sizes, consider using slices or defining functions for different array sizes.</p><pre>func copyArray(original [5]int) [5]int {<br>    copied := original<br>    return copied<br>}</pre><p><strong>3. Performance Impact:</strong> Copying large arrays can have a performance impact, especially if done frequently. In such cases, consider whether a copy is necessary or if alternative data structures, such as slices, might be more suitable.</p><pre>originalArray := [1000000]int{ /* ... */ }<br>copiedArray := originalArray // Potential performance impact for large arrays</pre><p><strong>4. Memory Usage:</strong> Creating copies of large arrays can consume additional memory. If memory usage is a concern, consider whether it’s possible to operate on the original array or use slices with shared underlying arrays.</p><h3>What happens if you try to access an index beyond the bounds of an array in Go?</h3><p>In Go, the length of an array is part of its type, and the size must be specified at compile time. If you attempt to access an index beyond the declared length of the array, it will result in a compile-time error, not a runtime panic. The Go compiler checks array index bounds at compile time, and if it detects an out-of-bounds access, it will generate an error, preventing the program from being compiled.</p><p>Here’s an example that will not compile due to an out-of-bounds access:</p><pre>package main<br><br>import &quot;fmt&quot;<br><br>func main() {<br>    // Creating an array with three elements<br>    myArray := [3]int{1, 2, 3}<br><br>    // Attempting to access an index beyond the bounds of the array<br>    // This will result in a compile-time error<br>    fmt.Println(myArray[5])<br>}</pre><p>Attempting to compile this program will result in an error like:</p><pre>./main.go:10:19: invalid array index 5 (out of bounds for 3-element array)</pre><h3>How are arrays stored in memory in Go?</h3><p>In Go, arrays are stored as contiguous blocks of memory. The memory layout for arrays is straightforward, and each element of the array is stored in a consecutive memory location. The size of each element is determined by its data type.</p><p>Here’s a basic illustration of how an array is stored in memory:</p><pre>+---------------------------------------+<br>| Element 0 | Element 1 | ... | Element N |<br>+---------------------------------------+</pre><p>In this representation:</p><ul><li>Each “Element” represents a single value of the array.</li><li>The memory addresses of the elements are consecutive.</li><li>The size of the array is determined by multiplying the size of each element by the number of elements.</li></ul><p>Go arrays are of fixed size, meaning that the size of the array is specified at the time of declaration and cannot be changed during the program’s execution. This fixed size is part of the array’s type.</p><p>For example, in the following declaration:</p><pre>var numbers [5]int</pre><p>The array numbers has a fixed size of 5, and each element is an integer (int). The memory for this array would be allocated as a block of memory to accommodate five consecutive integers.</p><p>It’s worth noting that the memory layout for arrays is different from slices. Slices, which are more flexible and dynamic, are implemented as data structures that include a pointer to the underlying array, the length of the slice, and the capacity of the slice. The underlying array for a slice may be larger than the visible length of the slice, providing room for future growth.</p><p>When working with arrays in Go, there are several considerations related to memory that developers should be aware of:</p><ol><li><strong>Fixed Size:</strong> Arrays in Go have a fixed size, and this size is part of the array’s type. This means that once an array is declared, its size cannot be changed during runtime. Developers need to choose an appropriate size based on the expected usage and avoid excessive memory allocation.</li></ol><pre>var numbers [5]int</pre><p><strong>2. Contiguous Memory:</strong> Array elements are stored in contiguous memory locations. This can have performance benefits as it allows for efficient memory access and cache utilization. However, it also means that the memory must be allocated as a single block, and the array’s size is determined at compile time.</p><p><strong>3. Value Semantics:</strong> Arrays in Go have value semantics, meaning that when an array is assigned to another variable or passed as a function parameter, a copy of the entire array is created. This can impact memory usage, especially for large arrays. If working with large datasets, slices or other data structures with reference semantics may be more memory-efficient.</p><pre>array1 := [3]int{1, 2, 3}<br>array2 := array1 // Creates a copy of the entire array</pre><h3>Compare and contrast the initialization of arrays and slices in Go.</h3><p>In Go, arrays and slices are both used to store ordered collections of elements, but they have key differences in terms of size, mutability, and initialization.</p><h4>Initialization of Arrays:</h4><ol><li><strong>Syntax:</strong></li></ol><ul><li>Arrays have a fixed size, and the size is part of the type.</li><li>The syntax for initializing an array is [size]elementType.</li></ul><pre>var numbers [5]int          // Array with size 5 and element type int<br>var daysOfWeek [7]string    // Array with size 7 and element type string</pre><p><strong>2. Size:</strong></p><ul><li>The size of an array is fixed at compile time and cannot be changed during runtime.</li><li>The size is an integral part of the array’s type.</li></ul><p><strong>3. Literal Initialization:</strong></p><ul><li>Arrays can be initialized with literal values.</li></ul><pre>primes := [6]int{2, 3, 5, 7, 11, 13}</pre><p><strong>4. Zero Values:</strong></p><ul><li>If specific values are not provided during initialization, array elements are set to their zero values.</li></ul><pre>var zeros [3]int  // All elements are initialized to 0</pre><h4>Initialization of Slices:</h4><ol><li><strong>Syntax:</strong></li></ol><ul><li>Slices are more flexible and dynamic. They are built on top of arrays and are not fixed in size.</li><li>The syntax for creating a slice is []elementType.</li></ul><pre>var numbers []int           // Slice with element type int<br>daysOfWeek := []string{}    // Slice with element type string, initialized as an empty slice</pre><p><strong>2. Size:</strong></p><ul><li>Slices do not have a fixed size and can grow or shrink dynamically during runtime.</li></ul><p><strong>3. Literal Initialization:</strong></p><ul><li>Slices can be initialized using a slice literal without specifying a size.</li></ul><pre>primes := []int{2, 3, 5, 7, 11, 13}</pre><p><strong>4. Zero Values:</strong></p><ul><li>An uninitialized slice has a zero value of nil, indicating that it does not point to any underlying array.</li></ul><pre>var nilSlice []int  // nilSlice is a nil slice</pre><p><strong>5. Dynamic Sizing:</strong></p><ul><li>Slices can be dynamically sized using the make function or by slicing an existing array or slice.</li></ul><pre>dynamicSlice := make([]int, 3, 5)  // A slice with a length of 3 and a capacity of 5</pre><p><strong>6. Appending Elements:</strong></p><ul><li>Slices support appending elements using the append function, allowing them to grow dynamically.</li></ul><pre>numbers = append(numbers, 42)  // Append 42 to the numbers slice</pre><p>In summary, arrays have a fixed size determined at compile time, and their size is part of their type. Slices, on the other hand, are dynamic and can be resized during runtime. Slices are more versatile and commonly used for their flexibility, especially when dealing with collections of variable sizes.</p><h3>Can an array in Go contain elements of different types?</h3><p>In Go, an array is a fixed-size, ordered collection of elements, and all elements in an array must have the same data type. Unlike some dynamically typed languages, Go enforces a strict type system, and arrays are homogeneous, meaning that all elements must be of the same data type.</p><p>For example, the following declaration creates an array of integers:</p><pre>var numbers [5]int</pre><p>In this case, the array named numbers can only store integers, and attempting to assign or initialize it with values of different types would result in a compilation error.</p><pre>// This would result in a compilation error<br>numbers = [5]int{1, 2, &quot;three&quot;, 4, 5}</pre><h3>How can you use the ellipsis (...) in array initialization, and what does it signify?</h3><p>In Go, the ellipsis (...) can be used in array initialization to automatically determine the size of the array based on the number of elements provided. It is especially useful when you want the compiler to infer the size of the array from the number of values you provide.</p><p>Here’s an example:</p><pre>package main<br><br>import &quot;fmt&quot;<br><br>func main() {<br> // Using the ellipsis to infer the array size<br> numbers := [...]int{1, 2, 3, 4, 5}<br><br> // Print the array elements<br> fmt.Println(&quot;Numbers:&quot;, numbers)<br>}</pre><p>In this example, the ellipsis (...) is used in the array declaration to infer the size of the numbers array based on the number of elements provided within the curly braces. The array size is determined to be 5 because there are five elements.</p><p>The use of the ellipsis in this context allows for concise array initialization without explicitly specifying the size. It’s particularly useful when you want the array size to be automatically determined based on the number of initial values.</p><p>Keep in mind that the ellipsis can only be used in array declarations, and it is not valid in slice declarations. Slices do not have a fixed size, and their length is determined dynamically at runtime.</p><h3>Can you compare arrays for equality in Go using the == operator?</h3><p>Yes, you can compare arrays for equality in Go using the == operator. However, there are some considerations to be aware of:</p><ol><li><strong>Arrays Must Have the Same Size:</strong></li></ol><ul><li>Arrays can only be compared for equality if they have the same size. The size is considered part of the array’s type in Go, so arrays of different sizes are distinct types and cannot be directly compared.</li></ul><p><strong>2. Element-wise Comparison:</strong></p><ul><li>When comparing arrays of the same size, the == operator performs an element-wise comparison. Each element of one array is compared to the corresponding element of the other array. The arrays are considered equal if all elements are equal.</li></ul><p>Here’s an example:</p><pre>package main<br><br>import &quot;fmt&quot;<br><br>func main() {<br> // Arrays with the same elements and size<br> array1 := [3]int{1, 2, 3}<br> array2 := [3]int{1, 2, 3}<br><br> // Arrays with the same elements but different size<br> array3 := [3]int{1, 2, 3}<br> array4 := [4]int{1, 2, 3, 4}<br><br> // Compare arrays for equality<br> fmt.Println(&quot;Arrays 1 and 2 are equal:&quot;, array1 == array2) // true<br> fmt.Println(&quot;Arrays 3 and 4 are equal:&quot;, array3 == array4) // false<br>}</pre><h3>Describe the concepts of length and capacity in the context of arrays.</h3><p>In the context of arrays in Go, the concepts of length and capacity are not as explicit or dynamic as they are with slices. However, it’s still relevant to understand the size and capacity of arrays:</p><ol><li><strong>Length:</strong></li></ol><ul><li>The length of an array in Go is a fixed and constant value that represents the number of elements in the array. When you declare an array, you specify its length, and that length cannot be changed during the lifetime of the array.</li></ul><pre>package main<br><br>import &quot;fmt&quot;<br><br>func main() {<br>    // Declare an array with a length of 3<br>    array := [3]int{1, 2, 3}<br><br>    // Length of the array is 3<br>    fmt.Println(&quot;Length of the array:&quot;, len(array)) // Output: 3<br>}</pre><p><strong>2. Capacity (Not Explicit):</strong></p><ul><li>Unlike slices, arrays in Go don’t have an explicit capacity. The capacity of an array is essentially the same as its length since the size is fixed. The distinction between length and capacity is more prominent when working with slices, where the capacity can change dynamically.</li></ul><pre>package main<br><br>import &quot;fmt&quot;<br><br>func main() {<br>    // Declare an array with a length of 3<br>    array := [3]int{1, 2, 3}<br><br>    // Capacity is not explicitly stated for arrays<br>    // It is essentially the same as the length<br>    fmt.Println(&quot;Capacity of the array:&quot;, len(array)) // Output: 3<br>}</pre><p>In practice, when you work with arrays, you typically focus on the fixed size specified during the declaration. The length and capacity concepts become more significant when dealing with slices, where the capacity can change dynamically as elements are appended.</p><p>If you need a dynamic data structure with a varying size, slices are more appropriate in Go. Slices provide a view into an underlying array and offer a length and capacity that can change as elements are added or removed.</p><h3>Explain the difference between an array of pointers and a pointer to an array in Go.</h3><p>In Go, the difference between an array of pointers and a pointer to an array lies in how the memory is structured and how you access elements. Let’s break down each concept:</p><ol><li><strong>Array of Pointers:</strong></li></ol><ul><li>An array of pointers is an array where each element is a pointer. It means that the array stores memory addresses and each element points to another memory location. The elements in the array can be of different types, and they are typically dynamically allocated.</li></ul><pre>package main<br><br>import &quot;fmt&quot;<br><br>func main() {<br>    // Array of pointers to integers<br>    var pointerArray [3]*int<br><br>    // Dynamically allocate memory for integers<br>    num1 := 10<br>    num2 := 20<br>    num3 := 30<br><br>    // Assign the addresses of the integers to the array<br>    pointerArray[0] = &amp;num1<br>    pointerArray[1] = &amp;num2<br>    pointerArray[2] = &amp;num3<br><br>    // Access the values through the pointers<br>    fmt.Println(*pointerArray[0]) // Output: 10<br>    fmt.Println(*pointerArray[1]) // Output: 20<br>    fmt.Println(*pointerArray[2]) // Output: 30<br>}</pre><p><strong>Pointer to an Array:</strong></p><ul><li>A pointer to an array is a single pointer variable that points to the memory address of the first element of an array. It provides a way to access the entire array indirectly through the pointer.</li></ul><pre>package main<br><br>import &quot;fmt&quot;<br><br>func main() {<br>    // Array of integers<br>    array := [3]int{10, 20, 30}<br><br>    // Pointer to the array<br>    var arrayPointer *[3]int<br><br>    // Assign the address of the array to the pointer<br>    arrayPointer = &amp;array<br><br>    // Access the array elements through the pointer<br>    fmt.Println((*arrayPointer)[0]) // Output: 10<br>    fmt.Println((*arrayPointer)[1]) // Output: 20<br>    fmt.Println((*arrayPointer)[2]) // Output: 30<br>}</pre><h3>Discuss whether arrays in Go are considered value types or reference types.</h3><p>Arrays in Go are considered value types. When you assign one array to another or pass an array as a function argument, a copy of the entire array is created. Changes made to the elements of the copied array do not affect the original array, and vice versa.</p><p>Here’s an example to illustrate the value semantics of arrays:</p><pre>package main<br><br>import &quot;fmt&quot;<br><br>func main() {<br>    // Declare and initialize an array<br>    array1 := [3]int{1, 2, 3}<br><br>    // Assign the array to another variable<br>    array2 := array1<br><br>    // Modify an element in the copied array<br>    array2[0] = 99<br><br>    // Print both arrays<br>    fmt.Println(&quot;Original array:&quot;, array1) // Output: [1 2 3]<br>    fmt.Println(&quot;Copied array:&quot;, array2)   // Output: [99 2 3]<br>}</pre><p>In this example, modifying the array2 does not affect the values in the original array1. Each array has its own copy of the data.</p><p>This is in contrast to reference types, like slices and maps, where the reference to the underlying data is shared. Changes made through one reference affect the data seen through other references. The value semantics of arrays make them suitable for scenarios where you want independent copies of data or when you need to ensure that modifications to an array do not impact other parts of the code.</p><h3>Can you use the append function to modify the size of an existing array in Go? - Discuss any considerations or limitations when using append with arrays.</h3><p>No, the append function in Go is used with slices, not arrays. The append function is designed to work with dynamic, resizable data structures like slices, not fixed-size arrays.</p><p>Arrays in Go have a fixed size that is determined at compile-time, and their size cannot be changed once they are declared. If you need a dynamic data structure that can grow or shrink, you should use slices.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d6e0237d0a13" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Golang Interview: Struct]]></title>
            <link>https://medium.com/@kiruu1238/golang-interview-struct-758db20ef4c9?source=rss-b0ae211f548d------2</link>
            <guid isPermaLink="false">https://medium.com/p/758db20ef4c9</guid>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[interview-questions]]></category>
            <category><![CDATA[golang-tutorial]]></category>
            <category><![CDATA[backend]]></category>
            <category><![CDATA[data-structures]]></category>
            <dc:creator><![CDATA[Kiran Adhikari]]></dc:creator>
            <pubDate>Tue, 19 Aug 2025 16:19:13 GMT</pubDate>
            <atom:updated>2025-08-19T16:19:13.465Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EQ8zBFyAUP3JTh5CdUM7mA.png" /><figcaption>struct</figcaption></figure><p>In Go, a struct is a composite data type that groups variables (fields or members) under a single name. They represent a collection of related data fields and are a fundamental building block for organizing and modeling data in Go programs.</p><p><strong>Syntax for Declaring a Struct:</strong></p><pre>// Define a struct named &#39;Person&#39; with fields &#39;Name&#39; and &#39;Age&#39;<br>type Person struct {<br>    Name string<br>    Age  int<br>}</pre><p>In the above example, Person is the name of the struct, and it has two fields: Name of type string and Age of type int.</p><p><strong>Creating Instances of a Struct:</strong></p><pre>// Create an instance of the &#39;Person&#39; struct<br>personInstance := Person{<br>    Name: &quot;John Doe&quot;,<br>    Age:  25,<br>}</pre><p><strong>Accessing Struct Fields:</strong></p><pre>// Accessing and modifying struct fields<br>fmt.Println(personInstance.Name) // Output: John Doe<br>fmt.Println(personInstance.Age)  // Output: 25<br><br>// Modifying a struct field<br>personInstance.Age = 26<br>fmt.Println(personInstance.Age)  // Output: 26</pre><p><strong>Anonymous Structs:</strong></p><p>In Go, you can also create anonymous structs, which are structs without a predefined name. They are often used for temporary or short-lived data structures</p><pre>// Anonymous struct<br>person := struct {<br>    Name string<br>    Age  int<br>}{<br>    Name: &quot;Jane Doe&quot;,<br>    Age:  30,<br>}</pre><p><strong>Struct Embedding:</strong></p><p>Go supports struct embedding, allowing a struct to include another struct type. This feature is useful for creating a hierarchy of types.</p><pre>// Base struct<br>type Animal struct {<br>    Name string<br>}<br><br>// Dog struct embeds the Animal struct<br>type Dog struct {<br>    Animal<br>    Breed string<br>}</pre><p><strong>Pointer to a Struct:</strong></p><p>You can use pointers to reference and modify struct instances.</p><pre>// Create a pointer to a struct<br>personPointer := &amp;Person{<br>    Name: &quot;Alice&quot;,<br>    Age:  28,<br>}<br><br>// Accessing and modifying struct fields through a pointer<br>fmt.Println(personPointer.Name) // Output: Alice<br>personPointer.Age = 29<br>fmt.Println(personPointer.Age)  // Output: 29</pre><p><strong>Initializing a Struct with </strong><strong>new:</strong></p><p>The new function can be used to create a new struct instance and return its address.</p><pre>// Initializing a struct with &#39;new&#39;<br>newPerson := new(Person)<br>newPerson.Name = &quot;Bob&quot;<br>newPerson.Age = 32</pre><p>Structs are versatile and are widely used in Go for representing and organizing data. They play a crucial role in creating clear and structured data models in Go programs.</p><h3>What is an anonymous struct, and in what situations might you use one?</h3><p>An anonymous struct in Go is a struct without a predefined name. It is created on the fly, often for short-lived or temporary data structures. Unlike named structs, which are declared with a specific type name, anonymous structs are defined and used in a single place without being assigned a name.</p><p><strong>Syntax of an Anonymous Struct:</strong></p><pre>// Anonymous struct definition<br>var person = struct {<br>    Name string<br>    Age  int<br>}{<br>    Name: &quot;John Doe&quot;,<br>    Age:  25,<br>}</pre><p>In this example, the anonymous struct is defined and initialized in a single statement.</p><h4>Situations where Anonymous Structs are Useful:</h4><ol><li><strong>Temporary Data Structures:</strong></li></ol><ul><li>Anonymous structs are convenient for creating temporary data structures that are used only in a specific context and don’t need a permanent type.</li></ul><pre>// Using an anonymous struct for a one-time data structure<br>data := struct {<br>    Status  string<br>    Message string<br>}{<br>    Status:  &quot;OK&quot;,<br>    Message: &quot;Data retrieved successfully&quot;,<br>}</pre><p>2. <strong>Inline Initialization:</strong></p><ul><li>When you need to initialize a struct and use it immediately without declaring a separate type, anonymous structs can provide a concise way to achieve this.</li></ul><pre>// Anonymous struct for inline initialization<br>result := struct{ Code int }{Code: 200}</pre><p><strong>3. Function Parameters:</strong></p><ul><li>Anonymous structs can be used as function parameters to pass a set of related values without explicitly defining a named struct type.</li></ul><pre>// Using anonymous struct as a function parameter<br>func processData(data struct{ ID int; Name string }) {<br>    // Process the data<br>    fmt.Println(&quot;Processing data:&quot;, data)<br>}<br><br>func main() {<br>    // Calling the function with an anonymous struct<br>    processData(struct{ ID int; Name string }{ID: 1, Name: &quot;Alice&quot;})<br>}</pre><p><strong>4. Marshaling and Unmarshaling JSON:</strong></p><ul><li>Anonymous structs are commonly used when marshaling and unmarshaling JSON data, especially when the structure of the data is known and doesn’t require a dedicated type.</li></ul><pre>// Unmarshaling JSON into an anonymous struct<br>var result struct {<br>    Status  string `json:&quot;status&quot;`<br>    Message string `json:&quot;message&quot;`<br>}<br><br>jsonStr := `{&quot;status&quot;: &quot;OK&quot;, &quot;message&quot;: &quot;Success&quot;}`<br>json.Unmarshal([]byte(jsonStr), &amp;result)</pre><p>Using anonymous structs in these situations provides a compact and expressive way to work with structured data without the need for explicitly named types. They are particularly useful when the structure is simple and context-specific.</p><h3>Explain the concept of struct embedding in Go. Provide an example.</h3><p>Struct embedding in Go is a way to achieve composition by including one or more fields of one struct type within another struct type. The embedded struct’s fields and methods become part of the outer struct, allowing the outer struct to inherit their behavior. This concept is sometimes referred to as “embedding” or “anonymous fields.”</p><h4>Example of Struct Embedding:</h4><pre>package main<br><br>import &quot;fmt&quot;<br><br>// Animal struct representing a basic animal<br>type Animal struct {<br> Name string<br>}<br><br>// Dog struct embeds the Animal struct<br>type Dog struct {<br> Animal        // Embedding the Animal struct<br> Breed  string // Additional field specific to Dog<br>}<br><br>// Cat struct embeds the Animal struct<br>type Cat struct {<br> Animal        // Embedding the Animal struct<br> Color string // Additional field specific to Cat<br>}<br><br>func main() {<br> // Creating instances of Dog and Cat<br> dog := Dog{<br>  Animal: Animal{Name: &quot;Buddy&quot;},<br>  Breed:  &quot;Labrador&quot;,<br> }<br><br> cat := Cat{<br>  Animal: Animal{Name: &quot;Whiskers&quot;},<br>  Color:  &quot;Gray&quot;,<br> }<br><br> // Accessing fields from embedded struct<br> fmt.Printf(&quot;Dog&#39;s name: %s\n&quot;, dog.Name) // Accessing Animal&#39;s field<br> fmt.Printf(&quot;Cat&#39;s name: %s\n&quot;, cat.Name) // Accessing Animal&#39;s field<br><br> // Accessing fields specific to each struct<br> fmt.Printf(&quot;Dog&#39;s breed: %s\n&quot;, dog.Breed)<br> fmt.Printf(&quot;Cat&#39;s color: %s\n&quot;, cat.Color)<br>}</pre><p>In this example:</p><ul><li>The Animal struct has a single field named Name.</li><li>The Dog struct embeds the Animal struct, and it also has an additional field named Breed.</li><li>The Cat struct also embeds the Animal struct, and it has an additional field named Color.</li></ul><p>When you create instances of Dog or Cat, the fields and methods of the embedded Animal struct becomes accessible directly from the instances of the outer structs (Dog and Cat). In this way, the outer structs inherit the behavior of the embedded struct.</p><h4>Key Points:</h4><ol><li>Fields from the embedded struct are directly accessible from the outer struct instances.</li><li>If there are conflicts (fields with the same name) between the outer and embedded structs, the field from the outer struct takes precedence.</li><li>Struct embedding is a form of composition that allows for code reuse and structuring of related types.</li></ol><p>Struct embedding is a powerful feature in Go that promotes code reuse and allows for creating clear and concise relationships between types. It provides a way to model relationships such as “is-a” or “has-a” between different types.</p><h3>How do you create a pointer to a struct? What benefits does using a pointer to a struct offer?</h3><p>Creating a pointer to a struct in Go is similar to creating a pointer to any other type. You can use the &amp; operator followed by the struct instance to obtain its memory address. The benefits of using a pointer to a struct include efficient memory management, the ability to modify the original struct through the pointer, and avoiding unnecessary copying of data.</p><h4>Creating a Pointer to a Struct:</h4><pre>package main<br><br>import &quot;fmt&quot;<br><br>// Define a struct named &#39;Person&#39; with fields &#39;Name&#39; and &#39;Age&#39;<br>type Person struct {<br>    Name string<br>    Age  int<br>}<br><br>func main() {<br>    // Create an instance of the &#39;Person&#39; struct<br>    personInstance := Person{<br>        Name: &quot;John Doe&quot;,<br>        Age:  25,<br>    }<br><br>    // Create a pointer to the &#39;Person&#39; struct<br>    personPointer := &amp;personInstance<br><br>    // Accessing struct fields through the pointer<br>    fmt.Println(&quot;Name:&quot;, personPointer.Name)<br>    fmt.Println(&quot;Age:&quot;, personPointer.Age)<br>}</pre><h4>Benefits of Using a Pointer to a Struct:</h4><p><strong>1. Efficient Memory Management:</strong></p><ul><li>When passing a struct to a function or storing it in a data structure, using a pointer can be more memory-efficient than passing or storing the entire struct. This is particularly beneficial for large structs.</li></ul><p><strong>2. Modify Original Struct:</strong></p><ul><li>Using a pointer allows you to modify the original struct’s values through the pointer. Changes made through the pointer directly affect the underlying struct.</li></ul><pre>// Modify the original struct through the pointer<br>personPointer.Age = 26<br>fmt.Println(&quot;Updated Age:&quot;, personInstance.Age) // Output: 26</pre><p><strong>3. Avoiding Copying:</strong></p><ul><li>When passing a struct as an argument to a function, using a pointer avoids copying the entire struct. This is advantageous for performance, especially when working with large data structures.</li></ul><p><strong>4. Nil Pointer Check:</strong></p><ul><li>Using a pointer enables you to check for nil (uninitialized) pointers, which can be helpful in scenarios where the struct might not be initialized.</li></ul><pre>// Check if the pointer is nil before dereferencing<br>if personPointer != nil {<br>    fmt.Println(&quot;Name:&quot;, personPointer.Name)<br>}</pre><p><strong>5. Sharing Data Between Functions:</strong></p><ul><li>Pointers allow sharing and modifying the same data between different parts of your program, facilitating coordination and synchronization.</li></ul><h3>Can you define methods for a struct in Go? How are they different from regular functions?</h3><p>Yes, in Go, you can define methods for a struct. Methods in Go are functions associated with a particular type, and they are declared with a receiver, which is similar to the concept of “this” or “self” in other programming languages. Methods allow you to associate behavior with a specific type, and they can be called on instances of that type.</p><h4>Syntax for Defining Methods:</h4><pre>package main<br><br>import &quot;fmt&quot;<br><br>// Define a struct named &#39;Rectangle&#39;<br>type Rectangle struct {<br>    Width  float64<br>    Height float64<br>}<br><br>// Method area() for the Rectangle struct<br>func (r Rectangle) area() float64 {<br>    return r.Width * r.Height<br>}<br><br>// Method perimeter() for the Rectangle struct<br>func (r Rectangle) perimeter() float64 {<br>    return 2*r.Width + 2*r.Height<br>}<br><br>func main() {<br>    // Create an instance of the Rectangle struct<br>    rectangle := Rectangle{Width: 5, Height: 3}<br><br>    // Call methods on the struct instance<br>    fmt.Println(&quot;Area:&quot;, rectangle.area())<br>    fmt.Println(&quot;Perimeter:&quot;, rectangle.perimeter())<br>}</pre><h4>In this example:</h4><ul><li>The Rectangle struct has two fields, Width and Height.</li><li>Two methods, area and perimeter, are defined for the Rectangle struct.</li></ul><h4>Key Points about Methods in Go:</h4><ol><li><strong>Receiver:</strong></li></ol><ul><li>The receiver is a parameter that appears in the method declaration. It specifies the type on which the method operates. In the example, (r Rectangle) the receiver is for both methods.</li></ul><p><strong>2. Value Receiver vs. Pointer Receiver:</strong></p><ul><li>Methods can have either a value receiver (as in the example) or a pointer receiver ((r *Rectangle)). A value receiver operates on a copy of the struct, while a pointer receiver operates on the original struct. The choice depends on whether you want to modify the original struct.</li></ul><p><strong>3. Associated with Type:</strong></p><ul><li>Methods are associated with a specific type, providing a way to encapsulate behavior related to that type.</li></ul><p><strong>4. Call Syntax:</strong></p><ul><li>Methods are called on instances of the type using the syntax instance.method(). In the example, rectangle.area() and rectangle.perimeter().</li></ul><p><strong>5. Visibility:</strong></p><ul><li>Methods can be defined for both exported (capitalized) and unexported (lowercase) struct types.</li></ul><h3>Is it possible to compare two structs in Go using the `==` operator? Why or why not?</h3><p>In Go, you can compare two structs using the == operator if and only if the structs have fields of comparable types, and the fields in both structs are equal. If the structs contain fields that are not comparable, the comparison will result in a compilation error.</p><p>Here’s an example:</p><pre>package main<br><br>import &quot;fmt&quot;<br><br>// Define a struct named &#39;Person&#39;<br>type Person struct {<br>    Name string<br>    Age  int<br>}<br><br>func main() {<br>    // Create two instances of the &#39;Person&#39; struct<br>    person1 := Person{Name: &quot;John&quot;, Age: 30}<br>    person2 := Person{Name: &quot;John&quot;, Age: 30}<br><br>    // Compare the two structs using the &#39;==&#39; operator<br>    if person1 == person2 {<br>        fmt.Println(&quot;The structs are equal.&quot;)<br>    } else {<br>        fmt.Println(&quot;The structs are not equal.&quot;)<br>    }<br>}</pre><p>In this example, the Person struct has fields of comparable types (string and int), and the two instances person1 and person2 have the same values for those fields. Therefore, the comparison using == yields true, and the message &quot;The structs are equal&quot; will be printed.</p><p>If the structs have fields that are not of comparable types, attempting to use the == the operator will result in a compilation error. For example:</p><pre>package main<br><br>import &quot;fmt&quot;<br><br>// Define a struct with a slice field<br>type ExampleStruct struct {<br>    Numbers []int<br>}<br><br>func main() {<br>    // Create two instances of the struct with slices<br>    struct1 := ExampleStruct{Numbers: []int{1, 2, 3}}<br>    struct2 := ExampleStruct{Numbers: []int{1, 2, 3}}<br><br>    // Attempt to compare the two structs using the &#39;==&#39; operator<br>    if struct1 == struct2 {<br>        fmt.Println(&quot;The structs are equal.&quot;)<br>    } else {<br>        fmt.Println(&quot;The structs are not equal.&quot;)<br>    }<br>}</pre><p>In this case, the comparison will result in a compilation error because the slices are not of comparable types.</p><h3>What is the zero value of a struct in Go? Does it depend on the values of its fields?</h3><p>In Go, the zero value of a struct is a struct with all its fields set to their respective zero values. The zero value for each field is determined by its data type. For example:</p><ul><li>Numeric types (int, float64, etc.) have a zero value of 0.</li><li>String types have a zero value of an empty string (&quot;&quot;).</li><li>Boolean types have a zero value of false.</li><li>Pointer types have a zero value of nil.</li><li>Struct types have a zero value where each field is set to its zero value.</li></ul><p>Here’s an example:</p><pre>package main<br><br>import &quot;fmt&quot;<br><br>// Define a struct named &#39;ExampleStruct&#39;<br>type ExampleStruct struct {<br>    Integer    int<br>    Float      float64<br>    Text       string<br>    IsActive   bool<br>    Pointer    *int<br>}<br><br>func main() {<br>    // Create an instance of &#39;ExampleStruct&#39; with no explicit values<br>    var zeroStruct ExampleStruct<br><br>    // Access and print the values of the struct fields<br>    fmt.Println(&quot;Integer:&quot;, zeroStruct.Integer)     // Output: 0<br>    fmt.Println(&quot;Float:&quot;, zeroStruct.Float)         // Output: 0<br>    fmt.Println(&quot;Text:&quot;, zeroStruct.Text)           // Output: &quot;&quot;<br>    fmt.Println(&quot;IsActive:&quot;, zeroStruct.IsActive)   // Output: false<br>    fmt.Println(&quot;Pointer:&quot;, zeroStruct.Pointer)     // Output: &lt;nil&gt;<br>}</pre><p>In this example, zeroStruct is an instance ExampleStruct with all its fields set to their zero values. The zero value ExampleStruct is determined by the zero values of its fields.</p><p>It’s important to note that the zero value of a struct is not dependent on the values assigned to its fields during initialization. The zero value is what the struct gets if it is declared without any explicit initialization or assignment. If you explicitly initialize a struct with specific values, those values will override the zero values for the corresponding fields.</p><h3>When would you choose to use a struct over a map in Go, and vice versa? What are the advantages and disadvantages of each?</h3><p>Choosing between a struct and a map in Go depends on the specific requirements and characteristics of the data you are working with. Here are some considerations for each:</p><p><strong>Structs:</strong></p><p><strong><em>Advantages:</em></strong></p><ol><li><strong>Type Safety:</strong> Structs provide compile-time type safety, ensuring that you access fields with the correct types.</li><li><strong>Performance:</strong> Accessing struct fields is generally faster than map lookups, especially for known fields with a fixed layout in memory.</li><li><strong>Readability:</strong> Structs are more expressive and self-documenting, making the code more readable.</li></ol><p><strong><em>Disadvantages:</em></strong></p><ol><li><strong>Fixed Structure:</strong> Structs have a fixed structure, which can be limiting if the data has dynamic or unknown fields.</li><li><strong>Initialization:</strong> Structs need to be initialized with all their fields, and zero values are assigned if not explicitly set.</li></ol><p><strong>Maps:</strong></p><p><strong><em>Advantages:</em></strong></p><ol><li><strong>Dynamic Structure:</strong> Maps allow dynamic addition and removal of key-value pairs, making them suitable for data with varying fields.</li><li><strong>Flexibility:</strong> Maps can be easily extended with new key-value pairs without modifying the data structure.</li><li><strong>Concise:</strong> Maps can be more concise for certain use cases, especially when dealing with a large number of fields.</li></ol><p><strong><em>Disadvantages:</em></strong></p><ol><li><strong>Type Safety:</strong> Maps do not provide compile-time type safety, and type assertions or conversions are needed when retrieving values.</li><li><strong>Performance:</strong> Map lookups can be slower than direct struct field access, especially for small and fixed-size datasets.</li><li><strong>Readability:</strong> Maps might be less expressive and self-documenting than structs, as the structure is not immediately visible in the code.</li></ol><p><strong>Differences:</strong></p><ol><li><strong>Syntax:</strong></li></ol><ul><li>Structs have a fixed syntax with named fields and known types.</li><li>Maps use the map Keywords are dynamically extensible with key-value pairs.</li></ul><p><strong>2. Initialization:</strong></p><ul><li>Structs are typically initialized using the var keyword or with a composite literal specifying values for each field.</li><li>Maps can be initialized using the make function or a composite literal with key-value pairs.</li></ul><p><strong>3. Access:</strong></p><ul><li>Struct fields are accessed using the dot notation (e.g., myStruct.field).</li><li>Map values are accessed using square brackets and the key (e.g., myMap[key]).</li></ul><p><strong>4. Type Safety:</strong></p><ul><li>Structs provide compile-time type safety for field access.</li><li>Maps require runtime type checks when retrieving values.</li></ul><p><strong>Guidelines:</strong></p><ul><li>Use structs when the data has a fixed structure, and compile-time type safety is essential.</li><li>Use maps when dealing with dynamic or unknown data structures, and flexibility in adding or removing fields is required.</li></ul><h3>Explain the purpose of struct tags in Go. Provide an example where struct tags are commonly used.</h3><p>In Go, struct tags are metadata associated with struct fields. Struct tags provide additional information about how a struct field should be treated, often used for encoding and decoding data, such as during serialization to formats like JSON, XML, or when interacting with databases. Struct tags are specified as a string literal following the field declaration within backticks (`).</p><h4>Purpose of Struct Tags:</h4><ol><li><strong>Serialization/Deserialization:</strong></li></ol><ul><li>Struct tags are commonly used to specify how a struct should be serialized and deserialized. Libraries like encoding/json use struct tags to determine how to encode and decode struct fields.</li></ul><p><strong>2. Database Mapping:</strong></p><ul><li>In database interactions, struct tags can be used to specify the mapping between struct fields and database columns. ORM (Object-Relational Mapping) libraries often leverage struct tags for this purpose.</li></ul><p><strong>3. Validation:</strong></p><ul><li>Some third-party packages use struct tags for validation purposes, defining rules and constraints for each field.</li></ul><p>Example Using encoding/json:</p><pre>package main<br><br>import (<br> &quot;encoding/json&quot;<br> &quot;fmt&quot;<br>)<br><br>// Define a struct named &#39;Person&#39; with struct tags<br>type Person struct {<br> Name  string `json:&quot;name&quot;`<br> Age   int    `json:&quot;age&quot;`<br> Email string `json:&quot;email,omitempty&quot;`<br>}<br><br>func main() {<br> // Create an instance of the &#39;Person&#39; struct<br> person := Person{<br>  Name:  &quot;John Doe&quot;,<br>  Age:   30,<br>  Email: &quot;john@example.com&quot;,<br> }<br><br> // Serialize the struct to JSON<br> jsonData, err := json.Marshal(person)<br> if err != nil {<br>  fmt.Println(&quot;Error:&quot;, err)<br>  return<br> }<br><br> // Print the JSON data<br> fmt.Println(string(jsonData))<br>}</pre><p>In this example:</p><ul><li>The Person struct has three fields: Name, Age, and Email.</li><li>Struct tags (e.g., json:&quot;name&quot;) are added to each field, specifying the corresponding JSON field names and additional options.</li><li>During serialization using json.Marshal, the struct tags guide the encoding process.</li></ul><p>Output:</p><pre>{&quot;name&quot;:&quot;John Doe&quot;,&quot;age&quot;:30,&quot;email&quot;:&quot;john@example.com&quot;}</pre><p>Here, struct tags are used to instruct the encoding/json package to encode the Name field as &quot;name&quot;, the Age field as &quot;age&quot;, and to omit the Email field if it is empty (omitempty).</p><p>Struct tags provide a powerful way to add metadata to struct fields, making them versatile for various purposes, including serialization, database mapping, and validation. The specific interpretation of struct tags depends on the library or tool that uses them.</p><h3>When you assign one struct variable to another in Go, is it a deep copy or a shallow copy? How can you perform a deep copy of a struct?</h3><p>In Go, when you assign one struct variable to another, it performs a shallow copy. This means that the individual fields of the destination struct receive copies of the values from the corresponding fields of the source struct. However, if the struct contains reference types (e.g., slices, maps, or pointers), the references themselves are copied, not the underlying data.</p><p>Here’s an example illustrating a shallow copy:</p><pre>package main<br><br>import &quot;fmt&quot;<br><br>// Define a struct named &#39;Person&#39;<br>type Person struct {<br> Name string<br> Age  int<br>}<br><br>func main() {<br> // Create an instance of the &#39;Person&#39; struct<br> person1 := Person{Name: &quot;Alice&quot;, Age: 25}<br><br> // Shallow copy by assignment<br> person2 := person1<br><br> // Modify a field in the original struct<br> person1.Name = &quot;Bob&quot;<br><br> // Print both structs<br> fmt.Println(&quot;Person 1:&quot;, person1) // Output: Person 1: {Bob 25}<br> fmt.Println(&quot;Person 2:&quot;, person2) // Output: Person 2: {Alice 25}<br>}</pre><p>In this example, modifying the Name field of person1 does not affect the Name field of person2.</p><h4>Performing a Deep Copy:</h4><p>To perform a deep copy, you need to manually copy each field, taking into account the type of the field. For example, if the struct contains slices or maps, you need to create new instances and copy the elements. If it contains pointers to other structs, you need to create new instances of the pointed-to structs.</p><p>Here’s an example of a deep copy:</p><pre>package main<br><br>import &quot;fmt&quot;<br><br>// Define a struct named &#39;Person&#39; with a slice field<br>type Person struct {<br> Name    string<br> Age     int<br> Hobbies []string<br>}<br><br>func main() {<br> // Create an instance of the &#39;Person&#39; struct<br> person1 := Person{<br>  Name:    &quot;Alice&quot;,<br>  Age:     25,<br>  Hobbies: []string{&quot;Reading&quot;, &quot;Traveling&quot;},<br> }<br><br> // Perform a deep copy<br> person2 := Person{<br>  Name:    person1.Name,<br>  Age:     person1.Age,<br>  Hobbies: make([]string, len(person1.Hobbies)),<br> }<br><br> copy(person2.Hobbies, person1.Hobbies)<br><br> // Modify a field in the original struct<br> person1.Name = &quot;Bob&quot;<br> person1.Hobbies[0] = &quot;Swimming&quot;<br><br> // Print both structs<br> fmt.Println(&quot;Person 1:&quot;, person1)<br> fmt.Println(&quot;Person 2:&quot;, person2)<br>}</pre><p>In this example, a deep copy is performed by manually copying each field, including creating a new slice and copying the elements. Now, modifying the Name or Hobbies fields of person1 does not affect person2.</p><h3>Explain the concept of unexported fields in a struct. How are they accessed or modified within and outside of the package?</h3><p>In Go, fields of a struct can be either exported (public) or unexported (private). The concept of exported and unexported fields is related to the visibility of those fields outside the package where the struct is defined.</p><ul><li><strong>Exported Fields (Public):</strong> Fields whose names start with an uppercase letter are exported and can be accessed from outside the package.</li><li><strong>Unexported Fields (Private):</strong> Fields whose names start with a lowercase letter are unexported and can only be accessed from within the same package.</li></ul><p>Here’s an example to illustrate:</p><pre>package mypackage<br><br>// Define a struct with both exported and unexported fields<br>type Person struct {<br>    FirstName string // Exported field<br>    lastName  string // Unexported field<br>    Age       int    // Exported field<br>}</pre><p>In this example, FirstName and Age are exported fields because they start with an uppercase letter, while lastName is an unexported field because it starts with a lowercase letter.</p><p><strong>Accessing and Modifying Fields within the Package:</strong></p><p>Within the same package, both exported and unexported fields can be accessed and modified freely:</p><pre>package mypackage<br><br>import &quot;fmt&quot;<br><br>func Example() {<br>    // Create an instance of the &#39;Person&#39; struct<br>    person := Person{<br>        FirstName: &quot;John&quot;,<br>        lastName:  &quot;Doe&quot;,<br>        Age:       30,<br>    }<br><br>    // Access and modify both exported and unexported fields<br>    fmt.Println(&quot;First Name:&quot;, person.FirstName)<br>    fmt.Println(&quot;Last Name:&quot;, person.lastName)<br>    fmt.Println(&quot;Age:&quot;, person.Age)<br><br>    // Modify an unexported field<br>    person.lastName = &quot;Smith&quot;<br>    fmt.Println(&quot;Modified Last Name:&quot;, person.lastName)<br>}</pre><p><strong>Accessing and Modifying Fields outside the Package:</strong></p><p>Attempting to access or modify unexported fields from outside the package will result in a compilation error:</p><pre>package main<br><br>import &quot;mypackage&quot;<br><br>func main() {<br>    // Create an instance of the &#39;Person&#39; struct from another package<br>    person := mypackage.Person{<br>        FirstName: &quot;Alice&quot;,<br>        // lastName:  &quot;Doe&quot;, // Compilation error: mypackage.Person.lastName undefined (cannot refer to unexported field or method lastName)<br>        Age: 25,<br>    }<br>}</pre><p>The use of exported and unexported fields helps enforce encapsulation and control access to the internal details of a package. Unexported fields are not visible to other packages, providing a level of privacy and encapsulation for the package’s implementation details.</p><h3>Go doesn’t have traditional constructors. How can you create a constructor-like function for a struct to initialize its fields with specific values?</h3><p>Here’s an example demonstrating how you can create a constructor-like function for a struct:</p><pre>package main<br><br>import &quot;fmt&quot;<br><br>// Define a struct named &#39;Person&#39;<br>type Person struct {<br> Name string<br> Age  int<br>}<br><br>// NewPerson is a constructor-like function for creating a new Person instance<br>func NewPerson(name string, age int) *Person {<br> return &amp;Person{<br>  Name: name,<br>  Age:  age,<br> }<br>}<br><br>func main() {<br> // Use the constructor-like function to create a new Person instance<br> person := NewPerson(&quot;Alice&quot;, 25)<br><br> // Print the created Person instance<br> fmt.Printf(&quot;Name: %s, Age: %d\n&quot;, person.Name, person.Age)<br>}</pre><p>In this example:</p><ul><li>The Person struct is defined with fields Name and Age.</li><li>The NewPerson function is a constructor-like function that takes parameters for initializing the struct fields and returns a pointer to a new Person instance.</li><li>Inside the NewPerson function, a new Person instance is created with the specified values, and its address is returned.</li></ul><p>Using constructor-like functions provides a clean and idiomatic way to initialize struct instances with specific values, and it encapsulates the details of struct creation. This pattern is especially useful when the struct has many fields or when additional initialization logic is required.</p><h3>Can you create an immutable struct in Go? Explain the concept and provide an example.</h3><p>In Go, structs are mutable by default, meaning their fields can be modified after creation. However, you can achieve immutability to some extent by following certain conventions. While you can’t make individual fields of a struct immutable, you can design the struct in a way that discourages or prevents modification after creation.</p><p>Here’s an example of how you might approach creating an “immutable” struct in Go:</p><pre>package main<br><br>import &quot;fmt&quot;<br><br>// Person is an &quot;immutable&quot; struct with exported fields and no setter methods<br>type Person struct {<br>    firstName string<br>    lastName  string<br>    age       int<br>}<br><br>// NewPerson creates a new instance of Person with specified values<br>func NewPerson(firstName, lastName string, age int) *Person {<br>    return &amp;Person{<br>        firstName: firstName,<br>        lastName:  lastName,<br>        age:       age,<br>    }<br>}<br><br>// FirstName returns the first name of the person<br>func (p Person) FirstName() string {<br>    return p.firstName<br>}<br><br>// LastName returns the last name of the person<br>func (p Person) LastName() string {<br>    return p.lastName<br>}<br><br>// Age returns the age of the person<br>func (p Person) Age() int {<br>    return p.age<br>}<br><br>func main() {<br>    // Create an &quot;immutable&quot; Person<br>    person := NewPerson(&quot;John&quot;, &quot;Doe&quot;, 30)<br><br>    // Access fields (read-only)<br>    fmt.Println(&quot;First Name:&quot;, person.FirstName())<br>    fmt.Println(&quot;Last Name:&quot;, person.LastName())<br>    fmt.Println(&quot;Age:&quot;, person.Age())<br><br>    // Attempting to modify fields will result in a compilation error<br>    // person.firstName = &quot;Jane&quot; // Error: cannot assign to person.firstName (unexported field)<br>}</pre><p>In this example:</p><ul><li>The Person struct has unexported fields (firstName, lastName, age) and no setter methods.</li><li>The NewPerson function acts as a constructor and returns a pointer to a new Person instance with the specified values.</li><li>Getter methods (FirstName, LastName, Age) provide read-only access to the fields.</li></ul><p>While this doesn’t make the struct truly immutable, it enforces a convention where modifications are discouraged. Attempting to directly modify the fields outside the package will result in compilation errors due to unexported fields.</p><p>It’s important to note that achieving complete immutability in Go requires using techniques like using interfaces and providing only read methods. In practice, the approach above provides a level of immutability by convention and can help prevent accidental modifications.</p><h3>How is the size of a struct determined in Go? Are there any factors that affect the size of a struct?</h3><p>In Go, the size of a struct is determined by the sum of the sizes of its fields. The size of each field depends on its type. The total size of a struct may include padding added by the compiler for alignment purposes.</p><p>Factors that affect the size of a struct in Go include:</p><ol><li><strong>Field Types:</strong> The size of each field is determined by its type. For example, the size of an int field is typically 4 or 8 bytes, depending on the architecture.</li><li><strong>Alignment:</strong> The compiler may add padding between fields to align them in memory. This alignment is done to optimize memory access, as many architectures have alignment requirements for certain types. For example, on a 64-bit system, an int64 might be aligned on an 8-byte boundary.</li><li><strong>Padding:</strong> The compiler may add padding at the end of the struct to ensure that the entire struct is aligned properly. This is known as “struct padding” and is done for performance reasons.</li><li><strong>Field Order:</strong> The order of fields in the struct may affect its size due to alignment and padding considerations. Reordering fields may change the amount of padding added by the compiler.</li></ol><p>Here’s an example to illustrate the impact of padding on struct size:</p><pre>package main<br><br>import (<br> &quot;fmt&quot;<br> &quot;unsafe&quot;<br>)<br><br>// ExampleStruct is a struct with different data types<br>type ExampleStruct struct {<br> BoolValue   bool    // 1 byte<br> Int32Value  int32   // 4 bytes<br> Float64Value float64 // 8 bytes<br>}<br><br>func main() {<br> // Create an instance of ExampleStruct<br> example := ExampleStruct{}<br><br> // Calculate the size of the struct using the unsafe package<br> size := unsafe.Sizeof(example)<br><br> // Print the size of the struct<br> fmt.Printf(&quot;Size of ExampleStruct: %d bytes\n&quot;, size)<br>}</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=758db20ef4c9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Golang Interview: Pointers]]></title>
            <link>https://medium.com/@kiruu1238/golang-interview-pointers-2856456a710f?source=rss-b0ae211f548d------2</link>
            <guid isPermaLink="false">https://medium.com/p/2856456a710f</guid>
            <category><![CDATA[pointers]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[backend]]></category>
            <category><![CDATA[interview]]></category>
            <category><![CDATA[tech]]></category>
            <dc:creator><![CDATA[Kiran Adhikari]]></dc:creator>
            <pubDate>Sat, 16 Aug 2025 16:24:57 GMT</pubDate>
            <atom:updated>2025-08-16T16:24:57.119Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vncwvpcCgarrll5tpFZ6aQ.png" /><figcaption>Gopher</figcaption></figure><p>In Go (Golang), a pointer is a variable that stores the memory address of another variable. Pointers provide a way to indirectly access the value of a variable and manipulate data through its memory address. Here are some key concepts related to pointers in Go:</p><ol><li><strong>Declaration and Initialization:</strong></li></ol><ul><li>To declare a pointer, you use the * symbol followed by the type of the variable it will point to. For example:</li></ul><pre>var p *int  // p is a pointer to an int</pre><p>2. <strong>Address-of Operator (</strong><strong>&amp;):</strong></p><ul><li>The address-of-operator &amp; is used to get the memory address of a variable. For example:</li></ul><pre>x := 42<br>p = &amp;x  // p now holds the memory address of x</pre><p>3. <strong>Dereferencing Operator (</strong><strong>*):</strong></p><ul><li>The dereferencing operator * is used to access the value stored at the memory address pointed to by a pointer. For example:</li></ul><pre>fmt.Println(*p)  // Prints the value stored at the memory address pointed to by p</pre><p><strong>4. Zero Value of Pointers:</strong></p><ul><li>A pointer that is declared but not explicitly initialized will have a zero value, which is nil for pointers. Attempting to dereference a nil pointer results in a runtime panic.</li></ul><p><strong>5. New Function:</strong></p><ul><li>The new function can be used to create a new instance of a variable and return its memory address. For example:</li></ul><pre>p:= new(int)  // p is a pointer to a newly allocated int</pre><p><strong>6. Passing Pointers to Functions:</strong></p><ul><li>Pointers are often used to pass references to variables to functions, allowing functions to modify the original data. When a pointer is passed to a function, changes made to the data through the pointer are reflected outside the function.</li></ul><pre>func modifyValue(ptr *int) {<br>    *ptr = 100<br>}<br><br>// Usage:<br>x := 42<br>p := &amp;x<br>modifyValue(p)<br>fmt.Println(x)  // Prints 100</pre><p><strong>7. Pointers and Structures:</strong></p><ul><li>Pointers can be used with structures to achieve more efficient memory management and to avoid copying large data structures. Accessing structure fields through pointers allows for in-place modification.</li></ul><pre>type Point struct {<br>    X, Y int<br>}<br><br>func movePoint(p *Point, deltaX, deltaY int) {<br>    p.X += deltaX<br>    p.Y += deltaY<br>}<br><br>// Usage:<br>point := Point{X: 10, Y: 20}<br>movePoint(&amp;point, 5, 5)<br>fmt.Println(point)  // Prints {15 25}</pre><p><strong>8. Pointers vs. Values:</strong></p><ul><li>In Go, passing large data structures by reference (using pointers) can be more efficient than passing them by value, especially when dealing with function arguments. However, it’s essential to consider issues like ownership and potential data races when using pointers.</li></ul><p><strong>9. Unsafe Package:</strong></p><ul><li>Go provides the unsafe package, which allows low-level operations, including direct manipulation of pointers. However, using the unsafe package should be approached with caution, as it can lead to undefined behavior and compromise the safety guarantees of the language.</li></ul><p>Here’s a simple example demonstrating some pointer concepts:</p><pre>package main<br><br>import &quot;fmt&quot;<br><br>func main() {<br>    x := 42<br>    var p *int   // Declaration of a pointer to an int<br>    p = &amp;x       // Assigning the address of x to the pointer p<br><br>    fmt.Println(&quot;Value of x:&quot;, x)<br>    fmt.Println(&quot;Address of x:&quot;, &amp;x)<br>    fmt.Println(&quot;Value through pointer p:&quot;, *p)  // Dereferencing the pointer<br><br>    *p = 100     // Modifying the value through the pointer<br>    fmt.Println(&quot;Modified value of x:&quot;, x)<br><br>    // Passing a pointer to a function<br>    modifyValue(p)<br>    fmt.Println(&quot;Value after function call:&quot;, x)<br>}<br><br>func modifyValue(ptr *int) {<br>    *ptr = 200<br>}</pre><h3>Advantages/ Use Cases of Pointers</h3><p>Pointers in Go provide a powerful mechanism for managing memory and indirectly accessing and modifying data. Here are some advantages of using pointers and common use cases:</p><ol><li><strong>Efficient Memory Management:</strong></li></ol><ul><li>Pointers allow for more efficient memory usage, especially when dealing with large data structures. Instead of passing around entire copies of data, you can pass a reference to the data using a pointer.</li></ul><p><strong>2. Passing by Reference:</strong></p><ul><li>Pointers enable passing variables by reference to functions, allowing the function to modify the original data rather than working with a copy. This is particularly useful when dealing with large data structures where passing by value would be less efficient.</li></ul><pre>func modifyValue(ptr *int) {<br>    *ptr = 100<br>}<br><br>// Usage:<br>x := 42<br>p := &amp;x<br>modifyValue(p)<br>fmt.Println(x)  // Prints 100</pre><p><strong>3. Dynamic Memory Allocation:</strong></p><ul><li>Pointers enable dynamic memory allocation using the new function or the make function for slices, maps, and channels. This allows for the creation of data structures whose size can be determined at runtime.</li></ul><pre>p:= new(int)    // Allocates memory for int and returns a pointer<br>*p = 42          // Sets the value stored at the memory location pointed to by p</pre><p><strong>4. Avoiding Data Copying:</strong></p><ul><li>Pointers can be used to avoid unnecessary copying of data. When passing large data structures between functions or goroutines, using pointers allows multiple parts of the program to share the same underlying data.</li></ul><p><strong>5. Linked Data Structures:</strong></p><ul><li>Pointers are essential for implementing linked data structures such as linked lists, trees, and graphs. These data structures often require references to other nodes or elements, and pointers provide a convenient way to express these relationships.</li></ul><pre>type Node struct {<br>    Data int<br>    Next *Node<br>}</pre><h3>Pass by Reference</h3><p>One common real-world scenario where mutating values using pointers is necessary is when working with large data structures or objects. Using pointers allows you to avoid unnecessary copying of data, which can be crucial for performance and memory efficiency. Let’s consider an example:</p><pre>package main<br><br>import &quot;fmt&quot;<br><br>// Person struct represents a person with a name and age.<br>type Person struct {<br> Name string<br> Age  int<br>}<br><br>// UpdateAge takes a pointer to a Person and updates the age.<br>func UpdateAge(p *Person, newAge int) {<br> p.Age = newAge<br>}<br><br>func main() {<br> // Create a Person instance.<br> person:= Person{Name: &quot;John&quot;, Age: 30}<br><br> // Print the original person.<br> fmt.Println(&quot;Original Person:&quot;, person)<br><br> // Update the age using a pointer to the person.<br> UpdateAge(&amp;person, 35)<br><br> // Print the person with the updated age.<br> fmt.Println(&quot;Updated Person:&quot;, person)<br>}</pre><p>In this example:</p><ol><li>The Person struct represents a person with a name and age.</li><li>The UpdateAge function takes a pointer to a Person and updates the Age field.</li><li>In the main function, a Person instance is created, and its age is updated using a pointer.</li></ol><p>Using pointers in this scenario is beneficial for the following reasons:</p><ul><li><strong>Performance:</strong> If Person struct is large, or if you have a collection of In Person instances, passing them by reference (using pointers) avoids copying the entire structure, leading to better performance.</li><li><strong>Memory Efficiency:</strong> Passing a pointer to a function allows the function to modify the original data directly, reducing memory overhead.</li><li><strong>Avoiding Data Copying:</strong> If you have a large data structure and you want to update only a small part of it, using pointers allows you to avoid copying the entire structure.</li></ul><h3>What is a pointer in Golang, and how is it different from a regular variable?</h3><p>In Go, a pointer is a variable that stores the memory address of another variable. It points to the location in memory where the actual value is stored. Pointers provide a way to indirectly access and manipulate the data at that memory address.</p><p>Here are key points about pointers in Go and how they differ from regular variables:</p><ol><li><strong>Declaration:</strong></li></ol><ul><li>To declare a pointer in Go, you use the * symbol followed by the type of the variable it will point to. For example:</li></ul><pre>var ptr *int  // ptr is a pointer to an int</pre><p><strong>2. Initialization:</strong></p><ul><li>Pointers are typically initialized using the address-of operator (&amp;), which returns the memory address of a variable. For example:</li></ul><pre>x := 42<br>ptr = &amp;x  // ptr now holds the memory address of x</pre><p><strong>3. Zero Value:</strong></p><ul><li>The zero value of a pointer isnil, which means it is not pointing to any valid memory address. Attempting to dereference a nil pointer results in a runtime panic.</li></ul><pre>var ptr *int  // Zero value of ptr is nil</pre><p><strong>4. Dereferencing:</strong></p><ul><li>The dereferencing operator (*) is used to access the value stored at the memory address pointed to by a pointer. For example:</li></ul><pre>fmt.Println(*ptr)  // Prints the value stored at the memory address pointed to by ptr</pre><p><strong>5. Assignment:</strong></p><ul><li>Pointers can be reassigned to point to different memory addresses. Changing the value through a pointer affects the original variable.</li></ul><pre>y := 10<br>ptr = &amp;y   // ptr now points to the memory address of y<br>*ptr = 20  // Modifies the value of y through the pointer</pre><p><strong>6. Difference from Regular Variables:</strong></p><ul><li>Regular variables in Go store values directly, while pointers store memory addresses. When you manipulate the value through a pointer, you are indirectly modifying the original data.</li></ul><pre>a := 5<br>b := a    // b is a copy of the value of a</pre><ul><li>Pointers enable passing references to variables to functions, allowing the function to modify the original data rather than working with a copy. This is a key difference from regular variables, where modifications made inside a function do not affect the original data.</li></ul><p>In summary, a pointer in Go is a variable that holds the memory address of another variable, providing a way to indirectly access and modify the data. Pointers are essential for tasks such as efficient memory management, passing by reference, and building data structures like linked lists.</p><h3>How does Go’s garbage collector work, and how does it impact the use of pointers?</h3><p>Go’s garbage collector (GC) is responsible for automatically managing memory by reclaiming memory that is no longer in use, preventing memory leaks, and allowing developers to focus on writing code without explicit memory management. The garbage collector in Go uses a concurrent and parallel approach to minimize its impact on program execution. Here’s an overview of how Go’s garbage collector works and its impact on the use of pointers:</p><h4>How Go’s Garbage Collector Works:</h4><ol><li><strong>Tracing and Marking:</strong></li></ol><ul><li>Go’s garbage collector uses a tracing garbage collection algorithm. It starts by marking all reachable objects (objects that are still in use) from the root set, which includes global variables, stack frames, and other roots. This marking phase is performed concurrently with the application’s execution.</li></ul><p><strong>2. Concurrent Sweep:</strong></p><ul><li>After marking, the garbage collector enters the sweep phase, where it reclaims memory from objects that are not marked as reachable. This phase is also performed concurrently, allowing the application to continue executing. The garbage collector is responsible for identifying and freeing up memory from unreachable objects.</li></ul><p><strong>3. Memory Reclamation:</strong></p><ul><li>During the sweep phase, the garbage collector identifies memory that is no longer in use and returns it to the heap. This memory can then be reused for new allocations.</li></ul><p><strong>4. Parallelism:</strong></p><ul><li>To minimize the impact on application performance, the garbage collector takes advantage of parallelism. It uses multiple threads to perform the marking and sweeping phases concurrently with the application’s execution.</li></ul><h4>Impact on the Use of Pointers:</h4><ol><li><strong>Automatic Memory Management:</strong></li></ol><ul><li>Go’s garbage collector allows developers to focus on writing code without manually managing memory allocation and deallocation. Pointers can be used freely, and the garbage collector takes care of reclaiming memory when it’s no longer needed.</li></ul><p><strong>2. Avoiding Memory Leaks:</strong></p><ul><li>Pointers can be used to create complex data structures, and the garbage collector ensures that the memory associated with these structures is reclaimed when there are no more references to them. This helps avoid memory leaks that could occur if the memory is not automatically managed.</li></ul><p><strong>3. Reference Counting Not Needed:</strong></p><ul><li>Unlike some other languages, Go’s garbage collector does not rely on reference counting. Reference counting can lead to performance overhead and challenges in handling circular references. Go’s garbage collector can handle circular references effectively.</li></ul><p><strong>4. Safe Use of Pointers:</strong></p><ul><li>Developers can use pointers in Go without explicit concern for manual memory deallocation. As long as the pointers are within the reach of the garbage collector, the memory associated with the pointed-to objects will be automatically managed.</li></ul><p><strong>5. Avoiding Dangling Pointers:</strong></p><ul><li>Go’s garbage collector helps avoid issues such as dangling pointers, where a pointer points to a memory location that has been freed. The garbage collector ensures that memory is only reclaimed when it is no longer reachable.</li></ul><h3>Explain the difference between stack and heap memory in Go.</h3><h4>Stack Memory:</h4><ol><li><strong>Size and Speed:</strong></li></ol><ul><li>The stack is a region of memory with a fixed size allocated for each goroutine (concurrent execution unit in Go). The size of the stack is typically small, and its allocation and deallocation are fast.</li></ul><p><strong>2. Purpose:</strong></p><ul><li>The stack is primarily used for storing local variables and managing the execution flow of functions. Each goroutine has its stack, and the stack frames hold information such as function parameters, local variables, and return addresses.</li></ul><p>3. <strong>Automatic Allocation and Deallocation:</strong></p><ul><li>Memory on the stack is automatically allocated and deallocated as function calls are made and returned. This makes the stack efficient for managing local variables with a known lifetime.</li></ul><p><strong>4. Scope:</strong></p><ul><li>The scope of variables in the stack is limited to the function in which they are declared. Once a function returns, the memory associated with its stack frame is automatically freed.</li></ul><p><strong>5. Fast Access:</strong></p><ul><li>Accessing variables on the stack is fast, as it involves simply adjusting the stack pointer.</li></ul><h4>Heap Memory:</h4><ol><li><strong>Dynamic Allocation:</strong></li></ol><ul><li>The heap is a region of memory used for dynamic memory allocation. It has a larger size compared to the stack and is shared among all goroutines.</li></ul><p><strong>2. Lifetime:</strong></p><ul><li>Memory allocated on the heap does not have a predetermined lifetime tied to function calls. It persists until explicitly deallocated or until the program exits.</li></ul><p><strong>3. Manual Allocation and Deallocation:</strong></p><ul><li>Memory on the heap must be manually allocated and deallocated by the programmer. Go’s garbage collector automates the process of deallocating memory that is no longer in use, reducing the need for explicit memory management.</li></ul><p><strong>4. Reference Storage:</strong></p><ul><li>Complex data structures, such as slices, maps, and dynamically allocated arrays, are typically stored on the heap. Pointers to heap-allocated memory can be shared among different parts of a program.</li></ul><p><strong>5. Slower Access:</strong></p><ul><li>Accessing variables on the heap involves dereferencing pointers, which can be slower compared to accessing variables on the stack. However, the benefits of dynamic allocation and a longer lifetime outweigh the performance trade-offs in many cases.</li></ul><h4>Common Use Cases:</h4><p><strong>Stack:</strong></p><ul><li>Local variables with a short lifetime (e.g., function parameters, temporary variables).</li><li>Function call information and return addresses.</li></ul><p><strong>Heap:</strong></p><ul><li>Dynamically allocated data structures with an unknown or longer lifetime (e.g., slices, maps, complex objects).</li><li>Data that needs to persist beyond the scope of a single function or goroutine.</li></ul><h3>When might you use the new function to allocate memory?</h3><p>In Go, the new function is used to allocate memory for a new variable and initialize it to the zero value of its type. The new function returns a pointer to the newly allocated memory. It is important to note that new only initializes the memory; it does not zero-initialize the memory for types with a zero value other than the zero value of their type.</p><p>Here are some scenarios where you might use the new function in Go:</p><ol><li><strong>Allocating Memory for Basic Types:</strong></li></ol><ul><li>When you need to allocate memory for a single value of a basic type (int, float, bool, etc.), and you want it to be initialized to its zero value.</li></ul><pre>// Allocate memory for an integer and initialize it to zero<br>p:= new(int)</pre><p><strong>2. Allocating Memory for Structs:</strong></p><ul><li>When you want to allocate memory for a struct and initialize its fields to their zero values.</li></ul><pre>type Point struct {<br>    X, Y int<br>}<br><br>// Allocate memory for a Point struct and initialize its fields to zero values<br>p := new(Point)</pre><p><strong>3. Creating Pointers to Custom Types:</strong></p><ul><li>When you want to create a pointer to a custom type and initialize it to the zero value of that type.</li></ul><pre>type Person struct {<br>    Name string<br>    Age  int<br>}<br><br>// Allocate memory for a Person struct and initialize its fields to zero values<br>p := new(Person)</pre><p><strong>4. Working with Pointers in Functions:</strong></p><ul><li>When working with pointers in functions, you want to return a pointer to a newly allocated value.</li></ul><pre>func createIntPointer() *int {<br>    return new(int)<br>}</pre><p>In this example, the createIntPointer function returns a pointer to a newly allocated integer.</p><p><strong>5. Dynamic Memory Allocation:</strong></p><ul><li>In cases where you need to allocate memory dynamically and explicitly manage the memory allocation process.</li></ul><pre>// Allocate memory for an array of integers<br>arr := new([5]int)</pre><p>This can be useful in scenarios where you need to manage memory manually, but in typical Go code, such manual memory management is rare, thanks to the garbage collector.</p><h4>Difference Between</h4><pre>var p int <br>p := new(int)</pre><p>In Go, the statements p := new(int) and var p int both involve the declaration and initialization of a variable named p, but they have different meanings and use cases.</p><p><strong>1. p := new(int)</strong>:</p><ul><li>This statement uses the new function to dynamically allocate memory for a new integer on the heap, and it initializes the variable p with a pointer to that newly allocated memory. The type p is *int (pointer to an integer).</li></ul><pre>p := new(int)</pre><ul><li>After this statement, p is a pointer variable pointing to a newly allocated integer on the heap. The value of the integer is the zero value for int (which is 0).</li></ul><p><strong>2. var p int</strong>:</p><ul><li>This statement declares a variable named p of type int and initializes it with the zero value of the int type. The memory for this variable is allocated on the stack.</li></ul><pre>var p int</pre><p>After this statement, p is a variable of type int with a value of 0.</p><h3>New vs Make</h3><h4>new Function:</h4><ol><li><strong>Use Case:</strong></li></ol><ul><li>new is used for general-purpose memory allocation.</li><li>It is primarily used with value types, such as integers, structs, or user-defined types.</li></ul><p><strong>2. Syntax:</strong></p><ul><li>new(T) returns a pointer to a newly allocated zeroed value of type T.</li><li>Example:</li></ul><pre>p := new(int)</pre><h4>make Function:</h4><ol><li><strong>Use Case:</strong></li></ol><ul><li>make is used for the allocation and initialization of certain built-in data structures, such as slices, maps, and channels.</li><li>It is used when you need to create and initialize a data structure that requires some initialization.</li></ul><p><strong>2. Syntax:</strong></p><ul><li>make(T, args) creates and initializes a value of type T.</li><li>It is specific to slices, maps, and channels.</li><li>Examples:</li></ul><pre>slice := make([]int, 5, 10)<br>m := make(map[string]int)<br>ch := make(chan int)</pre><h3>Discuss the role of pointers in the manipulation of slices and arrays.</h3><p>Pointers play a significant role in the manipulation of slices and arrays in Go, providing a means to access and modify elements in these data structures more efficiently. Understanding how pointers work with slices and arrays is crucial for effective memory management and efficient code.</p><h4>Arrays:</h4><ol><li><strong>Pointer to Array:</strong></li></ol><ul><li>A pointer can point to the first element of an array. This allows for easy traversal and manipulation of array elements.</li></ul><pre>arr := [3]int{1, 2, 3}<br>var p *int<br>p = &amp;arr[0] // p now points to the first element of arr<br><br>// Access and modify elements using the pointer<br>*p = 99</pre><p><strong>2. Pointer Arithmetic:</strong></p><ul><li>Pointer arithmetic can be used to navigate through array elements. This is particularly useful when iterating over an array.</li></ul><pre>arr := [3]int{1, 2, 3}<br>p := &amp;arr[0]<br><br>for i := 0; i &lt; len(arr); i++ {<br>    // Access elements using pointer arithmetic<br>    fmt.Println(*p)<br>    p = p + 1 // Move to the next element<br>}</pre><h4>Slices:</h4><ol><li><strong>Slice Header:</strong></li></ol><ul><li>A slice is a dynamic, flexible view of an array. It includes a pointer to the underlying array, the length, and the capacity.</li></ul><pre>arr := [5]int{1, 2, 3, 4, 5}<br>slice := arr[1:4] // Slice referencing elements 2, 3, 4<br><br>// Accessing and modifying elements using the slice<br>slice[0] = 99</pre><p><strong>2. Pointer to Slice:</strong></p><ul><li>A pointer can also point to the first element of a slice. The pointer provides a way to traverse the elements within the slice.</li></ul><pre>arr := [5]int{1, 2, 3, 4, 5}<br>slice := arr[1:4]<br>var p *int<br>p = &amp;slice[0] // p now points to the first element of the slice<br><br>// Accessing and modifying elements using the pointer<br>*p = 99</pre><p><strong>3. Pointer Arithmetic with Slices:</strong></p><ul><li>Similar to arrays, pointer arithmetic can be applied to slices for navigation through elements.</li></ul><pre>arr := [5]int{1, 2, 3, 4, 5}<br>slice := arr[1:4]<br>p := &amp;slice[0]<br><br>for i := 0; i &lt; len(slice); i++ {<br>    // Access elements using pointer arithmetic<br>    fmt.Println(*p)<br>    p = p + 1 // Move to the next element<br>}</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2856456a710f" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>