<?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"><channel><title><![CDATA[ferztyle.me]]></title><description><![CDATA[Practical Golang, AWS, and DevOps posts for engineers who want to understand the why, not just copy the code. Written by a Senior SRE from Paraguay.]]></description><link>https://ferztyle.me</link><image><url>https://cdn.hashnode.com/uploads/logos/61db385c3ce4b2377adfdcda/af07abf2-2daa-47ed-a6c2-c0baa1dc3898.png</url><title>ferztyle.me</title><link>https://ferztyle.me</link></image><generator>RSS for Node</generator><lastBuildDate>Sat, 14 Nov 2026 05:10:15 GMT</lastBuildDate><atom:link href="https://ferztyle.me/rss.xml" rel="self" type="application/rss+xml"/><language><![CDATA[en]]></language><ttl>60</ttl><item><title><![CDATA[Build an MCP Server in Go (Part 3): How IRSA and EKS Pod Identity Actually Work]]></title><description><![CDATA[IRSA vs EKS Pod Identity explained: how ServiceAccounts, RBAC, and OIDC actually grant AWS permissions to your pods.]]></description><link>https://ferztyle.me/build-an-mcp-server-in-go-part-3-how-irsa-and-eks-pod-identity-actually-work</link><guid isPermaLink="true">https://ferztyle.me/build-an-mcp-server-in-go-part-3-how-irsa-and-eks-pod-identity-actually-work</guid><category><![CDATA[EKS]]></category><category><![CDATA[mcp]]></category><category><![CDATA[Kubernetes]]></category><category><![CDATA[AWS]]></category><category><![CDATA[Devops]]></category><category><![CDATA[Platform Engineering ]]></category><dc:creator><![CDATA[Fer]]></dc:creator><pubDate>Thu, 27 Aug 2026 15:56:49 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/61db385c3ce4b2377adfdcda/88944059-5d2c-489c-a823-56f610164d15.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Everything the MCP server could check through <a href="https://ferztyle.me/build-an-mcp-server-in-go-part-2-building-the-mcp-tool-layer">Part 2</a> lives inside the cluster. But "my pod can't reach S3" is very often not a Kubernetes problem at all, it's a workload identity problem, and that identity lives partly on the Kubernetes side (the ServiceAccount) and partly on the AWS side (IAM, and now EKS Pod Identity). Before building a tool that diagnoses it, it's worth actually understanding how it works; most of the confusion people run into comes from treating IRSA and Pod Identity as interchangeable, when they solve the same problem through genuinely different mechanisms.</p>
<hr />
<h2>How pod permissions actually work on EKS</h2>
<p>Before touching the diagnostic tool, it's worth stopping and explaining this properly, because "how does a pod get AWS permissions" trips up almost everyone the first time, and the two mechanisms work in genuinely different ways under the hood.</p>
<h3>The problem neither mechanism existed to solve</h3>
<p>An EC2 instance gets AWS credentials through an instance profile, no secrets anywhere, the instance just asks a local metadata endpoint (IMDS) and gets temporary credentials back, automatically. A pod is not an instance. Dozens of pods can run on the same EC2 node, each one potentially needing <em>different</em> AWS permissions; the <code>checkout-service</code> pod should be able to write to one S3 bucket, the <code>image-resizer</code> pod to a different one, and neither should be able to touch what the other can. If every pod on a node just inherited the node's IAM role, that isolation is gone; any pod could do anything the node itself could do.</p>
<p><strong>Before:</strong></p>
<img src="https://cdn.hashnode.com/uploads/covers/61db385c3ce4b2377adfdcda/3f31fc59-7dc0-4c92-b718-a46b28db00b0.png" alt="" style="display:block;margin:0 auto" />

<p>Both IRSA and Pod Identity exist to solve exactly this: giving individual pods their own, scoped-down AWS identity, distinct from the node they happen to be running on and from every other pod sharing that node.</p>
<p><strong>Now:</strong></p>
<img src="https://cdn.hashnode.com/uploads/covers/61db385c3ce4b2377adfdcda/88b41ba1-77c0-4015-b60f-553f04534d83.png" alt="" style="display:block;margin:0 auto" />

<hr />
<h3>What a Kubernetes ServiceAccount actually is</h3>
<p>Both mechanisms above lean on something Kubernetes already has, so it's worth pinning down before going further: a <strong>ServiceAccount</strong> is Kubernetes's own concept of "an identity a pod runs as," entirely separate from AWS and predating both IRSA and Pod Identity by years. It has nothing to do with AWS by default, its original job is purely internal to the cluster.</p>
<p>Every pod runs as some ServiceAccount, whether you set one explicitly or not, if you don't specify one, the pod gets the <code>default</code> ServiceAccount for its namespace automatically. A ServiceAccount is a real Kubernetes object, small and unremarkable on its own:</p>
<pre><code class="language-yaml">apiVersion: v1
kind: ServiceAccount
metadata:
  name: checkout-service
  namespace: production
</code></pre>
<p>Its native purpose is to authenticate to the Kubernetes API server itself, not AWS. Kubernetes automatically mounts a token for the pod's ServiceAccount into the container filesystem, and that token is what lets, say, a controller running inside the cluster call <code>kubectl</code>-equivalent API operations as "the <code>checkout-service</code> identity", with whatever RBAC permissions (<code>Role</code>/<code>RoleBinding</code> or <code>ClusterRole</code>/<code>ClusterRoleBinding</code>) have been granted to that ServiceAccount. This is the exact same object <code>check_endpoints</code> and <code>describe_pod</code> implicitly rely on: the RBAC section back in <a href="https://ferztyle.me/build-an-mcp-server-in-go-part-2-building-the-mcp-tool-layer">Part 2</a> that scoped this MCP server's own <code>ServiceAccount</code> to <code>get</code>/<code>list</code>/<code>watch</code>; that's this same mechanism, just describing what the <em>server itself</em> is allowed to do inside the cluster.</p>
<p>What both IRSA and Pod Identity do is <em>extend</em> that existing identity outward, to AWS, instead of inventing a new one. That's why IRSA works by annotating a ServiceAccount rather than creating some new AWS-specific object, and why Pod Identity's association is keyed on a namespace/ServiceAccount pair rather than anything else.</p>
<blockquote>
<p>A ServiceAccount was already sitting there as "the identity of this pod" in Kubernetes' own model, and both mechanisms are answers to the same follow-up question: how do I get <em>that</em> identity recognized by AWS too?</p>
</blockquote>
<h3>RBAC: what a ServiceAccount is actually allowed to do</h3>
<p>A ServiceAccount by itself is just an identity, a name Kubernetes can authenticate. It comes with <em>zero</em> permissions attached. What decides what that identity is actually allowed to do inside the cluster is a separate system: <strong>RBAC</strong>, Role-Based Access Control.</p>
<p>RBAC works through four object types, and the relationship between them is the whole model:</p>
<ul>
<li><p><code>Role</code> (or <code>ClusterRole</code>, the cluster-wide version), a set of permissions, expressed as verbs on resources. Something like "can <code>get</code> and <code>list</code> <code>pods</code> in the <code>production</code> namespace." A <code>Role</code> on its own grants nothing to anyone, it's a description of a permission set, sitting unused until something is bound to it.</p>
</li>
<li><p><code>RoleBinding</code> (or <code>ClusterRoleBinding</code>), the thing that actually connects a <code>Role</code> to an identity. This is where a ServiceAccount (or a user, or a group) gets named and paired with a<code>Role</code>, and only once that binding exists does the permission become real.</p>
</li>
</ul>
<blockquote>
<p><strong>Put together:</strong> a ServiceAccount is <em>who</em>, a <code>Role</code> is <em>what's allowed</em>, and a <code>RoleBinding</code> is the <em>because I said so</em> connecting the two. Kubernetes checks all three together on every single API request, "is the ServiceAccount making this call bound, via some RoleBinding, to a Role that permits this specific verb on this specific resource", and denies anything that doesn't match.</p>
</blockquote>
<p>This is exactly what <a href="https://ferztyle.me/build-an-mcp-server-in-go-part-2-building-the-mcp-tool-layer">Part 2's</a> "RBAC scope the service account, not just the interface" practice was describing, now with the actual mechanism behind it named: this MCP server runs under its own ServiceAccount, which needs a <code>ClusterRole</code> granting only <code>get</code>/<code>list</code>/<code>watch</code> (never <code>create</code>/<code>update</code>/<code>delete</code>/<code>patch</code>), connected by a <code>ClusterRoleBinding</code>. The read-only guarantee built into <code>KubeClient</code>'s Go interface in <a href="https://ferztyle.me/build-an-mcp-server-in-go-part-1-designing-a-diagnostic-grade-kubernetes-client">Part 1</a> and the read-only guarantee enforced by RBAC here are two independent layers checking the same thing from different directions; the Go code structurally can't call a write operation because the interface has none, and even if it somehow did, RBAC would reject the request at the API server before it touched anything. Neither one depends on the other holding; both have to fail at once for something to go wrong.</p>
<p>It's also worth being precise about where RBAC's authority ends, since that boundary is exactly why this post exists: <strong>RBAC only governs the Kubernetes API.</strong> It has no opinion at all about what a pod is allowed to do once it starts making calls to AWS instead of to<code>kube-apiserver</code>, a ServiceAccount can be tightly scoped under RBAC and still hold an overly broad IAM role through IRSA or Pod Identity, because those are a completely separate permission system, checked by AWS, not by Kubernetes. That gap, RBAC stopping exactly at the cluster's edge, is the reason <code>diagnose_workload_identity</code> has to exist as its own tool rather than just being another RBAC check.</p>
<img src="https://cdn.hashnode.com/uploads/covers/61db385c3ce4b2377adfdcda/f524f34c-1777-4c47-add6-b8ce11232784.svg" alt="" style="display:block;margin:0 auto" />

<p>One <code>ServiceAccount</code>, two independent extensions. RBAC (left) is entirely a Kubernetes-side concern, it never leaves the cluster. IRSA and Pod Identity (right) both start from that same <code>ServiceAccount</code> but end up at AWS through completely different trust mechanisms, which is exactly why diagnosing one has nothing in common with diagnosing the other. The two sections below walk through each AWS-side path in detail.</p>
<hr />
<h2>IRSA: a pod proves who it is directly to AWS</h2>
<p>IRSA (IAM Roles for Service Accounts) works by turning a Kubernetes ServiceAccount into something AWS can verify cryptographically, using OpenID Connect (OIDC).</p>
<p><strong>OIDC (OpenID Connect)</strong> itself is worth grounding first, since everything else in this section builds on it. It's an identity protocol built on top of OAuth 2.0, and it solves a specific problem: how does party B trust a claim about identity made by party A, without B having to call A up and ask "is this real?" every single time? OIDC's answer is the JWT (JSON Web Token), a compact, signed piece of text containing claims like "this is ServiceAccount <code>X</code>, in namespace <code>Y</code>, issued at time <code>Z</code>". The token is signed with a private key only the issuer holds, and anyone who has the issuer's corresponding <em>public</em> key can verify that signature offline, no network call back to the issuer required, no shared secret sitting in a config file waiting to leak. That's the whole trick: proving something is genuine by checking a signature, not by trusting whoever happens to be presenting it. It's the same reason OIDC has become the backbone of "log in with X" buttons everywhere, the token itself carries proof of who issued it.</p>
<p>Before the rest of the flow makes sense, it's also worth being clear on what an <strong>OIDC issuer</strong> actually is, and, just as importantly, where it actually runs, since "the cluster's own issuer" is easy to misread as something running alongside your workloads. In OIDC terms, the <em>issuer</em> is the party that signs and stands behind tokens; Google, in the "Sign in with Google" example, or in this case, EKS itself.</p>
<img src="https://cdn.hashnode.com/uploads/covers/61db385c3ce4b2377adfdcda/2e66046c-c141-49e1-9cec-cd0841d6f76d.svg" alt="" style="display:block;margin:0 auto" />

<p>Every EKS cluster gets its own OIDC issuer: a public HTTPS endpoint, unique to that cluster, that serves the OIDC discovery document and the JWKS (the public keys needed to verify token signatures). That endpoint is part of the <strong>EKS control plane</strong>, hosted and managed by AWS, the same way <code>kube-apiserver</code> itself is, not a pod running on your nodes. The actual signing of ServiceAccount tokens happens inside <code>kube-apiserver</code> using a private key the control plane holds; the issuer endpoint is just where the corresponding public key gets published, so AWS STS can fetch it and verify signatures later without ever calling back into your cluster.</p>
<p>Registering that issuer with AWS IAM (step 1 below) is what lets IAM trust tokens signed by <em>your</em> cluster specifically; an OIDC provider registered in one AWS account only vouches for tokens from the one EKS cluster it points at, which is exactly why the trust policy's <code>Federated</code> principal has to reference this cluster's specific issuer URL, not some generic "any EKS cluster" identity.</p>
<p>Here's the flow, step by step:</p>
<ol>
<li><p>When you set up IRSA, your EKS cluster's OIDC issuer gets registered with AWS IAM as a trusted identity provider. This is a one-time step per cluster.</p>
</li>
<li><p>You annotate a ServiceAccount with <code>eks.amazonaws.com/role-arn: arn:aws:iam::...:role/my-role</code>. An <strong>annotation</strong> here just means ordinary Kubernetes metadata, a key-value pair stored under <code>metadata.annotations</code> on the object, the same mechanism used for all sorts of unrelated things across the ecosystem. Unlike labels, which Kubernetes uses to select and group objects, annotations aren't used for selection; they're just data a controller or webhook can read to change its behavior. In this case:</p>
</li>
</ol>
<p>yaml</p>
<pre><code class="language-yaml">   apiVersion: v1
   kind: ServiceAccount
   metadata:
     name: checkout-service
     namespace: production
     annotations:
       eks.amazonaws.com/role-arn: arn:aws:iam::123456789012:role/checkout-s3-reader
</code></pre>
<p>That specific <code>eks.amazonaws.com/role-arn</code> key is what the mutating webhook in the next step is watching for; its presence is the trigger, and its value is the role the webhook tells the pod to assume.</p>
<p>3. When a pod using that ServiceAccount starts, a mutating webhook (installed as part of the EKS setup) injects a JWT, a signed token proving "this pod belongs to ServiceAccount <code>X</code> in namespace <code>Y</code>, in this specific cluster", into the pod as a file, along with environment variables (<code>AWS_ROLE_ARN</code>, <code>AWS_WEB_IDENTITY_TOKEN_FILE</code>) telling the AWS SDK where to find it.</p>
<p>A <strong>mutating webhook</strong> is part of Kubernetes' admission control pipeline, the sequence of checks every API request passes through between "the request is authenticated" and "the object actually gets written to etcd". Here's the full sequence for something like <code>kubectl apply -f pod.yaml</code>:</p>
<ol>
<li><p><strong>Authentication</strong>: who is making this request?</p>
</li>
<li><p><strong>Authorization</strong>: RBAC check: is this identity allowed to do this?</p>
</li>
<li><p><strong>Mutating admission webhooks</strong>: a chance for registered external services to <em>modify</em> the object before it's persisted.</p>
</li>
<li><p><strong>Object schema validation</strong>: is the (possibly now-modified) object well-formed?</p>
</li>
<li><p><strong>Validating admission webhooks</strong>: a chance for external services to <em>approve or reject</em> the final object, no more modifications allowed.</p>
</li>
<li><p><strong>Persisted to etcd</strong>: the object is now real.</p>
</li>
</ol>
<p>A mutating webhook is registered via a <code>MutatingWebhookConfiguration</code> pointing at an HTTPS endpoint, usually a small service running as its own Deployment in the cluster. When a matching request comes in (here, Pod <code>CREATE</code>), <code>kube-apiserver</code> pauses, sends the object to that endpoint, and applies whatever JSON patch comes back before continuing.</p>
<p>For IRSA, this is the <strong>Amazon EKS Pod Identity Webhook</strong> (an IRSA-era name that predates EKS Pod Identity the newer mechanism, which is a frequent source of confusion). It looks up the pod's <code>spec.serviceAccountName</code>, checks that ServiceAccount for the <code>eks.amazonaws.com/role-arn</code> annotation from step 2, and if present, patches in the projected token volume and the two environment variables above. None of this appears anywhere in the pod spec as written, it's injected transparently at admission time, which is exactly why IRSA "just works" once the annotation is set, with nothing else to configure on the pod itself.</p>
<p>4. When your Go code makes its first AWS API call, the SDK automatically reads that token and calls <code>sts:AssumeRoleWithWebIdentity</code>, presenting the JWT directly to AWS Security Token Service.</p>
<p>5. STS verifies the JWT's signature against the cluster's registered OIDC provider, checks the IAM role's trust policy for a matching condition (the specific <code>sub</code> claim, <code>system:serviceaccount:&lt;namespace&gt;:&lt;serviceaccount&gt;</code>), and if everything lines up, hands back temporary credentials.</p>
<blockquote>
<p>The important thing to notice: <strong>the pod talks to AWS STS directly.</strong> No extra agent runs in the cluster to make this work, the SDK, the token file, and STS are the whole path. That also means the trust policy is where all the real security logic lives: it's the <em>only</em> thing standing between "I have a valid JWT" and "I get to assume this specific role."</p>
</blockquote>
<img src="https://cdn.hashnode.com/uploads/covers/61db385c3ce4b2377adfdcda/708d62ff-bfe5-4085-90ba-77d1113dbade.svg" alt="" style="display:block;margin:0 auto" />

<p>Same five steps as above, made concrete: a pod running as the <code>checkout-service</code> ServiceAccount wants to read an object from S3. Its <code>AWS SDK</code> component presents the JWT sitting in its <code>JWT Token</code> file to AWS STS (1), STS checks that token and the requested role against AWS IAM (3), IAM confirms the trust relationship checks out against the registered OIDC identity provider and the role's attached policies (3–4), STS hands back temporary credentials (5), and only then does the pod call S3 directly (6), S3 itself never sees the JWT at all, only the temporary credentials STS issued.</p>
<hr />
<h2>Pod Identity: an in-cluster agent brokers the exchange</h2>
<p>EKS Pod Identity, AWS's newer mechanism, moves that broker inside the cluster instead. Different flow:</p>
<ol>
<li><p>Instead of an OIDC trust relationship, you create an association, a record, stored in AWS via the EKS API, saying "ServiceAccount X in namespace Y on cluster Z maps to IAM role R." No OIDC provider, no cluster-specific string embedded in an IAM trust policy.</p>
</li>
<li><p>A DaemonSet called the EKS Pod Identity Agent runs on every node, alongside your workloads.</p>
</li>
<li><p>The same kind of mutating webhook sets environment variables on the pod, but this time pointing the AWS SDK at the local agent (AWS_CONTAINER_CREDENTIALS_FULL_URI, a standard mechanism the SDK already supports for container environments, the same one ECS tasks use), not at AWS directly.</p>
</li>
<li><p>When your Go code makes its first AWS call, the SDK requests credentials from that local endpoint instead of STS. The Pod Identity Agent receives that request, looks up the association for this pod's namespace/ServiceAccount, and calls a dedicated API (eks-auth:AssumeRoleForPodIdentity) on the pod's behalf to get temporary credentials, then hands them back to the SDK.</p>
</li>
</ol>
<p>It's worth being precise about where STS actually sits in this chain, since it's easy to assume Pod Identity skips STS entirely, it doesn't, it just moves further away from the pod. The pod's SDK never talks to STS or IAM directly; it only ever talks to the local agent.</p>
<img src="https://cdn.hashnode.com/uploads/covers/61db385c3ce4b2377adfdcda/be4f3c57-0180-4362-acff-5809d22a812c.svg" alt="" style="display:block;margin:0 auto" />

<p>Credentials flow back up the same four steps in reverse: STS to the EKS Auth API, to the agent, to the pod's SDK, so the diagram only needs to show one direction to be complete. The practical difference from IRSA's diagram earlier: there, the pod called STS itself, in one hop. Here, there are two extra hops and a different AWS API in the middle, which is exactly why Pod Identity failures can look different from IRSA failures even though both ultimately end at STS.</p>
<p>The trust policy here looks completely different too: instead of trusting an OIDC federated principal, it trusts the AWS service pods.eks.amazonaws.com directly. The association, which pod maps to which role, lives entirely in AWS, not encoded into the trust policy's conditions at all.</p>
<h3>The EKS Auth API</h3>
<p>The agent calls eks-auth:AssumeRoleForPodIdentity, and it's worth being precise about what that actually is, too: Amazon EKS Auth is its own standalone AWS service, with its own service ID (eks-auth), its own regional endpoint, and its own SDK client in every language, separate from both the general eks API and from iam/sts. It's part of the broader EKS product family, but it isn't the Kubernetes control plane (kube-apiserver, etcd, and friends, Kubernetes-specific infrastructure) and it isn't IAM's API either (IAM is global, not regional, with its own iam:* action namespace). Architecturally, EKS Auth sits as a peer to IAM and STS, not a part of either, a purpose-built bridge service that receives the pod's own projected token (audience pods.eks.amazonaws.com, different from IRSA's sts.amazonaws.com token), checks whether a Pod Identity association exists for this namespace/ServiceAccount, and whether the target role's trust policy allows it. Only then, internally, an implementation detail your code and the agent never see directly, does it call STS to actually mint the credentials, and hand them back down the chain.</p>
<p>One practical consequence of EKS Auth being its own regional service: a private EKS cluster with no outbound internet access needs its own VPC endpoint specifically for eks-auth, distinct from the endpoints for eks, sts, and everything else. It's newer and less well-known than the others, which makes it an easy one to miss when locking down a private cluster's networking, Pod Identity will simply fail to issue credentials with no obvious explanation until that endpoint exists.</p>
<hr />
<h2>Why this distinction matters for diagnosis</h2>
<p>This is exactly why diagnose_workload_identity has to check two completely different places rather than one: an IRSA misconfiguration is almost always a trust policy problem (wrong OIDC provider, wrong sub condition, wrong namespace/ServiceAccount string), diagnosable by reading the role. A Pod Identity misconfiguration can be an association problem, no association exists at all for this ServiceAccount, something no amount of staring at an IAM role will ever reveal, since the role's trust policy for Pod Identity looks identical regardless of which ServiceAccounts happen to be associated with it. You have to ask AWS's EKS API directly, which is exactly what FindPodIdentityRole does.</p>
<p>And since both can be configured on the same ServiceAccount at once, very common mid-migration, and Pod Identity silently wins when both are present, a pod can have a perfectly correct-looking IRSA setup that's doing nothing at all, because an association nobody remembers creating is quietly overriding it. That's not a rare edge case to handle defensively; it's routine enough right now, with teams actively migrating from IRSA to Pod Identity, that it deserves to be the first thing the tool checks.</p>
<hr />
<h2>Summary: one rule that matters most</h2>
<p>A pod gets AWS credentials one of two ways on EKS: IRSA (OIDC-based, checked via the ServiceAccount annotation and the IAM role's trust policy) or EKS Pod Identity (association-based, checked via the EKS API). Both can be configured at once during a migration, and when they are, Pod Identity wins, the mutating webhook prefers it whenever both are present. A role that looks unused from the Kubernetes side might still be the one actually granting access, or the one silently being ignored, and that precedence rule is the first thing any diagnostic tooling built on top of this needs to check.</p>
<h3>Three things worth carrying forward:</h3>
<p>A ServiceAccount is Kubernetes's own native identity concept, and RBAC governs it only inside the cluster, neither has any authority once a pod starts talking to AWS instead of kube-apiserver. IRSA and Pod Identity both extend that same ServiceAccount identity outward to AWS, but through completely different mechanisms: IRSA is a direct, OIDC-verified call from the pod to STS; Pod Identity routes through an in-cluster agent and an AWS-side association that has no visible trace on the Kubernetes side at all. Diagnosing a failure means checking two unrelated surfaces, an IAM role's trust policy for IRSA, and the EKS API's association records for Pod Identity, because nothing about looking at one tells you anything about the other.</p>
<p>Part 4 builds the actual diagnostic tool on top of everything explained here, a new AWS-facing Go client, a diagnose_workload_identity MCP tool that checks both mechanisms and applies the precedence rule above, and an honest look at what it means for this server to start needing AWS IAM permissions, not just Kubernetes RBAC.</p>
<hr />
<h2><strong>Let's connect!</strong></h2>
<p>One of the best parts of writing in public is the people you meet along the way, engineers at different stages of their journey, working on similar problems from completely different angles.</p>
<p>If something in this post resonated, if you spotted a bug, or if you just want to talk Go, Kubernetes, Platform Engineering, DevOps, or whatever, I'm always happy to hear from you.</p>
<ul>
<li><p><a href="https://www.linkedin.com/in/ferrios/"><strong>LinkedIn</strong></a></p>
</li>
<li><p><a href="https://github.com/FerRiosCosta"><strong>GitHub</strong></a></p>
</li>
<li><p><a href="https://x.com/ferztyle"><strong>Twitter / X</strong></a></p>
</li>
</ul>
<p><em>Building from Asunción, Paraguay 🇵🇾</em></p>
]]></content:encoded></item><item><title><![CDATA[LeetCode 151: Reverse Words in a String in Go]]></title><description><![CDATA[Solve LeetCode 151 (Reverse Words in a String) in Go two ways, split/join and true in-place. Learn what O(1) space really means in Go.]]></description><link>https://ferztyle.me/leetcode-151-reverse-words-in-a-string-in-go</link><guid isPermaLink="true">https://ferztyle.me/leetcode-151-reverse-words-in-a-string-in-go</guid><category><![CDATA[Go Language]]></category><category><![CDATA[golang]]></category><category><![CDATA[Software Engineering]]></category><category><![CDATA[interview]]></category><dc:creator><![CDATA[Fer]]></dc:creator><pubDate>Wed, 19 Aug 2026 15:39:26 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/61db385c3ce4b2377adfdcda/fe99b266-b7a4-40c0-96f3-5638dc4eccb0.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h2>The problem that looks simple until the whitespace shows up</h2>
<p>You open <a href="https://leetcode.com/problems/reverse-words-in-a-string/">LeetCode 151 — Reverse Words in a String</a> expecting a variation on reversing a string, and mostly, that's right. Given <code>"the sky is blue"</code>, you need <code>"blue is sky the"</code>, the <strong>words</strong> reverse order, not the letters inside them.</p>
<p>Then you notice the real complication buried in the constraints: the input can have leading spaces, trailing spaces, and multiple spaces between words (<code>" the sky is blue "</code>), and none of that garbage is allowed to survive into your output.</p>
<p>So this problem is really two problems stacked together: reversing word order, and cleaning up whitespace. This post walks through two ways to solve it in Go, and along the way clears up a common misconception about what "O(1) extra space" actually means once your language doesn't let you mutate strings directly.</p>
<hr />
<h2>Approach 1: split, reverse, join</h2>
<p>The simplest mental model: let the standard library handle the messy whitespace work, then reuse the same two-pointer swap pattern from <a href="https://ferztyle.me/leetcode-345-in-go-reverse-vowels-of-a-string-and-how-strings-bytes-and-runes-work-in-go">reversing vowels</a>, one level up, swapping whole words instead of characters.</p>
<h3>Step 1: Split, with whitespace handled for free</h3>
<pre><code class="language-go">words := strings.Fields(s)
</code></pre>
<p><code>strings.Fields</code> splits on <strong>any run</strong> of whitespace and silently discards empty pieces. That one call solves leading spaces, trailing spaces, and multiple spaces between words, all at once:</p>
<pre><code class="language-go">strings.Fields("  the sky  is blue  ")
// → []string{"the", "sky", "is", "blue"}
</code></pre>
<p>Compare that to <code>strings.Split(s, " ")</code>, which would instead give you <code>["", "", "the", "sky", "", "is", "blue", "", ""]</code>; every extra space becomes an empty string you'd have to filter out yourself. Picking the right stdlib function does half the problem for you here.</p>
<h3>Step 2: Reverse the slice of words</h3>
<p>Same collision two-pointer pattern as <a href="https://ferztyle.me/leetcode-345-in-go-reverse-vowels-of-a-string-and-how-strings-bytes-and-runes-work-in-go">before</a>, <code>left</code> and <code>right</code> start at opposite ends and swap toward the middle. The only difference from reversing vowels is that every element gets swapped unconditionally; there's no "is this a vowel" check gating the swap:</p>
<pre><code class="language-go">left, right := 0, len(words)-1
for left &lt; right {
    words[left], words[right] = words[right], words[left]
    left++
    right--
}
</code></pre>
<h3>Step 3: Join back with single spaces</h3>
<pre><code class="language-go">strings.Join(words, " ")
</code></pre>
<h3>Full Solution</h3>
<pre><code class="language-go">func reverseWords(s string) string {
    words := strings.Fields(s)

    left, right := 0, len(words)-1
    for left &lt; right {
        words[left], words[right] = words[right], words[left]
        left++
        right--
    }

    return strings.Join(words, " ")
}
</code></pre>
<h2>Trace</h2>
<p><code>" the sky is blue "</code></p>
<ol>
<li><p><code>strings.Fields</code> → <code>["the", "sky", "is", "blue"]</code></p>
</li>
<li><p>Reverse → <code>["blue", "is", "sky", "the"]</code></p>
</li>
<li><p><code>strings.Join</code> → <code>"blue is sky the"</code> ✅</p>
</li>
</ol>
<p>Three lines of real logic, and every whitespace edge case handled without writing a single line for it. The cost: <code>strings.Fields</code> allocates a slice of strings (one per word), and <code>strings.Join</code> allocates another buffer for the final result. Fine for most purposes, but not the leanest possible solution, which is exactly what Approach 2 addresses.</p>
<hr />
<h2>Approach 2: reverse-then-reverse, in place</h2>
<p>This is the classic interview follow-up answer: <strong>reverse the entire string first, then reverse each word individually back to normal.</strong> It reuses an idea worth remembering, since it reappears in other problems too: reverse the whole thing, then reverse the parts.</p>
<h3>Why "reverse, then reverse" works</h3>
<p>Take <code>"the sky"</code>. Reverse it completely, character by character:</p>
<pre><code class="language-plaintext">"the sky" → "yks eht"
</code></pre>
<p>The <strong>word order</strong> is now correct (<code>sky</code>'s letters come first, then <code>the</code>'s), but each word's internal letter order got scrambled as a side effect of reversing everything at once. So a second pass fixes just that: scan for each word's boundaries and reverse only that sub-range, back to normal:</p>
<pre><code class="language-plaintext">"yks eht" → "sky eht" → "sky the"
</code></pre>
<p>Result: <code>"sky the"</code>; word order fixed by the full reversal, letters fixed locally afterward, without disturbing the word order that's already correct.</p>
<h3>The part that's actually new: whitespace compaction, in place</h3>
<p>Since we can't call <code>strings.Fields</code> here without giving up the "in place" goal, whitespace has to be compacted manually, using a pattern we haven't needed until now: the <strong>read/write pointer</strong> technique (two pointers moving in the <em>same</em> direction, at different speeds, as opposed to the collision pattern, which moves them toward each other).</p>
<p>Think of it like re-typing a messy sentence onto the same sheet of paper, one pen, no extra paper. You read through with one pointer; every time you find something worth keeping, you write it at the next available spot with a second pointer, which is always at or behind where you're reading, so you never overwrite something you still need.</p>
<pre><code class="language-go">write := 0
read := 0
for read &lt; n {
    for read &lt; n &amp;&amp; b[read] == ' ' {
        read++ // skip spaces entirely
    }
    if read == n {
        break // trailing spaces exhausted
    }
    if write != 0 {
        b[write] = ' ' // exactly one separator, except before the first word
        write++
    }
    for read &lt; n &amp;&amp; b[read] != ' ' {
        b[write] = b[read] // copy the word
        write++
        read++
    }
}
b = b[:write]
n = write
</code></pre>
<p>Why this collapses multiple spaces into one: the inner "skip spaces" loop consumes an <em>entire run</em> of spaces before <code>write</code> ever moves; one space or ten, doesn't matter. Why it drops leading/trailing spaces: the separator is only written <code>if write != 0</code>, so nothing goes in before the first word, and once the last word is copied, there's no new word left to trigger writing a trailing separator.</p>
<h3>Reverse the whole compacted string</h3>
<pre><code class="language-go">reverse(b, 0, n-1)
</code></pre>
<p>using a small unconditional helper:</p>
<pre><code class="language-go">func reverse(b []byte, left, right int) {
    for left &lt; right {
        b[left], b[right] = b[right], b[left]
        left++
        right--
    }
}
</code></pre>
<h3>Reverse each word back to normal</h3>
<pre><code class="language-go">start := 0
for i := 0; i &lt;= n; i++ {
    if i == n || b[i] == ' ' {
        reverse(b, start, i-1)
        start = i + 1
    }
}
</code></pre>
<p>The loop runs to <code>i &lt;= n</code>, one past the last index, specifically so the final word, which has no trailing space to mark its end, still gets caught and reversed.</p>
<h2>Full Solution</h2>
<pre><code class="language-go">func reverseWords(s string) string {
    b := []byte(s)
    n := len(b)

    write := 0
    read := 0
    for read &lt; n {
        for read &lt; n &amp;&amp; b[read] == ' ' {
            read++
        }
        if read == n {
            break
        }
        if write != 0 {
            b[write] = ' '
            write++
        }
        for read &lt; n &amp;&amp; b[read] != ' ' {
            b[write] = b[read]
            write++
            read++
        }
    }
    b = b[:write]
    n = write

    reverse(b, 0, n-1)

    start := 0
    for i := 0; i &lt;= n; i++ {
        if i == n || b[i] == ' ' {
            reverse(b, start, i-1)
            start = i + 1
        }
    }

    return string(b)
}

func reverse(b []byte, left, right int) {
    for left &lt; right {
        b[left], b[right] = b[right], b[left]
        left++
        right--
    }
}
</code></pre>
<p>Three passes, three applications of the same two-pointer family: read/write for compaction, collision for the full reversal, collision again (on sub-ranges) for the per-word fix.</p>
<hr />
<h2>What "extra space" (auxiliary space) means</h2>
<p>When people analyze space complexity, they usually split memory usage into two buckets:</p>
<ul>
<li><p><strong>Input space</strong>: memory used to store the input itself (the string you were given). This doesn't count against you; you didn't choose to receive a big input.</p>
</li>
<li><p><strong>Extra / auxiliary space</strong>: any <em>additional</em> memory your algorithm allocates beyond the input, in order to compute the answer.</p>
</li>
</ul>
<p>"O(1) extra space" means: no matter how large the input <code>n</code> gets, the amount of <strong>additional</strong> memory your algorithm needs stays constant; a fixed handful of variables (a few <code>int</code>s for pointers/indices, maybe one temp variable), and nothing that grows with <code>n</code>.</p>
<h3>What "truly O(1)" looks like, concretely</h3>
<p>Take the classic version of this problem in <strong>C or C++</strong>, where a string is literally a mutable array of characters (<code>char[]</code> or <code>char*</code>) sitting in memory that you already own.</p>
<p>In that world, the reverse-then-reverse-words algorithm works like this:</p>
<ol>
<li><p>You're handed the character array directly; this <em>is</em> your input space, already allocated.</p>
</li>
<li><p>You do the whitespace compaction, the full reversal, and the per-word reversal <strong>directly inside that same array</strong>, using only a few integer index variables (<code>read</code>, <code>write</code>, <code>left</code>, <code>right</code>, <code>start</code>).</p>
</li>
<li><p>When you're done, that <em>same array</em>, now holding the answer, is returned or printed; <strong>no new array was ever created</strong>.</p>
</li>
</ol>
<p>The only extra memory used across the entire algorithm is a small, fixed number of integers; regardless of whether the string is 10 characters or 10 million. That's genuinely O(1) extra space: the auxiliary memory footprint never grows with <code>n</code>.</p>
<h3>So which one is actually "O(1) extra space"? Neither, really, and here's why that matters</h3>
<p>This is worth being precise about, because "O(1) space" gets thrown around loosely.</p>
<p><strong>"Extra" or "auxiliary" space</strong> means memory used <em>beyond</em> the input itself; a fixed handful of index variables counts as O(1) extra space; anything that grows with the input size <code>n</code> doesn't.</p>
<p>In <strong>C or C++</strong>, a string is a mutable <code>char[]</code> you already own. The reverse-then-reverse algorithm edits that array directly and hands the same array back; no new array is ever created. The only extra memory used is a few integers (<code>read</code>, <code>write</code>, <code>left</code>, <code>right</code>), regardless of whether the string is 10 characters or 10 million. That's genuinely O(1) extra space.</p>
<p><strong>Go doesn't let you do that</strong>, because <code>string</code> is immutable by design (this exists so that substrings can safely share underlying memory without one mutation corrupting another). So:</p>
<pre><code class="language-go">b := []byte(s)      // copies the input, O(n) new memory, before any logic runs
// ... in-place work on b ...
return string(b)    // copies again, another O(n) new memory
</code></pre>
<p>Both of those copies are proportional to <code>n</code>. So strictly speaking, <strong>Approach 2's Go implementation is O(n) extra space overall</strong>, not O(1), the in-place <em>logic</em> between those two conversions is O(1) extra beyond the <code>[]byte</code> copy, but the copy itself isn't optional in Go.</p>
<h3>Then what's actually different between the two approaches?</h3>
<p>Since neither is truly O(1) in Go, the real distinction is in <strong>how much intermediate garbage gets created along the way</strong>, constant factors that big-O notation deliberately hides but that matter in practice:</p>
<table>
<thead>
<tr>
<th></th>
<th>Approach 1</th>
<th>Approach 2</th>
</tr>
</thead>
<tbody><tr>
<td>Time</td>
<td>O(n)</td>
<td>O(n)</td>
</tr>
<tr>
<td>Space (Go-accurate)</td>
<td>O(n)</td>
<td>O(n)</td>
</tr>
<tr>
<td>Allocations</td>
<td>One string per word (from <code>strings.Fields</code>) + one buffer for <code>strings.Join</code>, roughly <em>O(number of words) + 1</em></td>
<td>One <code>[]byte</code> copy of the input, mutated in place, one final <code>string()</code> copy, a constant <strong>2</strong>, regardless of word count</td>
</tr>
<tr>
<td>Practical memory pressure</td>
<td>Higher, many small allocations, more garbage-collector work</td>
<td>Lower, few allocations, less GC pressure</td>
</tr>
</tbody></table>
<p>So when this problem's classic follow-up asks "can you do it with O(1) extra space," the honest answer in Go is: <strong>not truly</strong>, since string immutability forces at least one input-sized copy in and one out;</p>
<blockquote>
<p><strong>but Approach 2 is still the intended and meaningfully leaner answer</strong>, because it avoids all the <em>additional</em> per-word allocations Approach 1 introduces on top of that unavoidable baseline.</p>
</blockquote>
<hr />
<h2>Summary</h2>
<ul>
<li><p><strong>Approach 1</strong> (<code>strings.Fields</code> → reverse slice → <code>strings.Join</code>) is the simplest correct solution: whitespace cleanup comes free from the standard library, and the reversal is the same collision two-pointer pattern from earlier problems, just applied to whole words.</p>
</li>
<li><p><strong>Approach 2</strong> (compact → reverse all → reverse each word) is the leaner, interview-favorite solution, introducing the <strong>read/write pointer</strong> pattern for in-place compaction alongside the familiar collision pattern for reversal; two flavors of "two pointers," composed across three passes.</p>
</li>
<li><p><strong>"O(1) extra space" is baseline-dependent.</strong> In C/C++, it means genuinely no new allocations. In Go, string immutability forces an input-sized copy in and out regardless of approach, so the honest framing is: Approach 2 minimizes allocations <em>beyond</em> that unavoidable baseline, rather than achieving true O(1).</p>
</li>
</ul>
<p>That last point is the one worth carrying forward to every future string problem in Go: read space-complexity claims with the question <em>"O(1) relative to what baseline?"</em> in mind, especially in a language where the built-in string type won't let you mutate in place at all.</p>
<hr />
<h2><strong>Let's connect!</strong></h2>
<p>One of the best parts of writing in public is the people you meet along the way, engineers at different stages of their journey, working on similar problems from completely different angles.</p>
<p>If something in this post resonated, if you spotted a bug, or if you just want to talk Go, Kubernetes, Platform Engineering, DevOps, or whatever, I'm always happy to hear from you.</p>
<ul>
<li><p><a href="https://www.linkedin.com/in/ferrios/"><strong>LinkedIn</strong></a></p>
</li>
<li><p><a href="https://github.com/FerRiosCosta"><strong>GitHub</strong></a></p>
</li>
<li><p><a href="https://x.com/ferztyle"><strong>Twitter / X</strong></a></p>
</li>
</ul>
<p><em>Building from Asunción, Paraguay 🇵🇾</em></p>
]]></content:encoded></item><item><title><![CDATA[Build an MCP Server in Go (Part 2): Building the MCP tool layer]]></title><description><![CDATA[Building the MCP tool layer in GO]]></description><link>https://ferztyle.me/build-an-mcp-server-in-go-part-2-building-the-mcp-tool-layer</link><guid isPermaLink="true">https://ferztyle.me/build-an-mcp-server-in-go-part-2-building-the-mcp-tool-layer</guid><category><![CDATA[Go Language]]></category><category><![CDATA[Kubernetes]]></category><category><![CDATA[Devops]]></category><category><![CDATA[mcp]]></category><category><![CDATA[AI]]></category><dc:creator><![CDATA[Fer]]></dc:creator><pubDate>Fri, 14 Aug 2026 13:53:11 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/61db385c3ce4b2377adfdcda/eee79f20-0376-4c21-9b22-c0334c69fb5c.svg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p><a href="https://ferztyle.me/build-an-mcp-server-in-go-part-1-designing-a-diagnostic-grade-kubernetes-client"><em>Part 1</em></a> <em>designs the</em> <code>KubeClient</code> <em>interface this post builds on. If you haven't read it, the short version: a read-only, domain-composed Kubernetes client, pods, events, workloads, nodes, network, config, storage, metrics, with every unbounded query capped before an agent ever touches it.</em></p>
<p>With that client in hand, this post does the rest: wrap it as MCP tools, wire it to an agent, and run the whole thing end-to-end against a real cluster.</p>
<hr />
<h2>What MCP actually is</h2>
<p>Strip away the hype, and MCP is a small, well-defined protocol: a server exposes a list of <strong>tools</strong>, each with a name, a description, and a JSON Schema describing its input. A client, usually an LLM-powered agent, asks the server "what tools do you have," decides which one is relevant to the user's question, and calls it with structured arguments. The server runs the tool and returns a structured result. Repeat, as many times as the agent needs, until it has enough information to answer.</p>
<pre><code class="language-plaintext">Agent (Claude, etc.)
      │
      │  "list your tools"          →  tools/list
      │  ← [list_pods, get_pod_logs, describe_pod, ...]
      │
      │  "call get_pod_logs"        →  tools/call
      │  ← { "logs": "panic: ..." }
      │
      ▼
Your MCP server
      │
      │  client-go
      ▼
Kubernetes API server
</code></pre>
<p>That's the whole mental model. The interesting engineering problem wasn't the protocol, it was the <code>KubeClient</code> interface from part 1. What's left is wrapping it correctly.</p>
<h3>Two ways tools and calls actually travel: stdio vs. HTTP</h3>
<p>The diagram above shows <em>what</em> gets exchanged. It says nothing about <em>how</em> those messages physically move between client and server, that's a separate choice, called the transport, and MCP defines two of them.</p>
<p><strong>Stdio transport</strong> is what this post builds. The client, Claude Desktop, VS Code, spawns your compiled binary as a local child process and talks to it over that process's stdin and stdout. Every <code>tools/list</code> and <code>tools/call</code> message is a line of JSON written to the child's stdin; every response is a line of JSON written back to stdout. There's no network involved, no port to open, no auth to configure: the trust boundary is just "whoever can run this binary already has access to whatever it can reach," which for this server means your kubeconfig. This is exactly why <code>main.go</code> calls <code>server.Run(ctx, &amp;mcp.StdioTransport{})</code>, the server's entire life cycle is tied to one client process spawning it, talking to it, and eventually killing it.</p>
<p><strong>Streamable HTTP transport</strong> is the other option, and it's a genuinely different deployment shape, not just a different function call. The server runs as a long-lived process, think a pod in a cluster, listening on a port, and any number of clients connect to it over the network instead of spawning it. That unlocks things stdio structurally can't do: multiple agents sharing one server, a server that outlives any single client's session, a server nowhere near the machine that's using it. It also introduces problems stdio never has to solve: authenticating requests from strangers on the network, and keeping session state consistent when a client's calls might land on different backend replicas instead of the one process that remembers the conversation so far.</p>
<p>Neither transport is strictly better, they fit different situations. Stdio is the right choice for exactly what this post is: a tool one engineer runs locally, pointed at whatever cluster their kubeconfig currently targets. HTTP is what you'd reach for to run this as shared infrastructure other people's agents connect to, and that jump, with the session handling and auth it requires, is real enough to be its own post rather than a paragraph here.</p>
<hr />
<h2>Project structure</h2>
<pre><code class="language-plaintext">go-k8s-mcp-server/
├── go.mod
├── cmd/
│   └── k8s-mcp-server/
│       └── main.go             ← entry point — wires client, tools, transport
└── internal/
    ├── kubernetes/              ← the KubeClient from part 1, unchanged
    │   ├── client.go
    │   ├── pods.go
    │   ├── workloads.go
    │   ├── nodes.go
    │   ├── events.go
    │   ├── network.go
    │   ├── ingress.go
    │   ├── gateway.go
    │   ├── config.go
    │   ├── storage.go
    │   └── metrics.go
    └── tools/                   ← new in this post
        ├── list_pods.go
        ├── pod_logs.go
        ├── describe_pod.go
        ├── get_events.go
        ├── check_endpoints.go
        ├── describe_ingress.go
        ├── describe_httproute.go
        ├── list_configmap_keys.go
        └── pod_metrics.go
</code></pre>
<p><code>internal/kubernetes/</code> is exactly what part 1 built, nothing changes there. Everything new in this post lives in <code>cmd/k8s-mcp-server/</code> and <code>internal/tools/</code>, following the same <code>cmd/</code> + <code>internal/</code> convention from <a href="https://ferztyle.me/go-packages-and-modules-explained">Go packages and modules explained</a>.</p>
<hr />
<h2>The tool layer</h2>
<p><code>KubeClient</code> answers "what can this program do to a cluster." The tool layer answers a different question: "what is the agent allowed to ask for, and in what shape." These are not the same interface. A <code>KubeClient</code> method might take a <code>LogOptions</code> struct; an MCP tool needs a JSON Schema an LLM can read and a handler that translates one into the other.</p>
<p>We'll use the official Go SDK, <code>github.com/modelcontextprotocol/go-sdk/mcp</code>. It infers JSON Schema directly from Go struct tags and gives you typed handlers. <code>func(ctx, req, In) (*mcp.CallToolResult, Out, error)</code>, so there's no manual schema-writing and no untyped <code>map[string]any</code> argument parsing.</p>
<pre><code class="language-shell">go get github.com/modelcontextprotocol/go-sdk
</code></pre>
<p>Each tool gets its own file, same "one reason to change" rule as the reporter package in the client-go post: a new tool is a new file, not a new branch in a shared switch statement.</p>
<h3>Anatomy of a tool file</h3>
<p>Every tool in this project follows the same four-part shape. Before looking at a real one, it's worth naming each piece, since the same pattern repeats seven times below and it's easier to recognize once you know what you're looking at:</p>
<ul>
<li><p><code>*mcp.Tool</code>: the tool's identity as far as the agent is concerned: a <code>Name</code> the agent calls it by (<code>"list_pods"</code>), and a <code>Description</code> the agent reads to decide <em>when</em> to call it. This is metadata only, it holds no logic and touches no Kubernetes code.</p>
</li>
<li><p><code>In</code> <strong>(the input struct)</strong>, what the agent is allowed to send as arguments, expressed as a normal Go struct with <code>json</code> and <code>jsonschema</code> tags. The SDK turns this struct's shape into the JSON Schema the agent actually sees; you never write schema by hand.</p>
</li>
<li><p><strong>The handler function</strong>: the actual logic, with the signature <code>func(ctx context.Context, req *mcp.CallToolRequest, in In) (*mcp.CallToolResult, Out, error)</code>. This is where the input gets validated, <code>KubeClient</code> gets called, and the result gets shaped into <code>Out</code>. It's an ordinary Go function; nothing about it is MCP-specific beyond its signature.</p>
</li>
<li><p><code>Out</code> <strong>(the output struct)</strong>: what the agent receives back, again a plain Go struct. Returning a typed struct instead of a preformatted string matters: the agent gets structured JSON it can reason over programmatically (checking a <code>Phase</code> field, summing a <code>Restarts</code> count), rather than a paragraph of text it has to parse itself.</p>
</li>
<li><p><strong>The</strong> <code>New*Tool</code> <strong>constructor</strong>: a small function that builds and returns the <code>(*mcp.Tool, handler)</code> pair together, closing over a <code>KubeClient</code> so the handler has something to call. This is what makes each tool independently testable: pass in a fake <code>KubeClient</code>, call the returned handler directly, assert on <code>Out</code>, no MCP machinery involved at all.</p>
</li>
</ul>
<p><code>(*mcp.Tool, handler)</code> is the pair every <code>New*Tool</code> function returns, and the pair <code>mcp.AddTool</code> expects at registration time in <code>server.go</code>, worth keeping that shape in mind, since it's also exactly where the multi-value spread gotcha from the "Common gotchas" section comes from.</p>
<h3><code>list_pods</code></h3>
<p>The pieces above, in a real file: <code>tool</code> below is the <code>*mcp.Tool</code> identity, <code>ListPodsInput</code> is <code>In</code>, the closure returned second is the handler, and <code>ListPodsOutput</code> is <code>Out</code>.</p>
<pre><code class="language-go">// internal/tools/list_pods.go
package tools

import (
    "context"
    "fmt"

    "github.com/modelcontextprotocol/go-sdk/mcp"

    "github.com/FerRiosCosta/go-k8s-mcp-server/internal/kubernetes"
)

// ListPodsInput is inferred into JSON Schema from these struct tags,
// the agent sees "namespace" as an optional string with this description,
// nothing more to write by hand.
type ListPodsInput struct {
    Namespace string `json:"namespace" jsonschema:"Kubernetes namespace to list pods from. Leave empty to list pods across all namespaces."`
}

type PodSummary struct {
    Namespace string `json:"namespace"`
    Name      string `json:"name"`
    Phase     string `json:"phase"`
    Ready     string `json:"ready"`
    Restarts  int32  `json:"restarts"`
}

type ListPodsOutput struct {
    Pods []PodSummary `json:"pods"`
}

// NewListPodsTool returns the tool definition and its handler, bound to
// a concrete KubeClient. Keeping the constructor take the client as a
// parameter (rather than a package-level global) is what keeps this
// testable with a fake client.
func NewListPodsTool(kube kubernetes.KubeClient) (*mcp.Tool, func(context.Context, *mcp.CallToolRequest, ListPodsInput) (*mcp.CallToolResult, ListPodsOutput, error)) {
    tool := &amp;mcp.Tool{
        Name:        "list_pods",
        Description: "List pods in a namespace, or across all namespaces, with phase, readiness, and restart count.",
    }

    handler := func(ctx context.Context, _ *mcp.CallToolRequest, in ListPodsInput) (*mcp.CallToolResult, ListPodsOutput, error) {
        pods, err := kube.ListPods(ctx, in.Namespace)
        if err != nil {
            return nil, ListPodsOutput{}, fmt.Errorf("list_pods: %w", err)
        }

        out := ListPodsOutput{Pods: make([]PodSummary, 0, len(pods.Items))}
        for _, pod := range pods.Items {
            ready, total := 0, len(pod.Status.ContainerStatuses)
            var restarts int32
            for _, cs := range pod.Status.ContainerStatuses {
                if cs.Ready {
                    ready++
                }
                restarts += cs.RestartCount
            }
            out.Pods = append(out.Pods, PodSummary{
                Namespace: pod.Namespace,
                Name:      pod.Name,
                Phase:     string(pod.Status.Phase),
                Ready:     fmt.Sprintf("%d/%d", ready, total),
                Restarts:  restarts,
            })
        }
        return nil, out, nil
    }

    return tool, handler
}
</code></pre>
<p>Two things worth calling out. First, the tool returns a typed <code>ListPodsOutput</code>, not a formatted string, the SDK turns that into structured JSON the agent can reason over, the same way it would parse an API response. Second, the description on the tool itself matters as much as the code: it's the only thing the agent has to decide <em>when</em> to call this versus another tool. Vague descriptions produce agents that call the wrong tool, or the right tool with the wrong arguments, worth testing with real prompts once you've built a few tools, not just checking that the code compiles.</p>
<h3><code>get_pod_logs</code></h3>
<pre><code class="language-go">// internal/tools/pod_logs.go
package tools

import (
    "context"
    "fmt"

    "github.com/modelcontextprotocol/go-sdk/mcp"

    "github.com/FerRiosCosta/go-k8s-mcp-server/internal/kubernetes"
)

type GetPodLogsInput struct {
    Namespace string `json:"namespace" jsonschema:"Kubernetes namespace of the pod."`
    Name      string `json:"name" jsonschema:"Name of the pod."`
    Container string `json:"container" jsonschema:"Container name. Leave empty for the pod's first container."`
    Previous  bool   `json:"previous" jsonschema:"If true, fetch logs from the previous terminated instance of the container. Use this for CrashLoopBackOff pods — the current instance often has no logs yet."`
    TailLines int64  `json:"tailLines" jsonschema:"Number of lines to return from the end of the log, capped at 500. Defaults to 200."`
}

type GetPodLogsOutput struct {
    Logs string `json:"logs"`
}

const maxLogTailLines = 500

func NewGetPodLogsTool(kube kubernetes.KubeClient) (*mcp.Tool, func(context.Context, *mcp.CallToolRequest, GetPodLogsInput) (*mcp.CallToolResult, GetPodLogsOutput, error)) {
    tool := &amp;mcp.Tool{
        Name:        "get_pod_logs",
        Description: "Fetch recent logs for a pod's container. Set previous=true to diagnose CrashLoopBackOff.",
    }

    handler := func(ctx context.Context, _ *mcp.CallToolRequest, in GetPodLogsInput) (*mcp.CallToolResult, GetPodLogsOutput, error) {
        tail := in.TailLines
        if tail &lt;= 0 || tail &gt; maxLogTailLines {
            tail = maxLogTailLines
        }

        logs, err := kube.GetPodLogs(ctx, in.Namespace, in.Name, kubernetes.LogOptions{
            Container: in.Container,
            Previous:  in.Previous,
            TailLines: tail,
        })
        if err != nil {
            return nil, GetPodLogsOutput{}, fmt.Errorf("get_pod_logs: %w", err)
        }
        return nil, GetPodLogsOutput{Logs: logs}, nil
    }

    return tool, handler
}
</code></pre>
<p>Notice the cap is enforced <em>again</em> here, on top of the default already living in <code>LogOptions</code>. That's not redundant, the schema description tells the agent "capped at 500," but nothing stops a misbehaving or adversarial caller from sending <code>tailLines: 50000</code> anyway. The tool handler is the last line of defense before the request reaches the cluster, so it re-validates rather than trusting that the caller respected the description.</p>
<h3><code>describe_pod</code></h3>
<p>This one composes three <code>KubeClient</code> calls into a single tool; deliberately, it mirrors what <code>kubectl describe pod</code> does under the hood, giving the agent one call instead of three for a question it will ask constantly.</p>
<pre><code class="language-go">// internal/tools/describe_pod.go
package tools

import (
    "context"
    "fmt"

    "github.com/modelcontextprotocol/go-sdk/mcp"
    corev1 "k8s.io/api/core/v1"

    "github.com/FerRiosCosta/go-k8s-mcp-server/internal/kubernetes"
)

type DescribePodInput struct {
    Namespace string `json:"namespace" jsonschema:"Kubernetes namespace of the pod."`
    Name      string `json:"name" jsonschema:"Name of the pod."`
}

type ContainerState struct {
    Name     string `json:"name"`
    State    string `json:"state"`    // Waiting, Running, Terminated
    Reason   string `json:"reason"`   // CrashLoopBackOff, OOMKilled, etc.
    Restarts int32  `json:"restarts"`
}

type DescribePodOutput struct {
    Phase      string           `json:"phase"`
    Containers []ContainerState `json:"containers"`
    Events     []string         `json:"recentEvents"`
}

func NewDescribePodTool(kube kubernetes.KubeClient) (*mcp.Tool, func(context.Context, *mcp.CallToolRequest, DescribePodInput) (*mcp.CallToolResult, DescribePodOutput, error)) {
    tool := &amp;mcp.Tool{
        Name:        "describe_pod",
        Description: "Get a pod's phase, per-container state and restart reasons, and its most recent events — the fastest way to understand why a pod is unhealthy.",
    }

    handler := func(ctx context.Context, _ *mcp.CallToolRequest, in DescribePodInput) (*mcp.CallToolResult, DescribePodOutput, error) {
        pod, err := kube.GetPod(ctx, in.Namespace, in.Name)
        if err != nil {
            return nil, DescribePodOutput{}, fmt.Errorf("describe_pod: %w", err)
        }

        events, err := kube.GetEvents(ctx, in.Namespace, in.Name)
        if err != nil {
            return nil, DescribePodOutput{}, fmt.Errorf("describe_pod: %w", err)
        }

        out := DescribePodOutput{Phase: string(pod.Status.Phase)}
        for _, cs := range pod.Status.ContainerStatuses {
            state, reason := containerState(cs)
            out.Containers = append(out.Containers, ContainerState{
                Name: cs.Name, State: state, Reason: reason, Restarts: cs.RestartCount,
            })
        }
        for _, e := range events {
            out.Events = append(out.Events, fmt.Sprintf("[%s] %s", e.Reason, e.Message))
        }

        return nil, out, nil
    }

    return tool, handler
}

func containerState(cs corev1.ContainerStatus) (state, reason string) {
    switch {
    case cs.State.Waiting != nil:
        return "Waiting", cs.State.Waiting.Reason
    case cs.State.Terminated != nil:
        return "Terminated", cs.State.Terminated.Reason
    default:
        return "Running", ""
    }
}
</code></pre>
<p>If you've read the client-go post, <code>containerState</code> will look familiar, it's the same waiting/terminated distinction <code>inspectPod</code> made in the cluster health reporter, because it's the same underlying problem: a pod's <code>Phase</code> alone doesn't tell you the truth; you have to read <code>ContainerStatuses</code>.</p>
<h3><code>get_events</code></h3>
<p>Standalone from <code>describe_pod</code> because an agent sometimes wants events for a whole namespace, not one pod, a burst of <code>FailedScheduling</code> events across several pods is a cluster-capacity story, not a single-pod story, and <code>describe_pod</code> can't surface that.</p>
<pre><code class="language-go">// internal/tools/get_events.go
package tools

import (
    "context"
    "fmt"

    "github.com/modelcontextprotocol/go-sdk/mcp"

    "github.com/FerRiosCosta/go-k8s-mcp-server/internal/kubernetes"
)

type GetEventsInput struct {
    Namespace          string `json:"namespace" jsonschema:"Kubernetes namespace to fetch events from."`
    InvolvedObjectName string `json:"involvedObjectName" jsonschema:"Optional. Filter events to those involving this object name, e.g. a Pod or Deployment. Leave empty for all events in the namespace."`
}

type EventSummary struct {
    Type    string `json:"type"`   // Normal or Warning
    Reason  string `json:"reason"` // FailedScheduling, BackOff, Pulled, etc.
    Object  string `json:"object"`
    Message string `json:"message"`
    Count   int32  `json:"count"`
}

type GetEventsOutput struct {
    Events []EventSummary `json:"events"`
}

const maxEventsReturned = 50

func NewGetEventsTool(kube kubernetes.KubeClient) (*mcp.Tool, func(context.Context, *mcp.CallToolRequest, GetEventsInput) (*mcp.CallToolResult, GetEventsOutput, error)) {
    tool := &amp;mcp.Tool{
        Name:        "get_events",
        Description: "List recent Kubernetes events in a namespace, optionally filtered to a specific object. A burst of Warning events across multiple objects usually points to a cluster-level problem, not a single-resource one.",
    }

    handler := func(ctx context.Context, _ *mcp.CallToolRequest, in GetEventsInput) (*mcp.CallToolResult, GetEventsOutput, error) {
        events, err := kube.GetEvents(ctx, in.Namespace, in.InvolvedObjectName)
        if err != nil {
            return nil, GetEventsOutput{}, fmt.Errorf("get_events: %w", err)
        }

        // Cap the response the same way get_pod_logs caps its tail,
        // a noisy namespace can return thousands of events, and the
        // agent needs the most relevant slice, not all of it.
        if len(events) &gt; maxEventsReturned {
            events = events[len(events)-maxEventsReturned:]
        }

        out := GetEventsOutput{Events: make([]EventSummary, 0, len(events))}
        for _, e := range events {
            out.Events = append(out.Events, EventSummary{
                Type:    e.Type,
                Reason:  e.Reason,
                Object:  e.InvolvedObject.Name,
                Message: e.Message,
                Count:   e.Count,
            })
        }
        return nil, out, nil
    }

    return tool, handler
}
</code></pre>
<h3><code>check_endpoints</code></h3>
<p>This is the tool that answers "the Service exists, so why can't anything reach it", a question <code>list_pods</code> and <code>describe_pod</code> genuinely can't answer, since a healthy-looking pod can still be missing from a Service's endpoints entirely.</p>
<pre><code class="language-go">// internal/tools/check_endpoints.go
package tools

import (
    "context"
    "fmt"

    "github.com/modelcontextprotocol/go-sdk/mcp"

    "github.com/FerRiosCosta/go-k8s-mcp-server/internal/kubernetes"
)

type CheckEndpointsInput struct {
    Namespace   string `json:"namespace" jsonschema:"Kubernetes namespace of the service."`
    ServiceName string `json:"serviceName" jsonschema:"Name of the service to check."`
}

type CheckEndpointsOutput struct {
    ServiceSelector map[string]string `json:"serviceSelector"`
    ReadyAddresses  int               `json:"readyAddresses"`
    NotReady        int               `json:"notReadyAddresses"`
    Healthy         bool              `json:"healthy"`
}

func NewCheckEndpointsTool(kube kubernetes.KubeClient) (*mcp.Tool, func(context.Context, *mcp.CallToolRequest, CheckEndpointsInput) (*mcp.CallToolResult, CheckEndpointsOutput, error)) {
    tool := &amp;mcp.Tool{
        Name:        "check_endpoints",
        Description: "Check whether a Service has healthy endpoints backing it. Zero ready addresses despite matching pods usually means a label selector mismatch or a failing readiness probe.",
    }

    handler := func(ctx context.Context, _ *mcp.CallToolRequest, in CheckEndpointsInput) (*mcp.CallToolResult, CheckEndpointsOutput, error) {
        svc, err := kube.GetService(ctx, in.Namespace, in.ServiceName)
        if err != nil {
            return nil, CheckEndpointsOutput{}, fmt.Errorf("check_endpoints: %w", err)
        }

        eps, err := kube.GetEndpoints(ctx, in.Namespace, in.ServiceName)
        if err != nil {
            return nil, CheckEndpointsOutput{}, fmt.Errorf("check_endpoints: %w", err)
        }

        ready, notReady := 0, 0
        for _, subset := range eps.Subsets {
            ready += len(subset.Addresses)
            notReady += len(subset.NotReadyAddresses)
        }

        return nil, CheckEndpointsOutput{
            ServiceSelector: svc.Spec.Selector,
            ReadyAddresses:  ready,
            NotReady:        notReady,
            Healthy:         ready &gt; 0,
        }, nil
    }

    return tool, handler
}
</code></pre>
<p>Returning <code>ServiceSelector</code> alongside the counts is deliberate: when <code>ReadyAddresses</code> is zero, the very next thing an agent needs is the selector to cross-reference against pod labels via <code>list_pods</code>, handing it back here saves a tool call the agent would otherwise have to make anyway.</p>
<h3><code>describe_ingress</code></h3>
<p>Composes <code>GetIngress</code>, <code>ListIngressClasses</code>, and <code>GetEvents</code>, the same three-source pattern <code>describe_pod</code> used, applied to "is the ALB even provisioned" instead of "is the pod healthy."</p>
<pre><code class="language-go">// internal/tools/describe_ingress.go
package tools

import (
    "context"
    "fmt"

    "github.com/modelcontextprotocol/go-sdk/mcp"

    "github.com/FerRiosCosta/go-k8s-mcp-server/internal/kubernetes"
)

type DescribeIngressInput struct {
    Namespace string `json:"namespace" jsonschema:"Kubernetes namespace of the Ingress."`
    Name      string `json:"name" jsonschema:"Name of the Ingress."`
}

type DescribeIngressOutput struct {
    IngressClassName  string   `json:"ingressClassName"`
    IngressClassFound bool     `json:"ingressClassFound"`
    LoadBalancerHost  string   `json:"loadBalancerHost"` // empty if not yet provisioned
    RecentEvents      []string `json:"recentEvents"`
}

func NewDescribeIngressTool(kube kubernetes.KubeClient) (*mcp.Tool, func(context.Context, *mcp.CallToolRequest, DescribeIngressInput) (*mcp.CallToolResult, DescribeIngressOutput, error)) {
    tool := &amp;mcp.Tool{
        Name:        "describe_ingress",
        Description: "Diagnose an Ingress on EKS: whether its ingressClassName resolves to a real IngressClass, whether the ALB has finished provisioning, and recent reconciliation events from the AWS Load Balancer Controller.",
    }

    handler := func(ctx context.Context, _ *mcp.CallToolRequest, in DescribeIngressInput) (*mcp.CallToolResult, DescribeIngressOutput, error) {
        ing, err := kube.GetIngress(ctx, in.Namespace, in.Name)
        if err != nil {
            return nil, DescribeIngressOutput{}, fmt.Errorf("describe_ingress: %w", err)
        }

        out := DescribeIngressOutput{}
        if ing.Spec.IngressClassName != nil {
            out.IngressClassName = *ing.Spec.IngressClassName
        }
        if len(ing.Status.LoadBalancer.Ingress) &gt; 0 {
            out.LoadBalancerHost = ing.Status.LoadBalancer.Ingress[0].Hostname
        }

        classes, err := kube.ListIngressClasses(ctx)
        if err != nil {
            return nil, DescribeIngressOutput{}, fmt.Errorf("describe_ingress: %w", err)
        }
        for _, ic := range classes.Items {
            if ic.Name == out.IngressClassName {
                out.IngressClassFound = true
                break
            }
        }

        events, err := kube.GetEvents(ctx, in.Namespace, in.Name)
        if err != nil {
            return nil, DescribeIngressOutput{}, fmt.Errorf("describe_ingress: %w", err)
        }
        for _, e := range events {
            out.RecentEvents = append(out.RecentEvents, fmt.Sprintf("[%s] %s", e.Reason, e.Message))
        }

        return nil, out, nil
    }

    return tool, handler
}
</code></pre>
<p><code>IngressClassFound</code> deliberately gets computed here rather than left for the agent to figure out from a raw class list, an empty or mismatched <code>ingressClassName</code> with no error anywhere else in the object is exactly the kind of silent failure an agent won't reliably catch by eyeballing JSON, so the tool does the comparison itself and hands back a plain boolean.</p>
<h3><code>describe_httproute</code></h3>
<p>Gateway API's structured <code>status.conditions</code> make this tool simpler than <code>describe_ingress</code> in one respect, no cross-referencing an IngressClass list. but it has to check two objects instead of one, since a route's health depends on the Gateway underneath it.</p>
<pre><code class="language-go">// internal/tools/describe_httproute.go
package tools

import (
    "context"
    "fmt"

    "github.com/modelcontextprotocol/go-sdk/mcp"
    metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"

    "github.com/FerRiosCosta/go-k8s-mcp-server/internal/kubernetes"
)

type DescribeHTTPRouteInput struct {
    Namespace string `json:"namespace" jsonschema:"Kubernetes namespace of the HTTPRoute."`
    Name      string `json:"name" jsonschema:"Name of the HTTPRoute."`
    // GatewayName lets the tool also check the parent Gateway's status,
    // since a route can never work if its Gateway isn't Programmed,
    // optional because a route can have multiple parents.
    GatewayName string `json:"gatewayName" jsonschema:"Optional. Name of the parent Gateway to check alongside the route. Leave empty to skip the Gateway-level check."`
}

type ConditionSummary struct {
    Type    string `json:"type"`   // Accepted, ResolvedRefs, Programmed, etc.
    Status  string `json:"status"` // True, False, Unknown
    Reason  string `json:"reason"`
    Message string `json:"message"`
}

type DescribeHTTPRouteOutput struct {
    RouteConditions   []ConditionSummary `json:"routeConditions"`
    GatewayConditions []ConditionSummary `json:"gatewayConditions,omitempty"`
}

func NewDescribeHTTPRouteTool(kube kubernetes.KubeClient) (*mcp.Tool, func(context.Context, *mcp.CallToolRequest, DescribeHTTPRouteInput) (*mcp.CallToolResult, DescribeHTTPRouteOutput, error)) {
    tool := &amp;mcp.Tool{
        Name:        "describe_httproute",
        Description: "Diagnose an HTTPRoute's Accepted/ResolvedRefs conditions, and optionally its parent Gateway's Accepted/Programmed conditions. Check the Gateway conditions first — a route cannot work if its Gateway isn't Programmed.",
    }

    handler := func(ctx context.Context, _ *mcp.CallToolRequest, in DescribeHTTPRouteInput) (*mcp.CallToolResult, DescribeHTTPRouteOutput, error) {
        route, err := kube.GetHTTPRoute(ctx, in.Namespace, in.Name)
        if err != nil {
            return nil, DescribeHTTPRouteOutput{}, fmt.Errorf("describe_httproute: %w", err)
        }

        out := DescribeHTTPRouteOutput{}
        for _, parent := range route.Status.Parents {
            out.RouteConditions = append(out.RouteConditions, summarizeConditions(parent.Conditions)...)
        }

        if in.GatewayName != "" {
            gw, err := kube.GetGateway(ctx, in.Namespace, in.GatewayName)
            if err != nil {
                return nil, DescribeHTTPRouteOutput{}, fmt.Errorf("describe_httproute: %w", err)
            }
            out.GatewayConditions = summarizeConditions(gw.Status.Conditions)
        }

        return nil, out, nil
    }

    return tool, handler
}

func summarizeConditions(conditions []metav1.Condition) []ConditionSummary {
    summaries := make([]ConditionSummary, 0, len(conditions))
    for _, c := range conditions {
        summaries = append(summaries, ConditionSummary{
            Type:    c.Type,
            Status:  string(c.Status),
            Reason:  c.Reason,
            Message: c.Message,
        })
    }
    return summaries
}
</code></pre>
<p><code>summarizeConditions</code> exists as its own small function because both <code>route.Status.Parents[].Conditions</code> and <code>gw.Status.Conditions</code> are the same <code>[]metav1.Condition</code> shape; Gateway API standardizes on <code>metav1.Condition</code> throughout, which is exactly what lets one helper cover both without a type switch.</p>
<h3><code>list_configmap_keys</code></h3>
<p>The read-only, keys-only boundary from <code>ConfigClient</code> carries straight through to the tool layer, there's no <code>value</code> field anywhere in this output, by design.</p>
<pre><code class="language-go">// internal/tools/list_configmap_keys.go
package tools

import (
    "context"
    "fmt"

    "github.com/modelcontextprotocol/go-sdk/mcp"

    "github.com/FerRiosCosta/go-k8s-mcp-server/internal/kubernetes"
)

type ListConfigMapKeysInput struct {
    Namespace string `json:"namespace" jsonschema:"Kubernetes namespace of the ConfigMap."`
    Name      string `json:"name" jsonschema:"Name of the ConfigMap."`
}

type ListConfigMapKeysOutput struct {
    Keys []string `json:"keys"`
}

func NewListConfigMapKeysTool(kube kubernetes.KubeClient) (*mcp.Tool, func(context.Context, *mcp.CallToolRequest, ListConfigMapKeysInput) (*mcp.CallToolResult, ListConfigMapKeysOutput, error)) {
    tool := &amp;mcp.Tool{
        Name:        "list_configmap_keys",
        Description: "List the key names present in a ConfigMap. Returns keys only, never values — use this to check whether an expected config key exists.",
    }

    handler := func(ctx context.Context, _ *mcp.CallToolRequest, in ListConfigMapKeysInput) (*mcp.CallToolResult, ListConfigMapKeysOutput, error) {
        keys, err := kube.GetConfigMapKeys(ctx, in.Namespace, in.Name)
        if err != nil {
            return nil, ListConfigMapKeysOutput{}, fmt.Errorf("list_configmap_keys: %w", err)
        }
        return nil, ListConfigMapKeysOutput{Keys: keys}, nil
    }

    return tool, handler
}
</code></pre>
<p>There's no <code>list_secret_keys</code> tool shown separately here, it's the identical shape calling <code>kube.GetSecretKeys</code> instead, so I'm not pasting a near-duplicate file. If you're building this yourself, add it exactly like this one.</p>
<h3><code>pod_metrics</code></h3>
<p>The one tool that depends on metrics-server actually being installed in the cluster, worth surfacing that as a real error, not a generic 404, since it's a common reason for this specific tool to fail in a fresh cluster.</p>
<pre><code class="language-go">// internal/tools/pod_metrics.go
package tools

import (
    "context"
    "fmt"

    "github.com/modelcontextprotocol/go-sdk/mcp"

    "github.com/FerRiosCosta/go-k8s-mcp-server/internal/kubernetes"
)

type GetPodMetricsInput struct {
    Namespace string `json:"namespace" jsonschema:"Kubernetes namespace of the pod."`
    Name      string `json:"name" jsonschema:"Name of the pod."`
}

type ContainerUsage struct {
    Name   string `json:"name"`
    CPU    string `json:"cpu"`    // e.g. "12m"
    Memory string `json:"memory"` // e.g. "84Mi"
}

type GetPodMetricsOutput struct {
    Containers []ContainerUsage `json:"containers"`
}

func NewGetPodMetricsTool(kube kubernetes.KubeClient) (*mcp.Tool, func(context.Context, *mcp.CallToolRequest, GetPodMetricsInput) (*mcp.CallToolResult, GetPodMetricsOutput, error)) {
    tool := &amp;mcp.Tool{
        Name:        "pod_metrics",
        Description: "Get current CPU and memory usage per container in a pod, from metrics-server. Requires metrics-server to be installed in the cluster.",
    }

    handler := func(ctx context.Context, _ *mcp.CallToolRequest, in GetPodMetricsInput) (*mcp.CallToolResult, GetPodMetricsOutput, error) {
        metrics, err := kube.GetPodMetrics(ctx, in.Namespace, in.Name)
        if err != nil {
            // metrics-server missing or not yet scraped this pod shows up
            // as a normal API error here, wrap it with the likely cause
            // rather than letting the agent see a bare "not found."
            return nil, GetPodMetricsOutput{}, fmt.Errorf("pod_metrics: %w (is metrics-server installed?)", err)
        }

        out := GetPodMetricsOutput{Containers: make([]ContainerUsage, 0, len(metrics.Containers))}
        for _, c := range metrics.Containers {
            out.Containers = append(out.Containers, ContainerUsage{
                Name:   c.Name,
                CPU:    c.Usage.Cpu().String(),
                Memory: c.Usage.Memory().String(),
            })
        }
        return nil, out, nil
    }

    return tool, handler
}
</code></pre>
<p>That's twelve <code>KubeClient</code> methods reachable through nine tools (<code>describe_pod</code>, <code>describe_ingress</code>, and <code>describe_httproute</code> each composing more than one). Every tool file follows the identical shape: typed input, typed output, a handler that calls one or more <code>KubeClient</code> methods and translates the result, which is exactly the point of designing the client interface first, the way this post did.</p>
<hr />
<h2>Wiring it together</h2>
<pre><code class="language-go">// internal/mcpserver/server.go
package mcpserver

import (
    "github.com/modelcontextprotocol/go-sdk/mcp"

    "github.com/FerRiosCosta/go-k8s-mcp-server/internal/kubernetes"
    "github.com/FerRiosCosta/go-k8s-mcp-server/internal/tools"
)

// New builds an MCP server with every diagnostic tool registered against
// the given KubeClient. Adding a tool means adding one pair of lines
// here, the server itself has no Kubernetes-specific logic, it only
// wires things up.
func New(kube kubernetes.KubeClient) *mcp.Server {
    server := mcp.NewServer(&amp;mcp.Implementation{
        Name:    "k8s-diagnostics",
        Version: "0.1.0",
    }, nil)

    // Each New*Tool constructor returns two values, (*mcp.Tool, handler).
    // Go's multi-value spread only applies when that call is the sole
    // argument to the outer call, mcp.AddTool also takes server, so the
    // pair has to be captured into named variables first, tool by tool,
    // rather than nested directly inside AddTool.
    listPodsTool, listPodsHandler := tools.NewListPodsTool(kube)
    mcp.AddTool(server, listPodsTool, listPodsHandler)

    getPodLogsTool, getPodLogsHandler := tools.NewGetPodLogsTool(kube)
    mcp.AddTool(server, getPodLogsTool, getPodLogsHandler)

    describePodTool, describePodHandler := tools.NewDescribePodTool(kube)
    mcp.AddTool(server, describePodTool, describePodHandler)

    getEventsTool, getEventsHandler := tools.NewGetEventsTool(kube)
    mcp.AddTool(server, getEventsTool, getEventsHandler)

    checkEndpointsTool, checkEndpointsHandler := tools.NewCheckEndpointsTool(kube)
    mcp.AddTool(server, checkEndpointsTool, checkEndpointsHandler)

    describeIngressTool, describeIngressHandler := tools.NewDescribeIngressTool(kube)
    mcp.AddTool(server, describeIngressTool, describeIngressHandler)

    describeHTTPRouteTool, describeHTTPRouteHandler := tools.NewDescribeHTTPRouteTool(kube)
    mcp.AddTool(server, describeHTTPRouteTool, describeHTTPRouteHandler)

    listConfigMapKeysTool, listConfigMapKeysHandler := tools.NewListConfigMapKeysTool(kube)
    mcp.AddTool(server, listConfigMapKeysTool, listConfigMapKeysHandler)

    getPodMetricsTool, getPodMetricsHandler := tools.NewGetPodMetricsTool(kube)
    mcp.AddTool(server, getPodMetricsTool, getPodMetricsHandler)

    return server
}
</code></pre>
<pre><code class="language-go">// cmd/k8s-mcp-server/main.go
package main

import (
    "context"
    "fmt"
    "os"

    "github.com/modelcontextprotocol/go-sdk/mcp"

    k8s "github.com/FerRiosCosta/go-k8s-mcp-server/internal/kubernetes"
    "github.com/FerRiosCosta/go-k8s-mcp-server/internal/mcpserver"
)

func main() {
    kube, err := k8s.NewClient()
    if err != nil {
        fmt.Fprintf(os.Stderr, "failed to connect to cluster: %v\n", err)
        os.Exit(1)
    }

    server := mcpserver.New(kube)

    // Stdio is the right transport for a local agent (Claude Desktop, an
    // editor extension, or an agent CLI) running on the same machine as
    // the server. A remote, multi-tenant deployment needs a different
    // transport and a different set of tradeoffs entirely, that's its
    // own post.
    if err := server.Run(context.Background(), &amp;mcp.StdioTransport{}); err != nil {
        fmt.Fprintf(os.Stderr, "server error: %v\n", err)
        os.Exit(1)
    }
}
</code></pre>
<p><code>k8s.NewClient</code> no longer takes a path, it resolves config the same way <code>kubectl</code> does: in-cluster if running inside a pod, otherwise <code>$KUBECONFIG</code> if set, otherwise <code>~/.kube/config</code>, using whatever context is currently active. That means switching clusters with <code>kubectl config use-context</code> changes what this server talks to as well, without touching any config file for the MCP client itself.</p>
<hr />
<h2>Running it end-to-end</h2>
<p>Build the binary first:</p>
<pre><code class="language-shell">go build -o k8s-mcp-server ./cmd/k8s-mcp-server
</code></pre>
<p>Then point an MCP-compatible client at it. Since <code>NewClient</code> resolves config the same way <code>kubectl</code> does, no <code>KUBECONFIG</code> needs to be passed through the client config at all, whatever context is currently active is the one the server talks to.</p>
<p><strong>Claude Desktop</strong>, edit <code>claude_desktop_config.json</code> (<code>~/Library/Application Support/Claude/</code> on macOS, <code>%APPDATA%\Claude\</code> on Windows):</p>
<pre><code class="language-json">{
  "mcpServers": {
    "k8s-diagnostics": {
      "command": "/absolute/path/to/k8s-mcp-server"
    }
  }
}
</code></pre>
<p>Restart Claude Desktop, it only reads this file on startup, not live.</p>
<p><strong>VS Code (GitHub Copilot)</strong>, add to <code>.vscode/mcp.json</code> in the project, or via Command Palette → <code>MCP: Open User Configuration</code>. Note the root key is <code>servers</code>, not <code>mcpServers</code>:</p>
<pre><code class="language-json">{
  "servers": {
    "k8s-diagnostics": {
      "type": "stdio",
      "command": "/absolute/path/to/k8s-mcp-server"
    }
  }
}
</code></pre>
<p>MCP tools only show up once Copilot Chat's mode dropdown is switched to <strong>Agent</strong>, the default chat mode won't call tools at all.</p>
<blockquote>
<p><strong>If Copilot still reports the tools as unavailable</strong> even after <code>MCP: List Servers</code> shows <code>k8s-diagnostics</code> as <code>Running</code> and every tool is checked in the tools picker, start a brand new chat rather than continuing the existing one. Copilot fetches a session's tool list once, at the start of that conversation, enabling a server or checking its tools after the chat is already open doesn't retroactively update it. A fresh chat re-fetches the list and picks them up immediately. This is a quick thing to rule out before assuming the server itself is broken.</p>
</blockquote>
<p>With minikube running and the <code>go-api</code> deployment from the earlier posts still there, recreate the <code>memory-hog</code> pod from the client-go post's OOMKill simulation:</p>
<pre><code class="language-shell">kubectl apply -f memory-hog.yaml
# wait for CrashLoopBackOff
</code></pre>
<p>Then, in the agent, ask the question you'd normally type into a terminal:</p>
<blockquote>
<p>"Why is memory-hog failing in the default namespace?"</p>
</blockquote>
<p>Behind the scenes, the agent calls <code>list_pods</code>, sees <code>memory-hog</code> with a non-zero restart count, calls <code>describe_pod</code>, sees the container's waiting reason is <code>CrashLoopBackOff</code>, and calls <code>get_pod_logs</code> with <code>previous: true</code> since it knows the current instance may not have logged anything yet. It comes back with something like: <em>"memory-hog is crash-looping with 13 restarts. The container is being OOMKilled, it's allocating 100MB but its memory limit is 10Mi."</em> That's the same conclusion the reporter in the client-go post prints as a table row, arrived at through conversation instead of a report you have to read and interpret yourself.</p>
<pre><code class="language-shell">kubectl delete pod memory-hog
</code></pre>
<hr />
<h2>Engineering practices that matter here</h2>
<p><strong>Read-only by default.</strong> Covered above at the interface level, worth restating: nothing in this server can mutate the cluster. If you extend it later with write operations, put them behind an explicit flag and treat them as a different trust boundary, not an addition to this interface.</p>
<p><strong>Bound every unbounded query.</strong> Logs are the obvious one, but the same instinct applies to <code>ListPods</code> with no namespace on a thousand-pod cluster, or <code>GetEvents</code> on a noisy namespace. An agent doesn't know your cluster's scale before it asks; the server has to protect itself.</p>
<p><strong>Never construct a new Clientset per tool call.</strong> Same gotcha as the client-go post, just resurfacing in a new context: build the Clientset once in <code>main.go</code>, inject it into every tool through <code>KubeClient</code>, and let client-go's connection pooling and rate limiting actually do their job across the lifetime of the process.</p>
<p><strong>Log every tool invocation, structured.</strong> Not for debugging your Go code, for auditability: which tool was called, with what arguments, and what it returned, is the trail you'll want if an agent's actions ever need to be reconstructed after the fact. A single <code>slog</code> call wrapping each handler is enough to start.</p>
<p><strong>RBAC scope the service account, not just the interface.</strong> The <code>KubeClient</code> interface being read-only is a code-level guarantee. Pair it with a Kubernetes-level one: run the server with a ServiceAccount bound to a <code>ClusterRole</code> that only grants <code>get</code>, <code>list</code>, and <code>watch</code> verbs. Two independent layers that both have to agree before anything unexpected can happen.</p>
<hr />
<h2>Common gotchas</h2>
<p><strong>Vague tool descriptions produce wrong tool calls.</strong> "Get pod info" and "Get a pod's phase, per-container state and restart reasons, and its most recent events" are the difference between an agent guessing and an agent knowing exactly when to reach for this tool over <code>list_pods</code>. Write descriptions for the agent the way you'd write a docstring for a teammate who's never seen your codebase.</p>
<p><strong>Agents default to broad queries.</strong> Ask "what's wrong with my cluster" and an agent will happily call <code>list_pods</code> with an empty namespace before narrowing down. That's fine, as long as the tool is built to handle it cheaply, it's a reason the tool layer, not just the agent's judgment, needs to enforce limits.</p>
<p><strong>Silent schema mismatches are worse than loud errors.</strong> If a struct field's <code>jsonschema</code> tag doesn't match what you documented in the tool's <code>Description</code>, the agent gets a schema that contradicts your prose and picks unpredictably. Keep the two in sync, and when in doubt, let the inferred schema be the source of truth.</p>
<p><strong>Namespace scoping mistakes are common on the agent side.</strong> An agent asked to check "the checkout service" may not know which namespace it lives in and will guess <code>default</code>. Consider a tool that resolves a name to its namespace first (a <code>find_resource</code> style tool), rather than assuming every downstream tool call carries the right namespace.</p>
<p><code>mcp.AddTool(server, tools.NewXTool(kube))</code> <strong>doesn't compile.</strong> Every <code>New*Tool</code> constructor returns two values, <code>(*mcp.Tool, handler)</code>. Go only spreads a multi-value call into another call's parameters when that call is the <em>sole</em> argument — <code>mcp.AddTool</code> also takes <code>server</code> as a first argument, so the pair has to be captured into named variables first: <code>tool, handler := tools.NewListPodsTool(kube)</code>, then <code>mcp.AddTool(server, tool, handler)</code>. Easy to miss since the single-argument version of this pattern (a bare <code>f(g())</code>) does compile, which makes the two-argument failure feel inconsistent the first time you hit it.</p>
<p><code>describe_httproute</code> <strong>erroring on every call means Gateway API isn't installed.</strong> <code>gatewayClientset.NewForConfig</code> succeeds even against a cluster with zero Gateway API CRDs — it's just building a REST client for a set of API paths, not checking they exist. The failure only shows up once <code>GetHTTPRoute</code> or <code>GetGateway</code> actually runs, as a <code>NotFound</code>-shaped error on the CRD's group/version rather than a clear "Gateway API isn't installed" message. Worth wrapping that specific error with a clearer message in the tool handler, the same way <code>pod_metrics</code> wraps a missing metrics-server.</p>
<hr />
<h2>Summary</h2>
<p>The protocol part of MCP is almost incidental, tools, JSON Schema, call and response. What actually made this server useful was already built in part 1: a <code>KubeClient</code> interface scoped to real diagnostic needs, read-only by construction. This post's job was just to wrap it correctly.</p>
<p>Three things worth taking away:</p>
<ul>
<li><p>Every tool follows the same four-part shape, <code>*mcp.Tool</code> for identity, a typed <code>In</code>, a handler, a typed <code>Out</code>, which is what makes nine tools feel like one pattern instead of nine separate designs.</p>
</li>
<li><p>Return structured <code>Out</code> types, not preformatted strings. The agent reasons over JSON fields, not text it has to parse back apart.</p>
</li>
<li><p>Every boundary that matters, bounded log tails, capped event counts, secret values never leaving the cluster, gets enforced again at the tool layer, not just assumed from the client underneath it. An agent (or a misbehaving caller) can send arguments that ignore a schema's stated limits; the handler is the last line of defense.</p>
</li>
</ul>
<p>What's next for this server is running it as shared infrastructure instead of a local stdio process someone points their laptop at, a different transport, session handling under concurrent agents, and the AWS-specific pieces of running it on EKS. That's a real jump in complexity, and it deserves its own post rather than a rushed section at the end of this one.</p>
<hr />
<h2>Let's connect!</h2>
<p>If something in this post resonated, if you spotted a bug, or if you just want to talk Go, Kubernetes, AI agents, or Platform Engineering, I'm always happy to hear from you.</p>
<ul>
<li><p><strong>LinkedIn</strong></p>
</li>
<li><p><strong>GitHub</strong></p>
</li>
<li><p><strong>Twitter / X</strong></p>
</li>
</ul>
<p><em>Building from Asunción, Paraguay 🇵🇾</em></p>
<p><code>#go</code> <code>#kubernetes</code> <code>#mcp</code> <code>#ai-agents</code> <code>#platform-engineering</code></p>
]]></content:encoded></item><item><title><![CDATA[Build an MCP Server in Go (Part 1): Designing a diagnostic-grade Kubernetes client]]></title><description><![CDATA[Design a Kubernetes client in Go for an MCP server]]></description><link>https://ferztyle.me/build-an-mcp-server-in-go-part-1-designing-a-diagnostic-grade-kubernetes-client</link><guid isPermaLink="true">https://ferztyle.me/build-an-mcp-server-in-go-part-1-designing-a-diagnostic-grade-kubernetes-client</guid><category><![CDATA[Devops]]></category><category><![CDATA[Go Language]]></category><category><![CDATA[Kubernetes]]></category><category><![CDATA[mcp]]></category><dc:creator><![CDATA[Fer]]></dc:creator><pubDate>Fri, 14 Aug 2026 13:47:00 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/61db385c3ce4b2377adfdcda/e7011016-292b-44b8-b261-6b1f3ae05195.svg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p><em>This post designs the Kubernetes client.</em> <em>The next post</em> <em>wraps it as an MCP server and wires it to an agent.</em></p>
<h2>Asking instead of running</h2>
<p>There's a familiar rhythm to debugging a bad deploy: <code>kubectl get pods</code>, spot the <code>CrashLoopBackOff</code>, <code>kubectl logs --previous</code>, still not obvious, <code>kubectl describe pod</code>, scroll to Events, cross-reference with <code>kubectl get events</code>, maybe check if the Service even has endpoints. Five or six commands, in your head, in a specific order, because you've done this enough times to know the order.</p>
<p>That order is exactly what an AI agent can execute for you, if you give it the right tools, ask "why is <code>checkout-service</code> failing?" and have it chain through the same commands you would have, arriving at an actual answer instead of a wall of YAML. The protocol that makes an agent capable of calling tools like that is the Model Context Protocol (MCP), and building that server is part 2 of this series.</p>
<p>This post is about what comes first and matters more: the Kubernetes client those tools will eventually sit on top of. An agent is only as good as what it's allowed to ask for. Hand it a client with one <code>ListPods</code> method and it can list pods, nothing else. Hand it a client that mirrors what a senior engineer actually checks when something's broken, pod state, events, endpoints, node capacity, rollout history, and it can genuinely diagnose. That client is a real piece of engineering on its own, independent of whether an LLM ever touches it, which is why it gets its own post before MCP enters the picture at all.</p>
<h3><code>ferctl</code> vs. an MCP server: two answers to the same problem</h3>
<p><code>ferctl</code> was my first attempt at this: a Cobra CLI, backed by client-go, that wraps common troubleshooting checks into subcommands: <code>ferctl top</code>, <code>ferctl logs</code>, that shape. It's fast, deterministic, and scriptable. Run <code>ferctl describe-pod checkout-service</code>, get the same structured output every time, pipe it into<code>jq</code>, drop it into a CI step, no ambiguity about what ran or why. That predictability is exactly what a CLI is good at.</p>
<p>What it doesn't do is investigate. <code>ferctl</code> runs the one command you gave it, you're still the one who has to know that a <code>CrashLoopBackOff</code> means "check previous logs, then check events", and you're still typing each step by hand. It's a faster way to run the commands you already know, not a way to skip learning them.</p>
<p>An MCP server flips that. You ask "why is <code>checkout-service</code> failing" once, and the agent decides the sequence, list pods, notices the restart count, pulls previous logs, cross-references events, the way a <code>ferctl</code> invocation never will, because no single subcommand can adapt its next step to what the last one returned. That's the shift this series is really about: from "a faster way to run known commands" to "something that can figure out which commands to run." It's also, frankly, the more current way to build this kind of tooling, a fixed CLI surface is a fine interface for a human who already knows the shape of the problem, but an LLM-driven agent chaining calls dynamically is a better fit for the actual shape of debugging, which rarely follows a script.</p>
<p>None of that makes <code>ferctl</code> obsolete. A CLI is still the right tool when you want guaranteed, repeatable output, a CI health check, a pre-deploy gate, anything where non-determinism is a bug, not a feature. An agent is the right tool when the problem is exploratory, and you don't yet know which three commands you'll need. They're not really competitors; they're two different interfaces that answer "is my cluster healthy" in two different situations. And notably, both could sit on top of the exact same <code>KubeClient</code> this post builds, the interface doesn't care whether its caller is a Cobra command or an MCP tool handler, which is itself a small argument for designing the client first, independent of either.</p>
<hr />
<h2>Project structure</h2>
<pre><code class="language-plaintext">go-k8s-mcp-server/
├── go.mod
└── internal/
    └── kubernetes/
        ├── client.go           ← KubeClient interface, constructor
        ├── pods.go             ← PodClient implementation
        ├── workloads.go        ← WorkloadClient implementation
        ├── nodes.go            ← NodeClient implementation
        ├── events.go           ← EventClient implementation
        ├── network.go          ← NetworkClient implementation
        ├── ingress.go          ← IngressClient implementation
        ├── gateway.go          ← GatewayClient implementation
        ├── config.go           ← ConfigClient implementation
        ├── storage.go          ← StorageClient implementation
        └── metrics.go          ← MetricsClient implementation
</code></pre>
<p>This is only the client half of the project, next post adds <code>cmd/k8s-mcp-server/</code> and <code>internal/tools/</code> on top of this same <code>internal/kubernetes/</code> package. The <code>internal/</code> boundary and one-package-per-domain layout follow the same convention laid out in <a href="https://ferztyle.me/go-packages-and-modules-explained">Go packages and modules explained</a>: <code>internal/</code> for everything the Go toolchain should keep private to this module, one focused file per concern rather than one large one.</p>
<p>If you haven't set up a client-go connection before, this post assumes that groundwork. I covered kubeconfig loading, the Clientset, and how API groups work in <a href="https://ferztyle.me/talking-to-kubernetes-from-go-a-practical-client-go-guide">Talking to Kubernetes from Go: a practical client-go guide</a>. Everything below builds directly on that same connection pattern, same <code>rest.Config</code> setup, same in-cluster/out-of-cluster fallback, same "wrap the Clientset behind an interface" philosophy. What's new here is the shape of the interface itself.</p>
<hr />
<h2>Designing the <code>KubeClient</code> interface</h2>
<p>A tempting first move is one fat interface with every method the agent might ever need. Resist it. A twenty-method interface is hard to test, hard to fake, and it hides the fact that these methods address genuinely different diagnostic concerns: some are about pods, some are about scheduling, some are about networking. Go rewards small interfaces, so we compose one from several.</p>
<p>If you're starting this project fresh rather than following along from the client-go post, pin the packages to your cluster's version, same as before, mixing minor versions across them breaks at compile time. <code>k8s.io/metrics</code> and <code>sigs.k8s.io/gateway-api</code> are included here too, even though neither is used until their respective sub-clients further down, because the <code>client</code> struct and <code>NewClient</code> constructor right below already need both:</p>
<pre><code class="language-shell">mkdir go-k8s-mcp-server &amp;&amp; cd go-k8s-mcp-server
go mod init github.com/FerRiosCosta/go-k8s-mcp-server

go get k8s.io/client-go@v0.36.2
go get k8s.io/api@v0.36.2
go get k8s.io/apimachinery@v0.36.2
go get k8s.io/metrics@v0.36.2
go get sigs.k8s.io/gateway-api@v1.3.0
go mod tidy
</code></pre>
<pre><code class="language-go">// internal/kubernetes/client.go
package kubernetes

import (
    "context"
    "fmt"

    "k8s.io/client-go/kubernetes"
    "k8s.io/client-go/rest"
    "k8s.io/client-go/tools/clientcmd"
    metricsclientset "k8s.io/metrics/pkg/client/clientset/versioned"
    gatewayclientset "sigs.k8s.io/gateway-api/pkg/client/clientset/versioned"
)

// KubeClient is the full set of read-only diagnostic operations the
// MCP server exposes as tools. It's composed from smaller, domain-specific
// interfaces so each one stays independently testable and each
// implementation file has exactly one reason to change.
//
// Every method here is read-only by design. There is no Delete, Scale,
// or Patch anywhere in this interface, that's not an accident, it's
// the security boundary. See "Read-only by construction" below.
type KubeClient interface {
    PodClient
    WorkloadClient
    NodeClient
    EventClient
    NetworkClient
    IngressClient
    GatewayClient
    ConfigClient
    StorageClient
    MetricsClient
}

// client is the concrete implementation every sub-interface method
// below is defined on. It holds three Clientsets: the core Clientset
// for everything except metrics and Gateway API, a metrics-server
// Clientset (the split the client-go post flagged as needed once
// k8s.io/metrics entered the picture), and a Gateway API Clientset,
// Gateway API is CRD-based, so it isn't reachable through the core
// Clientset the way Ingress is.
type client struct {
    clientset        kubernetes.Interface
    metricsClientset metricsclientset.Interface
    gatewayClientset gatewayclientset.Interface
}

// NewClient builds a KubeClient the same way kubectl resolves its
// config: in-cluster config if running inside a pod, otherwise
// $KUBECONFIG if set, otherwise ~/.kube/config, and whichever
// context is marked current-context in that file, automatically.
// There's no path parameter here on purpose: hardcoding a path means
// this server silently ignores context switches made with
// `kubectl config use-context`, which is exactly the surprise you
// don't want from a diagnostic tool.
func NewClient() (KubeClient, error) {
    config, err := buildConfig()
    if err != nil {
        return nil, fmt.Errorf("build config: %w", err)
    }

    clientset, err := kubernetes.NewForConfig(config)
    if err != nil {
        return nil, fmt.Errorf("create clientset: %w", err)
    }

    metricsClientset, err := metricsclientset.NewForConfig(config)
    if err != nil {
        return nil, fmt.Errorf("create metrics clientset: %w", err)
    }

    gatewayClientset, err := gatewayclientset.NewForConfig(config)
    if err != nil {
        return nil, fmt.Errorf("create gateway clientset: %w", err)
    }

    return &amp;client{
        clientset:        clientset,
        metricsClientset: metricsClientset,
        gatewayClientset: gatewayClientset,
    }, nil
}

func buildConfig() (*rest.Config, error) {
    if config, err := rest.InClusterConfig(); err == nil {
        return config, nil
    }

    // NewDefaultClientConfigLoadingRules checks $KUBECONFIG first
    // (colon-separated on Linux/macOS, semicolon on Windows, merging
    // multiple files if listed), then falls back to ~/.kube/config.
    // ConfigOverrides{} is empty on purpose, an empty overrides
    // struct means "use whatever current-context is set," the same
    // default clientcmd.BuildConfigFromFlags gave us before, just
    // without hardcoding the path ourselves.
    loadingRules := clientcmd.NewDefaultClientConfigLoadingRules()
    overrides := &amp;clientcmd.ConfigOverrides{}
    return clientcmd.NewNonInteractiveDeferredLoadingClientConfig(loadingRules, overrides).ClientConfig()
}
</code></pre>
<p>Same packages as the client-go post's <code>client.go</code>, plus two additions: <code>metricsclientset</code> from <code>k8s.io/metrics</code>, and <code>gatewayclientset</code> from <code>sigs.k8s.io/gateway-api</code>, both alongside the core Clientset. <code>gatewayClientset</code> will show <code>NewForConfig</code> succeed even against a cluster with no Gateway API CRDs installed; it's just a REST client pointed at a set of API paths, and only fails once you actually call it against a cluster that doesn't serve them. That failure mode gets called out concretely in the Gateway API section below.</p>
<p>Every method in the sections below is defined on this same <code>*client</code> type, one file per domain.</p>
<h3>Pods, the core of "why is my app broken"</h3>
<pre><code class="language-go">// internal/kubernetes/pods.go
package kubernetes

import (
    "context"
    "fmt"
    "io"

    corev1 "k8s.io/api/core/v1"
    metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)

// PodClient covers the operations that answer "what's wrong with this pod."
type PodClient interface {
    // ListPods returns pods in namespace. An empty namespace returns
    // pods from every namespace, same convention as ListPods in the
    // client-go guide.
    ListPods(ctx context.Context, namespace string) (*corev1.PodList, error)

    // GetPod returns a single pod by name, used once the agent has
    // narrowed down which pod it cares about.
    GetPod(ctx context.Context, namespace, name string) (*corev1.Pod, error)

    // GetPodLogs returns log output for one container in a pod.
    GetPodLogs(ctx context.Context, namespace, name string, opts LogOptions) (string, error)
}

// LogOptions bounds a log request. This type exists specifically so an
// agent can never accidentally pull megabytes of logs in a single tool
// call, TailLines and SinceSeconds are the caps, not suggestions.
type LogOptions struct {
    Container    string // empty selects the pod's first container
    Previous     bool   // true fetches the last terminated instance's logs,
                         // essential for CrashLoopBackOff, since the *current*
                         // instance often hasn't logged the failure yet
    TailLines    int64  // 0 falls back to a safe default, never "unbounded"
    SinceSeconds int64  // 0 means no time bound
}

const defaultLogTailLines = 200

func (c *client) ListPods(ctx context.Context, namespace string) (*corev1.PodList, error) {
    pods, err := c.clientset.CoreV1().Pods(namespace).List(ctx, metav1.ListOptions{})
    if err != nil {
        return nil, fmt.Errorf("list pods namespace=%q: %w", namespace, err)
    }
    return pods, nil
}

func (c *client) GetPod(ctx context.Context, namespace, name string) (*corev1.Pod, error) {
    pod, err := c.clientset.CoreV1().Pods(namespace).Get(ctx, name, metav1.GetOptions{})
    if err != nil {
        return nil, fmt.Errorf("get pod namespace=%q name=%q: %w", namespace, name, err)
    }
    return pod, nil
}

func (c *client) GetPodLogs(ctx context.Context, namespace, name string, opts LogOptions) (string, error) {
    tail := opts.TailLines
    if tail &lt;= 0 {
        tail = defaultLogTailLines
    }

    podLogOpts := &amp;corev1.PodLogOptions{
        Container: opts.Container,
        Previous:  opts.Previous,
        TailLines: &amp;tail,
    }
    if opts.SinceSeconds &gt; 0 {
        podLogOpts.SinceSeconds = &amp;opts.SinceSeconds
    }

    req := c.clientset.CoreV1().Pods(namespace).GetLogs(name, podLogOpts)
    stream, err := req.Stream(ctx)
    if err != nil {
        return "", fmt.Errorf("stream logs namespace=%q pod=%q: %w", namespace, name, err)
    }
    defer stream.Close()

    data, err := io.ReadAll(stream)
    if err != nil {
        return "", fmt.Errorf("read logs namespace=%q pod=%q: %w", namespace, name, err)
    }
    return string(data), nil
}
</code></pre>
<p>Note that <code>TailLines</code> defaults to <code>200</code>, not <code>0</code> meaning unbounded. That single line is the difference between a tool an agent can call freely and a tool that occasionally hands it 40,000 lines of stack traces and blows past its context window on one call.</p>
<h3>Events, often the fastest path to a root cause</h3>
<pre><code class="language-go">// internal/kubernetes/events.go
package kubernetes

import (
    "context"
    "fmt"

    corev1 "k8s.io/api/core/v1"
    metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)

// EventClient covers the Events API, which frequently surfaces a root
// cause, a failed scheduling attempt, an image pull error, before
// anything else does. It's queried by involved object, not by name,
// which is different enough from PodClient to earn its own file.
type EventClient interface {
    // GetEvents returns events in namespace, optionally filtered to
    // those involving a specific object name (e.g. a Pod).
    // An empty involvedObjectName returns all events in the namespace.
    GetEvents(ctx context.Context, namespace, involvedObjectName string) ([]corev1.Event, error)
}

func (c *client) GetEvents(ctx context.Context, namespace, involvedObjectName string) ([]corev1.Event, error) {
    opts := metav1.ListOptions{}
    if involvedObjectName != "" {
        opts.FieldSelector = "involvedObject.name=" + involvedObjectName
    }

    events, err := c.clientset.CoreV1().Events(namespace).List(ctx, opts)
    if err != nil {
        return nil, fmt.Errorf("list events namespace=%q object=%q: %w", namespace, involvedObjectName, err)
    }
    return events.Items, nil
}
</code></pre>
<h3>Workloads, rollout and scheduling problems above the pod</h3>
<p>Not every failure lives at the pod level. A deployment that's stuck rolling out, or one whose pods belong to two different generations at once, needs a different query shape entirely: you're not asking about one pod anymore, you're asking about the relationship between a Deployment and the ReplicaSets it owns.</p>
<pre><code class="language-go">// internal/kubernetes/workloads.go
package kubernetes

import (
    "context"
    "fmt"

    appsv1 "k8s.io/api/apps/v1"
    metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)

// WorkloadClient covers Deployments and the ReplicaSets they own,
// the layer above individual pods, where rollout and scheduling
// problems that span multiple pods actually live.
type WorkloadClient interface {
    // GetDeployment returns a Deployment's spec and status, including
    // desired vs. available replica counts and rollout conditions.
    GetDeployment(ctx context.Context, namespace, name string) (*appsv1.Deployment, error)

    // ListReplicaSets finds every ReplicaSet matching labelSelector in
    // a namespace. This is what surfaces orphaned or stuck ReplicaSets,
    // the classic "Deployment says 3/3 but two of those pods belong to
    // the old ReplicaSet" failed-rollout scenario, which GetDeployment
    // alone won't show you.
    ListReplicaSets(ctx context.Context, namespace, labelSelector string) (*appsv1.ReplicaSetList, error)
}

func (c *client) GetDeployment(ctx context.Context, namespace, name string) (*appsv1.Deployment, error) {
    deploy, err := c.clientset.AppsV1().Deployments(namespace).Get(ctx, name, metav1.GetOptions{})
    if err != nil {
        return nil, fmt.Errorf("get deployment namespace=%q name=%q: %w", namespace, name, err)
    }
    return deploy, nil
}

func (c *client) ListReplicaSets(ctx context.Context, namespace, labelSelector string) (*appsv1.ReplicaSetList, error) {
    rs, err := c.clientset.AppsV1().ReplicaSets(namespace).List(ctx, metav1.ListOptions{
        LabelSelector: labelSelector,
    })
    if err != nil {
        return nil, fmt.Errorf("list replicasets namespace=%q selector=%q: %w", namespace, labelSelector, err)
    }
    return rs, nil
}
</code></pre>
<p><code>ListReplicaSets</code> takes a label selector rather than a Deployment name because that's what the ReplicaSets API actually indexes on, a Deployment doesn't "contain" its ReplicaSets, it selects them by label, the same way a Service selects its pods. To go from "diagnose this Deployment" to "here are its ReplicaSets," a tool built on this interface pulls the selector off the Deployment's spec first (<code>deploy.Spec.Selector</code>), then passes that into <code>ListReplicaSets</code>. That two-step shape is exactly why this stays two methods instead of one convenience method that hides the relationship, the tool layer is where composing them into a single <code>diagnose_rollout</code>-style tool belongs, not the client.</p>
<h3>Nodes, capacity and scheduling context</h3>
<pre><code class="language-go">// internal/kubernetes/nodes.go
package kubernetes

import (
    "context"
    "fmt"

    corev1 "k8s.io/api/core/v1"
    metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)

// NodeClient covers cluster capacity, what you need to explain a
// "0/3 nodes are available" scheduling failure, which is a node-level
// question, not a pod-level one.
type NodeClient interface {
    ListNodes(ctx context.Context) (*corev1.NodeList, error)

    // GetNode returns conditions (MemoryPressure, DiskPressure,
    // PIDPressure), taints, and allocatable resources for one node.
    GetNode(ctx context.Context, name string) (*corev1.Node, error)
}

func (c *client) ListNodes(ctx context.Context) (*corev1.NodeList, error) {
    nodes, err := c.clientset.CoreV1().Nodes().List(ctx, metav1.ListOptions{})
    if err != nil {
        return nil, fmt.Errorf("list nodes: %w", err)
    }
    return nodes, nil
}

func (c *client) GetNode(ctx context.Context, name string) (*corev1.Node, error) {
    node, err := c.clientset.CoreV1().Nodes().Get(ctx, name, metav1.GetOptions{})
    if err != nil {
        return nil, fmt.Errorf("get node name=%q: %w", name, err)
    }
    return node, nil
}
</code></pre>
<h3>Network, is anything actually answering</h3>
<pre><code class="language-go">// internal/kubernetes/network.go
package kubernetes

import (
    "context"
    "fmt"

    corev1 "k8s.io/api/core/v1"
    metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)

// NetworkClient covers Services and Endpoints. A Service existing
// doesn't mean anything is listening behind it, that's exactly the
// gap GetEndpoints is here to close.
type NetworkClient interface {
    GetService(ctx context.Context, namespace, name string) (*corev1.Service, error)

    // GetEndpoints checks whether a Service actually has healthy pods
    // backing it. Zero endpoints despite matching pods usually means a
    // label selector mismatch or a failing readiness probe, one of the
    // most common "works locally, broken in cluster" bugs.
    GetEndpoints(ctx context.Context, namespace, serviceName string) (*corev1.Endpoints, error)
}

func (c *client) GetService(ctx context.Context, namespace, name string) (*corev1.Service, error) {
    svc, err := c.clientset.CoreV1().Services(namespace).Get(ctx, name, metav1.GetOptions{})
    if err != nil {
        return nil, fmt.Errorf("get service namespace=%q name=%q: %w", namespace, name, err)
    }
    return svc, nil
}

func (c *client) GetEndpoints(ctx context.Context, namespace, serviceName string) (*corev1.Endpoints, error) {
    // The Endpoints object shares its name with the Service it backs,
    // Kubernetes creates and keeps it in sync automatically, so no
    // separate lookup by label is needed here.
    eps, err := c.clientset.CoreV1().Endpoints(namespace).Get(ctx, serviceName, metav1.GetOptions{})
    if err != nil {
        return nil, fmt.Errorf("get endpoints namespace=%q service=%q: %w", namespace, serviceName, err)
    }
    return eps, nil
}
</code></pre>
<h3>Ingress on EKS, is the ALB even pointing here</h3>
<p>A healthy Service with healthy endpoints still means nothing to an external caller if the layer in front of it, the Ingress, and on EKS almost always the AWS Load Balancer Controller (LBC) behind it, never finished provisioning. This is a different failure class from anything <code>NetworkClient</code> covers: the Service can be perfectly correct and traffic still never arrives, because the ALB was never created, was created against the wrong subnets, or is pointing at the wrong target group.</p>
<pre><code class="language-go">// internal/kubernetes/ingress.go
package kubernetes

import (
    "context"
    "fmt"

    networkingv1 "k8s.io/api/networking/v1"
    metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)

// IngressClient covers classic Ingress resources, on EKS, almost
// always reconciled by the AWS Load Balancer Controller into an ALB.
// No AWS API calls happen here; everything comes from the Kubernetes
// object the controller writes status and events back onto, which is
// usually enough to tell you where reconciliation stalled.
type IngressClient interface {
    GetIngress(ctx context.Context, namespace, name string) (*networkingv1.Ingress, error)

    // ListIngressClasses lets a diagnosis confirm the Ingress's
    // ingressClassName actually exists and matches a real controller.
    // A typo'd or missing class is a common reason an Ingress just
    // sits there, the LBC never picks it up, and nothing in the
    // Ingress object itself says why.
    ListIngressClasses(ctx context.Context) (*networkingv1.IngressClassList, error)
}

func (c *client) GetIngress(ctx context.Context, namespace, name string) (*networkingv1.Ingress, error) {
    ing, err := c.clientset.NetworkingV1().Ingresses(namespace).Get(ctx, name, metav1.GetOptions{})
    if err != nil {
        return nil, fmt.Errorf("get ingress namespace=%q name=%q: %w", namespace, name, err)
    }
    return ing, nil
}

func (c *client) ListIngressClasses(ctx context.Context) (*networkingv1.IngressClassList, error) {
    classes, err := c.clientset.NetworkingV1().IngressClasses().List(ctx, metav1.ListOptions{})
    if err != nil {
        return nil, fmt.Errorf("list ingress classes: %w", err)
    }
    return classes, nil
}
</code></pre>
<p>Three things matter when reading an <code>Ingress</code> object for diagnosis, worth knowing even before the tool layer wraps this in part 2:</p>
<ul>
<li><p><code>ingress.Status.LoadBalancer.Ingress</code>: empty means the LBC either hasn't reconciled yet or is stuck. A populated hostname (the ALB's DNS name) means AWS-side provisioning succeeded; an empty one after more than a minute or two almost always means the LBC is failing, not just slow.</p>
</li>
<li><p><code>ingress.Spec.IngressClassName</code>: cross-reference this against <code>ListIngressClasses</code> output. A <code>nil</code> or misspelled class is the single most common reason an Ingress is silently ignored, no error on the object itself, the LBC just never claims it.</p>
</li>
<li><p><strong>Events on the Ingress object</strong>: this is where <code>EventClient.GetEvents</code>, already built above, becomes directly useful here without any new code: the LBC writes events like <code>SuccessfullyReconciled</code> on success, and specific failure reasons (invalid target group, subnet tagging problems, certificate ARN not found) as <code>Warning</code> events when reconciliation fails. Composing <code>GetIngress</code> with <code>GetEvents</code> is exactly the same pattern <code>describe_pod</code> used for pods, applied one layer up the stack.</p>
</li>
</ul>
<h3>Gateway API, the newer, cluster-portable entry point</h3>
<p>Gateway API is the follow-on to Ingress: instead of one annotation-heavy resource, traffic routing splits across a <code>Gateway</code> (the listener; where traffic enters, which addresses/ports it accepts) and route resources like <code>HTTPRoute</code> (how it's matched and where it goes). EKS supports it the same way it supports Ingress, the AWS Load Balancer Controller reconciles <code>Gateway</code>/<code>HTTPRoute</code> into an ALB, the same way it reconciles <code>Ingress</code>.</p>
<p>The client-side difference is real, not cosmetic: Gateway API types are CRDs, not part of the core Kubernetes API, so they need their own Clientset, the <code>gatewayClientset</code> already added to the <code>client</code> struct above.</p>
<pre><code class="language-go">// internal/kubernetes/gateway.go
package kubernetes

import (
    "context"
    "fmt"

    gatewayv1 "sigs.k8s.io/gateway-api/apis/v1"
    metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)

// GatewayClient covers Gateway API's two core resources. Both come
// back with rich status.conditions, Gateway API standardizes on
// Accepted/Programmed for Gateways and Accepted/ResolvedRefs for
// routes, which is a more structured diagnostic signal than Ingress
// ever gave you: no need to infer state from events alone.
type GatewayClient interface {
    GetGateway(ctx context.Context, namespace, name string) (*gatewayv1.Gateway, error)

    // GetHTTPRoute returns the route's status, including
    // per-parent-Gateway conditions. ResolvedRefs=False on a route
    // almost always means a backendRef points at a Service or port
    // that doesn't exist, check it before assuming the problem is
    // upstream at the Gateway.
    GetHTTPRoute(ctx context.Context, namespace, name string) (*gatewayv1.HTTPRoute, error)
}

func (c *client) GetGateway(ctx context.Context, namespace, name string) (*gatewayv1.Gateway, error) {
    gw, err := c.gatewayClientset.GatewayV1().Gateways(namespace).Get(ctx, name, metav1.GetOptions{})
    if err != nil {
        return nil, fmt.Errorf("get gateway namespace=%q name=%q: %w", namespace, name, err)
    }
    return gw, nil
}

func (c *client) GetHTTPRoute(ctx context.Context, namespace, name string) (*gatewayv1.HTTPRoute, error) {
    route, err := c.gatewayClientset.GatewayV1().HTTPRoutes(namespace).Get(ctx, name, metav1.GetOptions{})
    if err != nil {
        return nil, fmt.Errorf("get httproute namespace=%q name=%q: %w", namespace, name, err)
    }
    return route, nil
}
</code></pre>
<p>Diagnosis here is a two-level check, and skipping the first level is the most common mistake:</p>
<ul>
<li><p><code>gateway.Status.Conditions</code>: check <code>Accepted</code> and <code>Programmed</code> first. If the <code>Gateway</code> itself isn't <code>Programmed</code>, no <code>HTTPRoute</code> attached to it can possibly work, no matter how correct that route is. This is the equivalent of checking <code>describe_pod</code>'s container state before chasing application-level logs, start at the layer closest to the infrastructure.</p>
</li>
<li><p><code>httproute.Status.Parents[].Conditions</code>: a route can reference multiple Gateways, so status is reported per-parent, not once. <code>ResolvedRefs: False</code> specifically means a <code>backendRef</code>, the Service and port the route sends traffic to, doesn't resolve. That's diagnosable the same way <code>check_endpoints</code> diagnoses a plain Service: the route's <code>backendRefs[].name</code> and <code>.port</code> are exactly what <code>GetService</code>/<code>GetEndpoints</code> from earlier need to cross-check.</p>
</li>
<li><p><strong>A cluster without Gateway API CRDs installed</strong>: surfaces as a real error from <code>GetGateway</code>/<code>GetHTTPRoute</code>, a <code>NotFound</code>-shaped error on the CRD's group/version, not on the specific object. Worth catching and wrapping with a clearer message at the tool layer in part 2, the same way <code>pod_metrics</code> wraps a missing metrics-server as a clearer error than the bare API response gives you.</p>
</li>
</ul>
<h3>Config, keys only, never values</h3>
<pre><code class="language-go">// internal/kubernetes/config.go
package kubernetes

import (
    "context"
    "fmt"

    metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)

// ConfigClient deliberately returns key names only, for both
// ConfigMaps and Secrets. An agent diagnosing a missing env var needs
// to know a key exists, never what it contains, see "Read-only by
// construction" below for why that boundary lives here and not in a
// tool description.
type ConfigClient interface {
    GetConfigMapKeys(ctx context.Context, namespace, name string) ([]string, error)
    GetSecretKeys(ctx context.Context, namespace, name string) ([]string, error)
}

func (c *client) GetConfigMapKeys(ctx context.Context, namespace, name string) ([]string, error) {
    cm, err := c.clientset.CoreV1().ConfigMaps(namespace).Get(ctx, name, metav1.GetOptions{})
    if err != nil {
        return nil, fmt.Errorf("get configmap namespace=%q name=%q: %w", namespace, name, err)
    }
    keys := make([]string, 0, len(cm.Data))
    for k := range cm.Data {
        keys = append(keys, k)
    }
    return keys, nil
}

func (c *client) GetSecretKeys(ctx context.Context, namespace, name string) ([]string, error) {
    secret, err := c.clientset.CoreV1().Secrets(namespace).Get(ctx, name, metav1.GetOptions{})
    if err != nil {
        return nil, fmt.Errorf("get secret namespace=%q name=%q: %w", namespace, name, err)
    }
    // secret.Data is map[string][]byte, the values are deliberately
    // never read here, only the key names.
    keys := make([]string, 0, len(secret.Data))
    for k := range secret.Data {
        keys = append(keys, k)
    }
    return keys, nil
}
</code></pre>
<h3>Storage, volumes that can't bind</h3>
<pre><code class="language-go">// internal/kubernetes/storage.go
package kubernetes

import (
    "context"
    "fmt"

    corev1 "k8s.io/api/core/v1"
    metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)

// StorageClient surfaces the "pod stuck Pending because its volume
// can't bind" class of failure, a Pending PVC explains a Pending pod
// that otherwise looks like a scheduling mystery.
type StorageClient interface {
    ListPVCs(ctx context.Context, namespace string) (*corev1.PersistentVolumeClaimList, error)
}

func (c *client) ListPVCs(ctx context.Context, namespace string) (*corev1.PersistentVolumeClaimList, error) {
    pvcs, err := c.clientset.CoreV1().PersistentVolumeClaims(namespace).List(ctx, metav1.ListOptions{})
    if err != nil {
        return nil, fmt.Errorf("list pvcs namespace=%q: %w", namespace, err)
    }
    return pvcs, nil
}
</code></pre>
<h3>Metrics, the same extension the client-go post already teed up</h3>
<p><code>k8s.io/metrics</code> was already installed above alongside the three core packages, since <code>NewClient</code> needed <code>metricsclientset</code> before this section even started. This is where it actually gets used:</p>
<pre><code class="language-go">// internal/kubernetes/metrics.go
package kubernetes

import (
    "context"
    "fmt"

    metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
    metricsv1beta1 "k8s.io/metrics/pkg/apis/metrics/v1beta1"
)

// MetricsClient reads from the metrics-server extension API, a
// separate Clientset from the core one, same as it was flagged in the
// client-go post's "what's next" for the ferctl top CLI.
type MetricsClient interface {
    GetPodMetrics(ctx context.Context, namespace, name string) (*metricsv1beta1.PodMetrics, error)
    GetNodeMetrics(ctx context.Context, name string) (*metricsv1beta1.NodeMetrics, error)
}

func (c *client) GetPodMetrics(ctx context.Context, namespace, name string) (*metricsv1beta1.PodMetrics, error) {
    m, err := c.metricsClientset.MetricsV1beta1().PodMetricses(namespace).Get(ctx, name, metav1.GetOptions{})
    if err != nil {
        return nil, fmt.Errorf("get pod metrics namespace=%q name=%q: %w", namespace, name, err)
    }
    return m, nil
}

func (c *client) GetNodeMetrics(ctx context.Context, name string) (*metricsv1beta1.NodeMetrics, error) {
    m, err := c.metricsClientset.MetricsV1beta1().NodeMetricses().Get(ctx, name, metav1.GetOptions{})
    if err != nil {
        return nil, fmt.Errorf("get node metrics name=%q: %w", name, err)
    }
    return m, nil
}
</code></pre>
<p><code>GetPodMetrics</code> and <code>GetNodeMetrics</code> reach through a second Clientset, <code>c.metricsClientset</code>, built from <code>k8s.io/metrics</code> alongside the core one in <code>NewClient</code>, the same two-Clientset shape the client-go post flagged as coming in a future post, now realized here instead.</p>
<p><code>GetConfigMapKeys</code> and <code>GetSecretKeys</code> are worth pausing on. It would be less code to return the whole object, <code>map[string]string</code> and all. Returning only the keys is a security decision made at the interface boundary, before a single tool or prompt exists, an agent that can only ever see "this Secret has a key called <code>DATABASE_URL</code>" cannot leak what that key contains, no matter how it's prompted. That's a much stronger guarantee than "the tool description tells the agent not to print secret values."</p>
<h3>Read-only by construction</h3>
<h2>Summary</h2>
<p>Every method on <code>KubeClient</code> is <code>List</code>, <code>Get</code>, or <code>Stream</code>, nothing that mutates the cluster. That boundary, along with the read-only <code>Secret</code>/<code>ConfigMap</code> key-only design and the bounded <code>LogOptions</code>, all live in the Go types themselves rather than in documentation someone has to remember to follow. Three things worth taking away:</p>
<ul>
<li><p>Compose small, domain-specific interfaces (<code>PodClient</code>, <code>EventClient</code>, <code>NetworkClient</code>, ...) instead of one large <code>KubeClient</code> with twenty methods on it, easier to test, easier to fake, and each file has one reason to change.</p>
</li>
<li><p>Design the client before you design anything that calls it. Whether the caller ends up being a CLI, a report generator, or an AI agent, the interface should already answer "what's actually useful to ask a cluster" independent of who's asking.</p>
</li>
<li><p>Every safety boundary that matters, read-only access, bounded queries, secret values never leaving the cluster, belongs in the interface's types and method signatures, not in a comment asking future callers to be careful.</p>
</li>
</ul>
<p>Part 2 picks up exactly here: wrapping this <code>KubeClient</code> as MCP tools, wiring it to an agent, and running the whole thing end-to-end against a real cluster. <a href="https://ferztyle.me/build-an-mcp-server-in-go-part-2-building-the-mcp-tool-layer">Building a Kubernetes-aware AI agent with a Go MCP server →</a></p>
<hr />
<h2>Let's connect!</h2>
<p>If something in this post resonated, if you spotted a bug, or if you just want to talk Go, Kubernetes, AI agents, or Platform Engineering, I'm always happy to hear from you.</p>
<ul>
<li><p><strong>LinkedIn</strong></p>
</li>
<li><p><strong>GitHub</strong></p>
</li>
<li><p><strong>Twitter / X</strong></p>
</li>
</ul>
<p><em>Building from Asunción, Paraguay 🇵🇾</em></p>
<p><code>#go</code> <code>#kubernetes</code> <code>#platform-engineering</code></p>
]]></content:encoded></item><item><title><![CDATA[LeetCode #345 in Go: reverse vowels of a string, and how strings, bytes, and runes work in Go
]]></title><description><![CDATA[LeetCode #345 in Go: reverse vowels of a string, and how strings, bytes, and runes work in Go]]></description><link>https://ferztyle.me/leetcode-345-in-go-reverse-vowels-of-a-string-and-how-strings-bytes-and-runes-work-in-go</link><guid isPermaLink="true">https://ferztyle.me/leetcode-345-in-go-reverse-vowels-of-a-string-and-how-strings-bytes-and-runes-work-in-go</guid><category><![CDATA[golang]]></category><category><![CDATA[coding]]></category><category><![CDATA[coding challenge]]></category><dc:creator><![CDATA[Fer]]></dc:creator><pubDate>Wed, 05 Aug 2026 12:58:44 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/61db385c3ce4b2377adfdcda/a4ce50e5-0002-4d63-b4d8-cb19847994b6.svg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h2>Why I started this series</h2>
<p>A while back, I went through a job interview that included a coding challenge. It looked pretty easy, so I finished in like 90 seconds, and all tests passed! Then, the (non-technical) interviewer said to me:</p>
<ul>
<li><p>Interviewer: Why did you choose Golang? Do you actually know how to code in Golang?</p>
</li>
<li><p>Me: I said, yes, that challenge was easy, and all tests passed!.</p>
</li>
<li><p>Interviewer: Well, you only got 43% on that challenge.</p>
</li>
</ul>
<p>I'm going to be honest with you.</p>
<p>I've been writing about Go for a while: Lambda functions, Kubernetes tooling, HTTP middleware, client-go. But there's a difference between <em>using</em> Go and actually <em>understanding</em> Go.</p>
<p>I decided to fix that by doing LeetCode challenges. Not to grind interview prep. Not to get a FAANG job. Just to force myself to use the language in ways I wouldn't naturally reach for on a normal workday as a Senior SRE.</p>
<p>And something unexpected happened: every challenge I struggled with exposed a Go concept I hadn't fully understood. This is the first one.</p>
<hr />
<h2>The challenge</h2>
<h3>LeetCode #345</h3>
<blockquote>
<p><a href="https://leetcode.com/problems/reverse-vowels-of-a-string/description/">https://leetcode.com/problems/reverse-vowels-of-a-string/description/</a></p>
</blockquote>
<p>The problem requires us to reverse the vowels in a string. Note that letter case matters.</p>
<pre><code class="language-plaintext">Input: "IceCreAm"

Output: "AceCreIm"
</code></pre>
<hr />
<h2>Solution Approach</h2>
<p>The solution approach for this problem is to use 2 pointers, the two-pointer collision approach, to continuously swap the elements at the beginning and end.</p>
<blockquote>
<p>The solution approach was extrated from this [amazing book](http:// <a href="https://books.halfrost.com/leetcode/en/">https://books.halfrost.com/leetcode/en/</a> ), please consider reading this book if you want to improve your Golang coding skills like me.</p>
</blockquote>
<h3>The core idea: two pointers moving toward each other</h3>
<p>First, let's try to understand how the solution approach works. Imagine the string as a row of people standing in a line, numbered from left to right. You place one finger at the very first person (index <code>left = 0</code>) and another finger at the very last person (index <code>right = len - 1</code>). Then you move both fingers toward the middle, one step at a time, until they meet or cross.</p>
<p>This is different from two pointers moving in the <em>same</em> direction (like for finding duplicates in a sorted array). Here they move toward each other, which is why it's called the "collision" pattern; they're on a collision course toward the center.</p>
<h3>Why this pattern fits "reverse vowels"</h3>
<p>Think about what "reversing only the vowels" really means: the vowels that appear in the string should end up in reverse order, but every consonant should stay exactly where it is.</p>
<p>The trick is: you don't need to know the positions of all the vowels ahead of time. You can discover them as you scan from both ends, because:</p>
<ul>
<li><p>The <strong>leftmost</strong> vowel needs to be swapped with the <strong>rightmost</strong> vowel.</p>
</li>
<li><p>Then the <strong>second leftmost</strong> vowel needs to be swapped with the <strong>second rightmost</strong> vowel.</p>
</li>
<li><p>And so on, working inward.</p>
</li>
</ul>
<p>That's exactly what the collision pointers give you for free, if you use them correctly.</p>
<h3>Step-by-step logic</h3>
<ol>
<li><p>Set <code>left</code> at the start of the string, <code>right</code> at the end.</p>
</li>
<li><p><strong>Move</strong> <code>left</code> <strong>forward</strong> until it lands on a vowel (skip consonants).</p>
</li>
<li><p><strong>Move</strong> <code>right</code> <strong>backward</strong> until it lands on a vowel (skip consonants).</p>
</li>
<li><p>Once both <code>left</code> and <code>right</code> are sitting on vowels, <strong>swap them</strong>.</p>
</li>
<li><p>Move <code>left</code> one step further right, and <code>right</code> one step further left (since those two are now "done").</p>
</li>
<li><p>Repeat until <code>left &gt;= right</code> (the pointers meet or cross).</p>
</li>
</ol>
<p>Notice the elegance: consonants are never touched or moved; the pointers just glide past them. Only vowels get swapped, and because you're always taking the current outermost unprocessed vowel from each side, they naturally end up reversed relative to each other.</p>
<h3>Walking through an example</h3>
<p>Let's use <code>"leetcode"</code>.</p>
<pre><code class="language-plaintext">l  e  e  t  c  o  d  e
0  1  2  3  4  5  6  7
</code></pre>
<ul>
<li><p><code>left = 0</code> → <code>'l'</code> is not a vowel → move <code>left</code> to 1.</p>
</li>
<li><p>Index 1 → <code>'e'</code> is a vowel → stop <code>left</code> here.</p>
</li>
<li><p><code>right = 7</code> → <code>'e'</code> is a vowel → stop <code>right</code> here.</p>
</li>
<li><p>Both are vowels → swap index 1 and index 7. Since both are <code>'e'</code>, string looks unchanged, but conceptually a swap happened.</p>
</li>
<li><p>Move <code>left</code> to 2, <code>right</code> to 6.</p>
</li>
<li><p>Index 2 → <code>'e'</code> is a vowel → stop <code>left</code>.</p>
</li>
<li><p>Index 6 → <code>'d'</code> is not a vowel → move <code>right</code> to 5.</p>
</li>
<li><p>Index 5 → <code>'o'</code> is a vowel → stop <code>right</code>.</p>
</li>
<li><p>Swap index 2 (<code>'e'</code>) and index 5 (<code>'o'</code>) → now index 2 is <code>'o'</code>, index 5 is <code>'e'</code>.</p>
</li>
<li><p>Move <code>left</code> to 3, <code>right</code> to 4. Now <code>left (3) &lt; right (4)</code> still true, but index 3 is <code>'t'</code> (not vowel) → move <code>left</code> to 4. Now <code>left == right</code>, loop stops.</p>
</li>
</ul>
<p>Result: <code>"leotcede"</code>. That's the correct answer; the vowels <code>e, e, o, e</code> have been reversed to <code>e, o, e, e</code> while consonants <code>l, t, c, d</code> stayed in place.</p>
<h3>A second, trickier example: mixed case</h3>
<p>Try <code>"Aa"</code>, both are vowels (<code>'A'</code> and <code>'a'</code>, the problem says vowels can be uppercase or lowercase). <code>left=0</code> is <code>'A'</code>, <code>right=1</code> is <code>'a'</code>, both vowels immediately, so you swap. Result: <code>"aA"</code>. This tests that your vowel-check needs to handle <strong>both cases</strong>, not just lowercase.</p>
<hr />
<h2>Checklist for how you'd think about implementing it</h2>
<p>When you're ready to write this yourself, you'll want to think through:</p>
<ol>
<li><p><strong>How do I quickly check whether a character is a vowel?:</strong> Hint: a small lookup set/map is cleaner than a long chain of <code>if</code> statements comparing against <code>a, e, i, o, u, A, E, I, O, U</code>.</p>
</li>
<li><p><strong>Can I swap characters directly in a Go</strong> <code>string</code><strong>?:</strong> This is an important Go-specific gotcha: strings in Go are <strong>immutable</strong>, so you cannot do <code>s[i], s[j] = s[j], s[i]</code> directly on a <code>string</code>. You'll need to convert it into something mutable first.</p>
</li>
<li><p><code>[]byte</code> <strong>vs</strong> <code>[]rune</code>: Since this problem only deals with ASCII vowels, a <code>[]byte</code> conversion works fine and is efficient. (If the problem involved non-ASCII/multi-byte characters, you'd need <code>[]rune</code> instead.)</p>
</li>
<li><p><strong>Loop condition</strong>: When do you stop? (<code>left &lt; right</code>)</p>
</li>
<li><p><strong>Two separate inner loops or one combined check?</strong>: You need to advance <code>left</code> past consonants and advance <code>right</code> past consonants, independently, before doing the swap.</p>
</li>
</ol>
<p>Let's dig into the Go-specific mechanics that matter for this problem.</p>
<h3>Why Go strings are immutable</h3>
<p>In Go, a <code>string</code> is internally a small struct; conceptually, it looks like this:</p>
<pre><code class="language-go">type stringHeader struct {
    data uintptr // pointer to the underlying byte array
    len  int     // length in bytes
}
</code></pre>
<p>It's a <strong>read-only view</strong> into a sequence of bytes. The language spec deliberately does not let you write to that underlying array through a string variable. So this:</p>
<pre><code class="language-go">s := "leetcode"
s[0] = 'L' // compile error!
</code></pre>
<p>...will not even compile. Go gives you: <code>cannot assign to s[0] (neither addressable nor a map index expression)</code>.</p>
<p>This immutability exists for good reasons; it lets multiple strings safely <strong>share the same underlying byte array</strong> (e.g., substring operations like <code>s[2:5]</code> don't copy memory; they just create a new header pointing into the same data). If strings were mutable, that sharing would be dangerous; modifying one substring could silently corrupt another.</p>
<h3>How to get mutability: convert to <code>[]byte</code></h3>
<p>Since you <em>can</em> mutate a slice, the standard trick is to convert the string into a <code>[]byte</code>:</p>
<pre><code class="language-go">b := []byte(s)
</code></pre>
<p>This conversion <strong>copies</strong> the string's bytes into a brand-new, independent slice. Now you're free to do:</p>
<pre><code class="language-go">b[0] = 'L'
</code></pre>
<p>...because <code>b</code> is a slice, a mutable, addressable view over its own memory. When you're done modifying, you convert back:</p>
<pre><code class="language-go">result := string(b)
</code></pre>
<p>That conversion also <strong>copies</strong> the bytes back into a new immutable string. So the full round trip (<code>string</code> → <code>[]byte</code> → <code>string</code>) does involve two copies total, but for a single-pass algorithm like this one, that's totally acceptable and is the idiomatic way to do in-place-style string manipulation in Go.</p>
<h3><code>[]byte</code> vs <code>[]rune</code>: why it matters</h3>
<p>This is one of the most important Go concepts for string problems, so let's be precise about it.</p>
<ul>
<li><p>A <code>byte</code> is Go's alias for <code>uint8</code>, one 8-bit unit. <code>[]byte(s)</code> gives you the <strong>raw UTF-8 encoded bytes</strong> of the string.</p>
</li>
<li><p>A <code>rune</code> is Go's alias for <code>int32</code>, it represents a single <strong>Unicode code point</strong>, which might be encoded using 1 to 4 bytes in UTF-8.</p>
</li>
</ul>
<p>For plain ASCII characters, like the letters <code>a-z</code>, <code>A-Z</code> that this problem deals with, <strong>each character is exactly one byte</strong>. So <code>[]byte</code> gives you a clean one-index-per-character view, which is exactly what the two-pointer approach needs (<code>b[left]</code> and <code>b[right]</code> each represent one whole letter).</p>
<p>If the string contained non-ASCII characters (like <code>é</code>, <code>日</code>, or emoji), a single character could span multiple bytes, and indexing into <code>[]byte</code> at arbitrary positions could land you in the <em>middle</em> of a multi-byte character, corrupting it. In that scenario, you'd need <code>[]rune(s)</code> instead, which decodes the UTF-8 bytes into a slice where each element is one full code point, safe to index individually, at the cost of an extra decoding pass.</p>
<p>For this exercise, the constraints guarantee the input consists only of printable ASCII characters, so <code>[]byte</code> is the correct and more efficient choice. Good habit to build: <strong>always check the problem's constraints for character set before deciding between</strong> <code>[]byte</code> <strong>and</strong> <code>[]rune</code><strong>.</strong></p>
<h3>Checking "is this a vowel" idiomatically</h3>
<p>A few ways this is commonly done in Go, from least to most idiomatic for this case:</p>
<p><strong>Option A: long boolean chain (works, but verbose and easy to mistype):</strong></p>
<pre><code class="language-go">c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u' || c == 'A' || ...
</code></pre>
<p><strong>Option B: a map used as a set:</strong></p>
<pre><code class="language-go">vowels := map[byte]bool{
    'a': true, 'e': true, 'i': true, 'o': true, 'u': true,
    'A': true, 'E': true, 'I': true, 'O': true, 'U': true,
}
// then: vowels[c]
</code></pre>
<p>This is very readable. Map lookups are O(1) on average, so it doesn't hurt performance meaningfully for such a small, fixed set.</p>
<p><strong>Option C:</strong> <code>strings.ContainsRune</code><strong>:</strong></p>
<pre><code class="language-go">strings.ContainsRune("aeiouAEIOU", rune(c))
</code></pre>
<p>Short and clean, though technically does a linear scan over 10 characters each time; negligible here, but worth knowing it's not a true O(1) lookup like the map.</p>
<p>For a problem like this with a tiny, fixed alphabet, either B or C is considered clean, idiomatic Go. The map is generally preferred when you want to signal "this is a set membership check" clearly and efficiently.</p>
<h2>Bringing it together conceptually (still no full code)</h2>
<p>So your mental model in Go terms becomes:</p>
<ol>
<li><p>Convert <code>s</code> to <code>b := []byte(s)</code> to get a mutable working copy.</p>
</li>
<li><p>Run your <code>left</code>/<code>right</code> collision pointers over <code>b</code>, using your vowel-check function/map on <code>b[left]</code> and <code>b[right]</code>.</p>
</li>
<li><p>When both point to vowels, do a byte swap: <code>b[left], b[right] = b[right], b[left]</code>; this works fine because <code>b</code> is a slice, and Go allows this kind of tuple-assignment swap directly, no temp variable needed.</p>
</li>
<li><p>After the loop finishes, convert back: <code>string(b)</code>.</p>
</li>
</ol>
<hr />
<h2>A quick introduction to Big-O notation, and why this matter</h2>
<p>Good, let's tackle Big-O intuition first since it'll come up constantly in LeetCode, according to wikipedia:</p>
<blockquote>
<p>Big O notation is a mathematical framework used in computer science to describe how an algorithm's execution time or memory usage scales as the input size grows.</p>
</blockquote>
<h3>What "O(1)" actually means</h3>
<p>Big-O notation describes how the <strong>cost of an operation grows as the input size grows</strong>. The letter usually used for input size is <code>n</code>.</p>
<ul>
<li><p><strong>O(n)</strong> means: if you double the input size, the work roughly doubles too. A linear scan through an array is O(n), checking every element once.</p>
</li>
<li><p><strong>O(1)</strong> means: the amount of work stays <strong>constant, no matter how big the input is</strong>. It doesn't mean "one operation" literally, it means "a fixed, bounded number of operations that doesn't depend on <code>n</code>."</p>
</li>
</ul>
<p>Think of it like this analogy: imagine you have a giant phone book with a million names.</p>
<ul>
<li><p><strong>O(n) approach</strong>: You start at page 1 and flip through every single page looking for "Smith." If the book had 10 names, that'd be fast. With a million names, it's painfully slow; the work scales with the size of the book.</p>
</li>
<li><p><strong>O(1) approach</strong>: Instead, imagine you have a magic index card that instantly tells you "Smith is on page 4213", you jump straight there. Whether the book has 10 names or 10 million, that lookup takes the same tiny amount of time.</p>
</li>
</ul>
<h3>Why map lookups are O(1)</h3>
<p>A Go <code>map</code> is implemented as a <strong>hash table</strong>. When you do <code>vowels[c]</code>, Go doesn't loop through every key checking for a match. Instead:</p>
<ol>
<li><p>It runs the key (<code>c</code>) through a <strong>hash function</strong>; a formula that converts the key into a number very quickly.</p>
</li>
<li><p>That number tells it almost directly which "bucket" in memory to look in.</p>
</li>
<li><p>It checks that bucket (usually just one item, sometimes a couple if there's a hash collision) and returns the result.</p>
</li>
</ol>
<p>This process takes roughly the same amount of time whether your map has 5 entries or 5 million, that's why it's called O(1) <strong>on average</strong> (technically "amortized average case," since hash collisions can rarely cause it to degrade, but for practical purposes, treat it as constant time).</p>
<p>Compare that to <code>strings.ContainsRune("aeiouAEIOU", rune(c))</code>; internally, this <strong>does</strong> loop through the characters of that 10-character string comparing one by one until it finds a match or exhausts the string. It's technically O(k) where k is the length of that fixed string (10). Since 10 never changes, people often casually call it "O(1) too" because it's a <em>bounded constant</em>; but it's doing more actual comparisons than a map lookup, just not enough to matter for a 10-character set.</p>
<p><strong>The key exam-style distinction to remember:</strong> O(1) doesn't mean "instant" or "zero cost"; it means "cost that doesn't grow with your input size <code>n</code>."</p>
<hr />
<h2>Now, the tuple swap</h2>
<p>Go has a really elegant built-in feature for swapping: <strong>multiple assignment</strong>. When you write:</p>
<pre><code class="language-go">b[left], b[right] = b[right], b[left]
</code></pre>
<p>Here's what happens under the hood, step by step:</p>
<ol>
<li><p>Go first evaluates the <strong>entire right-hand side</strong> of the assignment, in order, <em>before</em> assigning anything. So it reads the current value of <code>b[right]</code> and the current value of <code>b[left]</code>, and holds both of them temporarily (essentially in a tuple, like <code>(valueOfRight, valueOfLeft)</code>).</p>
</li>
<li><p>Then it assigns those held values to the left-hand side, in order: <code>b[left]</code> gets the first held value (<code>old b[right]</code>), and <code>b[right]</code> gets the second held value (<code>old b[left]</code>).</p>
</li>
</ol>
<p>Because Go evaluates the whole right-hand side <em>first</em>, there's no risk of accidentally overwriting <code>b[left]</code> before you've read its original value to place into <code>b[right]</code>. This is exactly why you <strong>don't need a temporary variable</strong>, unlike languages such as C, where a swap traditionally requires:</p>
<pre><code class="language-c">temp = b[left];
b[left] = b[right];
b[right] = temp;
</code></pre>
<p>In Go, the language does that temporary-holding for you internally, and lets you express it in one clean line.</p>
<blockquote>
<p><strong>Remember:</strong> this works because slice indexing (<code>b[left]</code>) is <em>addressable</em>, meaning you can actually assign to that memory location. Recall this is exactly why we converted our <code>string</code> to a <code>[]byte</code> earlier; string indexing (<code>s[left]</code>) is <strong>not addressable</strong>, so <code>s[left], s[right] = s[right], s[left]</code> would fail to compile, but <code>b[left], b[right] = b[right], b[left]</code> works perfectly because <code>b</code> is a slice.</p>
</blockquote>
<hr />
<h2>Writing the full solution</h2>
<p>You now have all the conceptual pieces: two-pointer collision logic, why/how to convert <code>string</code> ↔ <code>[]byte</code>, <code>[]byte</code> vs <code>[]rune</code>, O(1) vowel checks, and how Go's swap syntax works.</p>
<pre><code class="language-go">func reverseVowels(s string) string {
    vowels := map[byte]bool{
        'a': true, 'e': true, 'i': true, 'o': true, 'u': true,
        'A': true, 'E': true, 'I': true, 'O': true, 'U': true, 
    }
    
    b := []byte(s)
    left, right := 0, len(b) - 1

    for left &lt; right {
        if !vowels[b[left]] {
            left++
            continue
        }
        if !vowels[b[right]] {
            right--
            continue
        }
        b[left], b[right] = b[right], b[left]
        left++
        right--

    }
    return string(b)
    
}
</code></pre>
<hr />
<h2>Summary</h2>
<p>Three things worth keeping from this problem:</p>
<ul>
<li><p><strong>Two-pointer collision</strong> is the pattern to reach for whenever a problem wants you to work from both ends of a sequence toward the middle, reversing, palindrome checks, and partitioning problems all lean on this same idea.</p>
</li>
<li><p><strong>Go strings are immutable.</strong> Any in-place-style string manipulation goes through a <code>string</code> → <code>[]byte</code> → <code>string</code> round trip.</p>
</li>
<li><p><strong>A map is your O(1) toolbox for set membership</strong>, and Go's tuple assignment (<code>a, b = b, a</code>) gives you a clean swap for free, as long as both sides are addressable.</p>
</li>
</ul>
<p>This problem is small, but it's a solid vehicle for internalizing patterns that show up constantly in string and array problems on LeetCode.</p>
<hr />
<h2><strong>Let's connect!</strong></h2>
<p>One of the best parts of writing in public is the people you meet along the way, engineers at different stages of their journey, working on similar problems from completely different angles.</p>
<p>If something in this post resonated, if you spotted a bug, or if you just want to talk Go, Kubernetes, Platform Engineering, DevOps, or whatever, I'm always happy to hear from you.</p>
<ul>
<li><p><a href="https://www.linkedin.com/in/ferrios/"><strong>LinkedIn</strong></a></p>
</li>
<li><p><a href="https://github.com/FerRiosCosta"><strong>GitHub</strong></a></p>
</li>
<li><p><a href="https://x.com/ferztyle"><strong>Twitter / X</strong></a></p>
</li>
</ul>
<p><em>Building from Asunción, Paraguay 🇵🇾</em></p>
]]></content:encoded></item><item><title><![CDATA[Building ferctl top: Kubernetes resource usage vs requests and limits]]></title><description><![CDATA[Build a production-quality Go CLI that shows Kubernetes CPU and memory usage alongside requests and limits, with near-limit warnings.]]></description><link>https://ferztyle.me/building-ferctl-top-kubernetes-resource-usage-vs-requests-and-limits</link><guid isPermaLink="true">https://ferztyle.me/building-ferctl-top-kubernetes-resource-usage-vs-requests-and-limits</guid><category><![CDATA[Go Language]]></category><category><![CDATA[Platform Engineering ]]></category><category><![CDATA[Kubernetes]]></category><category><![CDATA[cli]]></category><category><![CDATA[tools]]></category><dc:creator><![CDATA[Fer]]></dc:creator><pubDate>Sun, 02 Aug 2026 15:17:40 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/61db385c3ce4b2377adfdcda/75331605-ea83-4f40-a224-c7d8f85ea27f.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<blockquote>
<p><strong>Series:</strong> Platform engineering with Go | <strong>Topics:</strong> Go, Kubernetes, Cobra, client-go, metrics-server, Platform Engineering</p>
</blockquote>
<p><em>This is part of the</em> <em><strong>Platform Engineering with Go</strong></em> <em>series. This post builds on the Cobra CLI patterns from post 4 and client-go from post 3.</em> <a href="https://ferztyle.me/building-go-clis-with-cobra-a-practical-guide"><em>Read post 4 first</em></a> <em>if you haven't yet.</em></p>
<hr />
<h2>kubectl top tells you what's happening. It doesn't tell you how close to the edge you are.</h2>
<p>In <a href="https://ferztyle.me/talking-to-kubernetes-from-go-a-practical-client-go-guide">post 3</a> and <a href="https://ferztyle.me/building-go-clis-with-cobra-a-practical-guide">post 4</a>, we built a health reporter and learned how to structure a Go CLI with Cobra. Now we put both together into something with real operational value.</p>
<pre><code class="language-bash">kubectl top pods -n production

NAME                      CPU(cores)   MEMORY(bytes)
go-api-7d6b9f8c4-xk2pq   240m         490Mi
go-api-7d6b9f8c4-mn9rt   180m         210Mi
go-api-7d6b9f8c4-p8wvz   200m         198Mi
</code></pre>
<p>That first pod is using 490Mi of memory. Is that fine or is that a problem? Without knowing the limit, you can't tell. You'd have to run <code>kubectl describe pod go-api-7d6b9f8c4-xk2pq</code>, find the resources section, do the mental arithmetic, and repeat for every pod you care about.</p>
<p><code>ferctl top</code> does all of that in one command:</p>
<pre><code class="language-bash">ferctl top -n production

NAMESPACE    NAME                      CPU USE  CPU REQ  CPU LIM  CPU%  MEM USE  MEM REQ  MEM LIM  MEM%  STATUS
production   go-api-7d6b9f8c4-xk2pq   240m     250m     500m     48%   490Mi    256Mi    512Mi    95%   !! CRITICAL
production   go-api-7d6b9f8c4-mn9rt   180m     250m     500m     36%   210Mi    256Mi    512Mi    41%      OK
production   go-api-7d6b9f8c4-p8wvz   200m     250m     500m     40%   198Mi    256Mi    512Mi    38%      OK
</code></pre>
<p>One pod is at 95% of its memory limit. In production, that's a page waiting to happen. <code>ferctl top</code> catches it before it becomes an incident.</p>
<hr />
<h2>What you'll learn</h2>
<ul>
<li><p>How to extend the Cobra CLI structure from <a href="https://ferztyle.me/building-go-clis-with-cobra-a-practical-guide">post 4</a> with a real subcommand</p>
</li>
<li><p>How to query the metrics-server API using <code>k8s.io/metrics</code></p>
</li>
<li><p>How to correlate live metrics with pod specs to show usage vs limits</p>
</li>
<li><p>How to implement configurable near-limit warnings</p>
</li>
<li><p>How to format clean aligned output with <code>tabwriter</code></p>
</li>
<li><p>How to verify the tool against your real minikube cluster</p>
</li>
</ul>
<hr />
<h2>Prerequisites</h2>
<ul>
<li><p>Posts 1–4 read; client-go patterns from <a href="https://ferztyle.me/talking-to-kubernetes-from-go-a-practical-client-go-guide">post 3</a>, Cobra CLI structure from <a href="https://ferztyle.me/building-go-clis-with-cobra-a-practical-guide">post 4</a></p>
</li>
<li><p>minikube running with metrics-server enabled (from <a href="https://ferztyle.me/setting-up-a-local-kubernetes-cluster-with-minikube">post 2</a>)</p>
</li>
<li><p>Understand what limits and requests are in Kubernetes (from <a href="https://ferztyle.me/kubernetes-resource-requests-and-limits-explained-scheduling-throttling-and-oomkill">post1</a>)</p>
</li>
<li><p>Go 1.26.3 installed</p>
</li>
<li><p>The <code>go-api</code> deployment from <a href="https://ferztyle.me/setting-up-a-local-kubernetes-cluster-with-minikube">post 2</a> running in your cluster</p>
</li>
</ul>
<hr />
<h2>Project structure</h2>
<p>As always, go to this <a href="https://ferztyle.me/go-packages-and-modules-explained">post</a> if you don't know how to create a structure for your Golang project.</p>
<blockquote>
<p>Also, you can find the completed repo <a href="https://github.com/FerRiosCosta/ferctl">here</a></p>
</blockquote>
<pre><code class="language-plaintext">ferctl/
├── go.mod
├── Makefile
├── cmd/
│   └── ferctl/
│       └── main.go                  ← 3 lines — just calls Execute()
└── internal/
    ├── kubernetes/
    │   ├── client.go                ← KubeClient interface + real implementation
    │   └── metrics.go               ← MetricsClient interface + real implementation
    ├── top/
    │   ├── command.go               ← Cobra command — flags and wiring only
    │   ├── runner.go                ← business logic — fetches and correlates data
    │   ├── output.go                ← tabwriter formatting
    │   └── types.go                 ← PodRow and shared types
    └── threshold/
        └── threshold.go             ← near-limit warning logic — isolated and reusable
</code></pre>
<p>Each file has one reason to change, a design decision that will pay off in the next post when we add a namespace summary and JSON output without touching any of the existing files.</p>
<p>Here's the <code>go.mod</code>:</p>
<pre><code class="language-plaintext">module github.com/FerRiosCosta/ferctl

go 1.26

require (
    github.com/spf13/cobra      v1.10.2
    k8s.io/api                  v0.35.1
    k8s.io/apimachinery         v0.35.1
    k8s.io/client-go            v0.35.1
    k8s.io/metrics              v0.35.1
)
</code></pre>
<hr />
<h2>Installing the dependencies</h2>
<p>Before writing any code, initialize the module and install all dependencies. Run these commands inside your project directory:</p>
<pre><code class="language-bash">mkdir ferctl &amp;&amp; cd ferctl
go mod init github.com/FerRiosCosta/ferctl

# Install Cobra, the CLI framework
go get github.com/spf13/cobra@v1.10.2

# Install the Kubernetes packages, all pinned to match your server version
go get k8s.io/client-go@v0.35.1
go get k8s.io/api@v0.35.1
go get k8s.io/apimachinery@v0.35.1

# Install the metrics package, separate from client-go, explained below
go get k8s.io/metrics@v0.35.1

# Fetch all transitive dependencies and clean up
go get ./...
go mod tidy
</code></pre>
<h3>What is go get ./...?</h3>
<p>You'll notice we run <code>go get ./...</code> after installing the individual packages. Here's what it does and why it matters.</p>
<p><code>./...</code> means "every package in this module, recursively", <code>.</code> is the current directory, and <code>...</code> expands to all subdirectories.</p>
<pre><code class="language-plaintext">go get ./...
      │
      ▼
Scans every .go file in your module
      │
      ▼
Finds every import, including transitive ones
(packages that your packages depend on, that you never imported directly)
      │
      ▼
Downloads missing packages and adds them to go.mod and go.sum
</code></pre>
<p>When you run individual <code>go get</code> commands, Go downloads those specific packages, but doesn't always fetch everything they depend on internally. <code>k8s.io/client-go</code> itself imports <code>k8s.io/klog/v2</code>, <code>github.com/spf13/pflag</code>, <code>golang.org/x/net</code>, and many others. Those transitive dependencies might not be in your <code>go.sum</code> yet.</p>
<p>Without <code>go get ./...</code> you might see errors like:</p>
<pre><code class="language-plaintext">missing go.sum entry for module providing package k8s.io/klog/v2
</code></pre>
<p>That's <code>k8s.io/klog/v2</code>, a logging package that <code>k8s.io/client-go</code> uses internally. You never imported it directly, but Go needs its checksum in <code>go.sum</code> to verify the build. <code>go get ./...</code> catches it automatically.</p>
<h3>What is go mod tidy?</h3>
<p><code>go mod tidy</code> and <code>go get ./...</code> are often confused because they're usually run together. They do different things:</p>
<pre><code class="language-plaintext">go get ./...   → ADDS missing dependencies
               → fetches everything your code needs

go mod tidy    → CLEANS UP
               → removes dependencies that are no longer used
               → verifies go.sum is complete and consistent
</code></pre>
<p>Think of it this way:</p>
<ul>
<li><p><code>go get ./...</code> — <em>"make sure everything I need is downloaded"</em></p>
</li>
<li><p><code>go mod tidy</code> — <em>"remove anything I don't need and make sure go.sum is complete"</em></p>
</li>
</ul>
<p>Running both together is the safest way to ensure your module is in a clean, consistent state. Always run <code>go mod tidy</code> last; it's the final cleanup step.</p>
<blockquote>
<p>You don't need to run <code>go mod tidy</code> immediately; better to have all your code written and then run it.</p>
</blockquote>
<h3>Why is k8s.io/metrics a separate package?</h3>
<p>The <code>k8s.io/metrics</code> package is not part of <code>k8s.io/client-go</code>. It's a separate package because metrics-server is an extension API, not a core Kubernetes API. The Kubernetes API server doesn't collect resource usage itself; it delegates that to metrics-server, which exposes its data through a separate API endpoint. That's why it needs its own client package.</p>
<p>Before writing any code, verify metrics-server is running and collecting data:</p>
<pre><code class="language-bash">kubectl top pods -n default

# NAME                      CPU(cores)   MEMORY(bytes)
# go-api-7d6b9f8c4-xk2pq   2m           11Mi
</code></pre>
<p>If you see <code>error: Metrics API not available</code>, metrics-server isn't ready yet. Wait 60 seconds and try again. If it's not installed, enable it:</p>
<pre><code class="language-bash">minikube addons enable metrics-server
</code></pre>
<hr />
<h2>The entry point</h2>
<pre><code class="language-go">// cmd/ferctl/main.go
package main

import "github.com/FerRiosCosta/ferctl/internal/top"

// main is intentionally minimal, all wiring happens in internal packages.
func main() {
    top.Execute()
}
</code></pre>
<hr />
<h2>The Kubernetes client</h2>
<p>The <code>KubeClient</code> interface is the same pattern from <a href="https://ferztyle.me/talking-to-kubernetes-from-go-a-practical-client-go-guide">post 3</a>. We need one additional method, <code>ListPods</code> to fetch resource requests and limits from pod specs:</p>
<pre><code class="language-go">// internal/kubernetes/client.go
package kubernetes

import (
    "context"
    "fmt"

    corev1 "k8s.io/api/core/v1"
    metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
    "k8s.io/client-go/kubernetes"
    "k8s.io/client-go/rest"
    "k8s.io/client-go/tools/clientcmd"
)

// KubeClient defines the Kubernetes operations ferctl uses.
// Wrapping the Clientset behind an interface keeps ferctl testable
// without a real cluster.
type KubeClient interface {
    // ListPods returns all pods in the given namespace.
    // An empty namespace string returns pods from all namespaces.
    ListPods(ctx context.Context, namespace string) (*corev1.PodList, error)
}

// client is the real implementation backed by the official Kubernetes Clientset.
// Unexported, callers always use the KubeClient interface.
type client struct {
    clientset kubernetes.Interface
}

// NewClient creates a KubeClient from the kubeconfig at the given path.
// Tries in-cluster config first, then falls back to kubeconfig file.
func NewClient(kubeconfigPath string) (KubeClient, error) {
    config, err := buildConfig(kubeconfigPath)
    if err != nil {
        return nil, fmt.Errorf("build kubeconfig: %w", err)
    }
    clientset, err := kubernetes.NewForConfig(config)
    if err != nil {
        return nil, fmt.Errorf("create clientset: %w", err)
    }
    return &amp;client{clientset: clientset}, nil
}

// buildConfig tries in-cluster config first (inside a pod), then
// falls back to the kubeconfig file on disk (local development).
func buildConfig(kubeconfigPath string) (*rest.Config, error) {
    if config, err := rest.InClusterConfig(); err == nil {
        return config, nil
    }
    return clientcmd.BuildConfigFromFlags("", kubeconfigPath)
}

func (c *client) ListPods(ctx context.Context, namespace string) (*corev1.PodList, error) {
    pods, err := c.clientset.CoreV1().Pods(namespace).List(ctx, metav1.ListOptions{})
    if err != nil {
        return nil, fmt.Errorf("list pods namespace=%q: %w", namespace, err)
    }
    return pods, nil
}
</code></pre>
<hr />
<h2>The metrics client</h2>
<p>The metrics client queries the metrics-server API for real-time CPU and memory usage. We define our own <code>PodMetrics</code> type rather than exposing the raw metrics API type, this decouples the rest of ferctl from the metrics API's exact structure:</p>
<pre><code class="language-go">// internal/kubernetes/metrics.go
package kubernetes

import (
    "context"
    "fmt"

    "k8s.io/apimachinery/pkg/api/resource"
    metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
    metrics "k8s.io/metrics/pkg/client/clientset/versioned"
)

// PodMetrics holds real-time resource usage for a single pod.
// We define our own type here rather than exposing the raw metrics API
// type, this decouples the rest of ferctl from the metrics API's
// exact structure and makes the fake trivial to build.
type PodMetrics struct {
    Name      string
    Namespace string
    CPU       resource.Quantity // current CPU usage in millicores
    Memory    resource.Quantity // current memory usage in bytes
}

// MetricsClient defines the metrics-server operations ferctl uses.
type MetricsClient interface {
    // ListPodMetrics returns current CPU and memory usage for all pods
    // in the given namespace. An empty namespace returns all namespaces.
    ListPodMetrics(ctx context.Context, namespace string) ([]PodMetrics, error)
}

// metricsClient is the real implementation backed by the metrics-server API.
type metricsClient struct {
    clientset metrics.Interface
}

// NewMetricsClient creates a MetricsClient connected to the metrics-server.
func NewMetricsClient(kubeconfigPath string) (MetricsClient, error) {
    config, err := buildConfig(kubeconfigPath)
    if err != nil {
        return nil, fmt.Errorf("build kubeconfig for metrics: %w", err)
    }
    clientset, err := metrics.NewForConfig(config)
    if err != nil {
        return nil, fmt.Errorf("create metrics clientset: %w", err)
    }
    return &amp;metricsClient{clientset: clientset}, nil
}

// ListPodMetrics fetches current resource usage from the metrics-server
// and maps it to our own PodMetrics type.
func (m *metricsClient) ListPodMetrics(ctx context.Context, namespace string) ([]PodMetrics, error) {
    list, err := m.clientset.MetricsV1beta1().PodMetricses(namespace).List(ctx, metav1.ListOptions{})
    if err != nil {
        return nil, fmt.Errorf("list pod metrics namespace=%q: %w", namespace, err)
    }

    result := make([]PodMetrics, 0, len(list.Items))
    for _, item := range list.Items {
        // Sum CPU and memory across all containers in the pod.
        // A pod can have multiple containers, sidecars, init containers,
        // and we want the total resource usage, not just the main container.
        var totalCPU, totalMemory resource.Quantity
        for _, container := range item.Containers {
            totalCPU.Add(*container.Usage.Cpu())
            totalMemory.Add(*container.Usage.Memory())
        }

        result = append(result, PodMetrics{
            Name:      item.Name,
            Namespace: item.Namespace,
            CPU:       totalCPU,
            Memory:    totalMemory,
        })
    }

    return result, nil
}
</code></pre>
<hr />
<h2>The threshold package</h2>
<p>Warning logic lives in its own package; isolated, independently testable, and reusable across any future ferctl command that needs near-limit detection:</p>
<pre><code class="language-go">// internal/threshold/threshold.go
package threshold

import "k8s.io/apimachinery/pkg/api/resource"

// DefaultWarningPercent is the usage percentage above which a pod
// is considered near its limit and should be flagged.
const DefaultWarningPercent = 80

// Status represents how close a pod's usage is to its configured limit.
type Status int

const (
    StatusOK       Status = iota // usage is comfortably below the limit
    StatusWarning                // usage is above the warning threshold
    StatusCritical               // usage is at or above 95% of the limit
)

// String returns a human-readable label for display in the output table.
func (s Status) String() string {
    switch s {
    case StatusWarning:
        return "!  WARNING"
    case StatusCritical:
        return "!! CRITICAL"
    default:
        return "   OK"
    }
}

// Check returns the Status of a resource given its current usage and limit.
// If the limit is zero (not set), returns StatusOK, we can't warn without
// a limit to compare against.
func Check(usage, limit resource.Quantity, warningPercent int) Status {
    if limit.IsZero() {
        return StatusOK
    }

    usageVal := usage.MilliValue()
    limitVal := limit.MilliValue()

    if limitVal == 0 {
        return StatusOK
    }

    percent := (usageVal * 100) / limitVal

    switch {
    case percent &gt;= 95:
        return StatusCritical
    case percent &gt;= int64(warningPercent):
        return StatusWarning
    default:
        return StatusOK
    }
}

// Percent returns usage as a percentage of the limit.
// Returns 0 if the limit is zero; avoids division by zero.
func Percent(usage, limit resource.Quantity) int64 {
    if limit.IsZero() {
        return 0
    }

    usageVal := usage.MilliValue()
    limitVal := limit.MilliValue()

    if limitVal == 0 {
        return 0
    }

    return (usageVal * 100) / limitVal
}
</code></pre>
<hr />
<h2>The shared types</h2>
<pre><code class="language-go">// internal/top/types.go
package top

import (
    "k8s.io/apimachinery/pkg/api/resource"

    "github.com/FerRiosCosta/ferctl/internal/threshold"
)

// PodRow represents one row in the ferctl top output table.
// It's the intermediate data type between data fetching (runner.go)
// and formatting (output.go). Keeping it separate means the output
// layer can be swapped, tabwriter today, JSON in post 6, without
// touching the runner at all.
type PodRow struct {
    Namespace  string
    Name       string
    CPUUsage   resource.Quantity
    CPURequest resource.Quantity
    CPULimit   resource.Quantity
    CPUPercent int64
    CPUStatus  threshold.Status
    MemUsage   resource.Quantity
    MemRequest resource.Quantity
    MemLimit   resource.Quantity
    MemPercent int64
    MemStatus  threshold.Status
}
</code></pre>
<hr />
<h2>The runner, correlating pods and metrics</h2>
<p>The runner is the business logic layer. It fetches pod specs and metrics independently, correlates them by namespace and name, and returns a slice of <code>PodRow</code> ready for display. It knows nothing about Cobra or tabwriter, just data in, data out:</p>
<pre><code class="language-go">// internal/top/runner.go
package top

import (
    "context"
    "fmt"

    corev1 "k8s.io/api/core/v1"
    "k8s.io/apimachinery/pkg/api/resource"

    k8s "github.com/FerRiosCosta/ferctl/internal/kubernetes"
    "github.com/FerRiosCosta/ferctl/internal/threshold"
)

// Config holds everything the runner needs to execute.
// Using a struct instead of individual parameters makes it easy
// to add new options in the future without changing the function signature.
type Config struct {
    Namespace      string
    AllNamespaces  bool
    WarningPercent int
}

// Runner fetches and correlates Kubernetes resource data.
// It depends on interfaces, never on concrete client-go types,
// so it works identically with real clients and fakes.
type Runner struct {
    kube    k8s.KubeClient
    metrics k8s.MetricsClient
}

// NewRunner creates a Runner with its dependencies injected.
func NewRunner(kube k8s.KubeClient, metrics k8s.MetricsClient) *Runner {
    return &amp;Runner{kube: kube, metrics: metrics}
}

// Run fetches pod specs and metrics, correlates them, and returns
// a slice of PodRows ready for the output formatter.
func (r *Runner) Run(ctx context.Context, cfg Config) ([]PodRow, error) {
    namespace := cfg.Namespace
    if cfg.AllNamespaces {
        // Empty string means all namespaces in the Kubernetes API.
        namespace = ""
    }

    // Fetch pod specs, gives us requests and limits.
    pods, err := r.kube.ListPods(ctx, namespace)
    if err != nil {
        return nil, fmt.Errorf("fetch pods: %w", err)
    }

    // Fetch live resource usage from metrics-server.
    podMetrics, err := r.metrics.ListPodMetrics(ctx, namespace)
    if err != nil {
        return nil, fmt.Errorf("fetch metrics: %w", err)
    }

    // Build a lookup map from pod metrics for O(1) correlation.
    // Key format: "namespace/name", uniquely identifies a pod in the cluster.
    metricsMap := make(map[string]k8s.PodMetrics, len(podMetrics))
    for _, m := range podMetrics {
        key := m.Namespace + "/" + m.Name
        metricsMap[key] = m
    }

    rows := make([]PodRow, 0, len(pods.Items))
    for _, pod := range pods.Items {
        // Skip non-running pods, they won't have metrics from metrics-server.
        if pod.Status.Phase != corev1.PodRunning {
            continue
        }

        // Aggregate requests and limits across all containers in the pod.
        cpuReq, cpuLim, memReq, memLim := aggregateResources(&amp;pod)

        row := PodRow{
            Namespace:  pod.Namespace,
            Name:       pod.Name,
            CPURequest: cpuReq,
            CPULimit:   cpuLim,
            MemRequest: memReq,
            MemLimit:   memLim,
        }

        // Look up live metrics for this pod.
        // Newly started pods may not have metrics yet, handle gracefully
        // by leaving usage fields at their zero values.
        key := pod.Namespace + "/" + pod.Name
        if m, ok := metricsMap[key]; ok {
            row.CPUUsage   = m.CPU
            row.CPUPercent = threshold.Percent(m.CPU, cpuLim)
            row.CPUStatus  = threshold.Check(m.CPU, cpuLim, cfg.WarningPercent)
            row.MemUsage   = m.Memory
            row.MemPercent = threshold.Percent(m.Memory, memLim)
            row.MemStatus  = threshold.Check(m.Memory, memLim, cfg.WarningPercent)
        }

        rows = append(rows, row)
    }

    return rows, nil
}

// aggregateResources sums CPU and memory requests and limits across
// all containers in a pod, including sidecars and init containers.
// This matches how Kubernetes accounts for pod resource usage.
func aggregateResources(pod *corev1.Pod) (cpuReq, cpuLim, memReq, memLim resource.Quantity) {
    for _, container := range pod.Spec.Containers {
        res := container.Resources
        if req := res.Requests.Cpu(); req != nil {
            cpuReq.Add(*req)
        }
        if lim := res.Limits.Cpu(); lim != nil {
            cpuLim.Add(*lim)
        }
        if req := res.Requests.Memory(); req != nil {
            memReq.Add(*req)
        }
        if lim := res.Limits.Memory(); lim != nil {
            memLim.Add(*lim)
        }
    }
    return
}
</code></pre>
<hr />
<h2>The output formatter</h2>
<pre><code class="language-go">// internal/top/output.go
package top

import (
    "fmt"
    "io"
    "text/tabwriter"

    "k8s.io/apimachinery/pkg/api/resource"

    "github.com/FerRiosCosta/ferctl/internal/threshold"
)

// PrintTable writes the pod rows as an aligned table to w.
// Accepting io.Writer instead of os.Stdout directly means this
// function is testable, tests can pass a bytes.Buffer and inspect output.
func PrintTable(w io.Writer, rows []PodRow) {
    // tabwriter aligns columns by padding with spaces.
    // Arguments: output, minwidth, tabwidth, padding, padchar, flags.
    tw := tabwriter.NewWriter(w, 0, 0, 2, ' ', 0)
    defer tw.Flush()

    // Print the header row, \t is the column separator tabwriter uses.
    fmt.Fprintln(tw, "NAMESPACE\tNAME\tCPU USE\tCPU REQ\tCPU LIM\tCPU%\tMEM USE\tMEM REQ\tMEM LIM\tMEM%\tSTATUS")

    for _, row := range rows {
        // The overall row status is the worse of CPU and memory status.
        // If either is CRITICAL, the whole row is CRITICAL.
        status := worstStatus(row.CPUStatus, row.MemStatus)

        fmt.Fprintf(tw, "%s\t%s\t%s\t%s\t%s\t%d%%\t%s\t%s\t%s\t%d%%\t%s\n",
            row.Namespace,
            row.Name,
            formatQuantity(row.CPUUsage, "m"),    // CPU in millicores
            formatQuantity(row.CPURequest, "m"),
            formatQuantity(row.CPULimit, "m"),
            row.CPUPercent,
            formatQuantity(row.MemUsage, "Mi"),   // memory in mebibytes
            formatQuantity(row.MemRequest, "Mi"),
            formatQuantity(row.MemLimit, "Mi"),
            row.MemPercent,
            status.String(),
        )
    }
}

// worstStatus returns the more severe of two threshold statuses.
// CRITICAL &gt; WARNING &gt; OK, we always surface the worst condition.
func worstStatus(a, b threshold.Status) threshold.Status {
    if a &gt; b {
        return a
    }
    return b
}

// formatQuantity converts a resource.Quantity to a readable string.
// unit controls the suffix: "m" for millicores, "Mi" for mebibytes.
func formatQuantity(q resource.Quantity, unit string) string {
    switch unit {
    case "m":
        return fmt.Sprintf("%dm", q.MilliValue())
    case "Mi":
        // Convert bytes to mebibytes (1 MiB = 1024 * 1024 bytes)
        return fmt.Sprintf("%dMi", q.Value()/(1024*1024))
    default:
        return q.String()
    }
}
</code></pre>
<hr />
<h2>The Cobra command</h2>
<p>In <a href="https://ferztyle.me/building-go-clis-with-cobra-a-practical-guide">post 4</a> we built the full Cobra foundation, root command, persistent flags, <code>RunE</code>, <code>SilenceUsage</code>, and the <code>init()</code> wiring pattern. This file follows exactly the same structure. If anything here looks unfamiliar, <a href="https://ferztyle.me/building-go-clis-with-cobra-a-practical-guide">post 4</a> covers it in depth.</p>
<p>The key difference from the <code>k8s-info</code> example in <a href="https://ferztyle.me/building-go-clis-with-cobra-a-practical-guide">post 4</a> is that ferctl has two clients to initialize (Kubernetes and metrics) and passes them into a dedicated runner rather than doing the work inline in <code>RunE</code>. The Cobra layer stays thin; it only handles flags and wiring.</p>
<pre><code class="language-go">// internal/top/command.go
package top

import (
    "context"
    "fmt"
    "os"

    "github.com/spf13/cobra"

    k8s "github.com/FerRiosCosta/ferctl/internal/kubernetes"
    "github.com/FerRiosCosta/ferctl/internal/threshold"
)

// flags holds the parsed flag values across all subcommands.
// Using a struct keeps flag handling tidy as the CLI grows.
type flags struct {
    namespace      string
    allNamespaces  bool
    kubeconfig     string
    warningPercent int
}

var f flags

// rootCmd is the base command, every subcommand is registered on it.
var rootCmd = &amp;cobra.Command{
    Use:   "ferctl",
    Short: "Platform tooling for your Kubernetes cluster",
    Long:  "ferctl wraps common Kubernetes workflows into team-friendly commands.",
    // SilenceUsage prevents Cobra from printing the full usage text on
    // every error, covered in post 4. Add it to every root command.
    SilenceUsage: true,
}

// topCmd is the "ferctl top" subcommand.
var topCmd = &amp;cobra.Command{
    Use:   "top",
    Short: "Show resource usage vs requests and limits",
    Long: `Show CPU and memory usage alongside configured requests and limits
for every running pod. Flags pods approaching their limits.`,
    Example: `  ferctl top -n default
  ferctl top --all-namespaces
  ferctl top -n default --warning-percent 70`,
    RunE: func(cmd *cobra.Command, args []string) error {
        ctx := context.Background()

        // Build the Kubernetes client, real implementation using kubeconfig.
        kube, err := k8s.NewClient(f.kubeconfig)
        if err != nil {
            return fmt.Errorf("connect to cluster: %w", err)
        }

        // Build the metrics client, connects to metrics-server.
        metricsClient, err := k8s.NewMetricsClient(f.kubeconfig)
        if err != nil {
            return fmt.Errorf("connect to metrics-server: %w", err)
        }

        // Inject both clients into the runner, business logic is
        // completely decoupled from how clients are created.
        runner := NewRunner(kube, metricsClient)

        rows, err := runner.Run(ctx, Config{
            Namespace:      f.namespace,
            AllNamespaces:  f.allNamespaces,
            WarningPercent: f.warningPercent,
        })
        if err != nil {
            return err
        }

        if len(rows) == 0 {
            fmt.Println("no running pods found")
            return nil
        }

        PrintTable(os.Stdout, rows)
        return nil
    },
}

func init() {
    // --kubeconfig is a persistent flag, inherited by all subcommands.
    // Defaults to the standard kubectl location (~/.kube/config).
    // You almost never need to type it, the default handles it automatically.
    rootCmd.PersistentFlags().StringVar(
        &amp;f.kubeconfig,
        "kubeconfig",
        os.Getenv("HOME")+"/.kube/config",
        "path to kubeconfig file",
    )

    // Flags specific to the top subcommand, local flags, not persistent.
    topCmd.Flags().StringVarP(&amp;f.namespace, "namespace", "n", "default", "namespace to query")
    topCmd.Flags().BoolVar(&amp;f.allNamespaces, "all-namespaces", false, "query all namespaces")
    topCmd.Flags().IntVar(
        &amp;f.warningPercent,
        "warning-percent",
        threshold.DefaultWarningPercent,
        "usage % above which to show a warning (default 80)",
    )

    rootCmd.AddCommand(topCmd)
}

// Execute is the public entry point called from main.go.
func Execute() {
    if err := rootCmd.Execute(); err != nil {
        fmt.Fprintln(os.Stderr, err)
        os.Exit(1)
    }
}
</code></pre>
<hr />
<h2>The Makefile</h2>
<p><a href="https://ferztyle.me/building-go-clis-with-cobra-a-practical-guide">Post 4</a> covered what a Makefile is, how targets and dependencies work, and the tab character rule. This Makefile follows the same pattern, the only addition is a <code>test</code> target and the git version embedding introduced in <a href="https://ferztyle.me/building-go-clis-with-cobra-a-practical-guide">post 4's</a> Makefile:</p>
<pre><code class="language-makefile">BINARY  := ferctl
VERSION := $(shell git describe --tags --always --dirty 2&gt;/dev/null || echo "dev")

.PHONY: build install test clean

# -X embeds the git version into the binary at build time, same pattern as post 4.
build:
	go build \
	  -ldflags="-s -w -X github.com/FerRiosCosta/ferctl/internal/top.Version=$(VERSION)" \
	  -o $(BINARY) \
	  ./cmd/ferctl/...

# install depends on build — runs build first automatically.
install: build
	cp $(BINARY) /usr/local/bin/$(BINARY)
	@echo "installed $(BINARY) to /usr/local/bin"

# test runs the full test suite.
# -v: verbose output  -count=1: no caching  -race: detect race conditions.
test:
	go test ./... -v -count=1 -race

clean:
	rm -f $(BINARY)
</code></pre>
<p>Build and install:</p>
<pre><code class="language-bash">make install

# Verify it's available
ferctl --help
</code></pre>
<hr />
<h2>Verifying against minikube</h2>
<h3>Healthy cluster</h3>
<pre><code class="language-bash">ferctl top -n default

NAMESPACE   NAME                      CPU USE  CPU REQ  CPU LIM  CPU%  MEM USE  MEM REQ  MEM LIM  MEM%  STATUS
default     go-api-7d6b9f8c4-xk2pq   2m       50m      100m     2%    11Mi     32Mi     64Mi     17%      OK
default     go-api-7d6b9f8c4-mn9rt   2m       50m      100m     2%    10Mi     32Mi     64Mi     15%      OK
default     go-api-7d6b9f8c4-p8wvz   2m       50m      100m     2%    11Mi     32Mi     64Mi     17%      OK
</code></pre>
<h3>All namespaces</h3>
<pre><code class="language-bash">ferctl top --all-namespaces

NAMESPACE     NAME                                CPU USE  CPU REQ  CPU LIM  CPU%  MEM USE  MEM REQ  MEM LIM  MEM%  STATUS
default       go-api-7d6b9f8c4-xk2pq             2m       50m      100m     2%    11Mi     32Mi     64Mi     17%      OK
kube-system   coredns-5dd5756b68-7wvzp            4m       100m     0m       0%    14Mi     70Mi     170Mi    8%       OK
kube-system   metrics-server-7746f77f97-xswk9     4m       100m     0m       0%    20Mi     200Mi    0Mi      0%       OK
</code></pre>
<h3>Triggering a warning</h3>
<p>Use the <code>memory-hog.yaml</code> from <a href="https://ferztyle.me/building-go-clis-with-cobra-a-practical-guide">post 4</a> to create a pod that's under memory pressure:</p>
<pre><code class="language-bash">kubectl apply -f memory-hog.yaml

# Wait for CrashLoopBackOff
kubectl get pods -w
</code></pre>
<p>Lower the warning threshold to catch it:</p>
<pre><code class="language-bash">ferctl top -n default --warning-percent 50

NAMESPACE   NAME                      CPU USE  CPU REQ  CPU LIM  CPU%  MEM USE  MEM REQ  MEM LIM  MEM%  STATUS
default     go-api-7d6b9f8c4-xk2pq   2m       50m      100m     2%    11Mi     32Mi     64Mi     17%      OK
default     memory-hog                8m       0m       10Mi     0%    9Mi      10Mi     10Mi     90%   !! CRITICAL
</code></pre>
<p><code>memory-hog</code> is at 90% of its memory limit, <code>ferctl top</code> catches it immediately as CRITICAL. The <code>go-api</code> pods show as OK.</p>
<p>Clean up:</p>
<pre><code class="language-bash">kubectl delete pod memory-hog
</code></pre>
<hr />
<h2>Common gotchas</h2>
<p><strong>metrics-server not running</strong></p>
<p>If metrics-server isn't available, <code>ferctl top</code> returns a clear error immediately:</p>
<pre><code class="language-plaintext">Error: fetch metrics: list pod metrics namespace="default":
the server is currently unable to handle the request
</code></pre>
<p>Enable it on minikube and wait 60 seconds:</p>
<pre><code class="language-bash">minikube addons enable metrics-server
</code></pre>
<p><strong>Newly started pods have no metrics</strong></p>
<p>metrics-server scrapes data on a ~60 second interval. A pod that started less than a minute ago won't appear in metrics output. <code>ferctl top</code> handles this gracefully, it shows the pod with its requests and limits but leaves CPU% and MEM% at 0% rather than panicking on a missing key.</p>
<p><strong>Metrics lag under burst traffic</strong></p>
<p>metrics-server shows a point-in-time snapshot, not an average. A pod that just spiked and recovered may look fine by the time you check. For trending data over time, Prometheus with <code>container_memory_working_set_bytes</code> is more reliable. <code>ferctl top</code> is for current state visibility, not historical analysis.</p>
<p><strong>Multi-container pods, sidecars count</strong></p>
<p><code>ferctl top</code> sums CPU and memory across all containers in a pod, including sidecars like logging agents or service mesh proxies. If a sidecar is consuming unexpected resources, it shows up in the totals. Use <code>kubectl top pod &lt;name&gt; --containers</code> to see per-container breakdown.</p>
<p><strong>Pods without limits show 0%</strong></p>
<p>If a pod has no memory limit set (<code>limits.memory</code> not configured), <code>ferctl top</code> shows <code>0Mi</code> for MEM LIM and <code>0%</code> for MEM%, not a division error. This is intentional: we can't calculate a percentage without a known limit. This is also a signal, pods without limits set are <code>BestEffort</code> QoS class and are evicted first under node pressure (as covered in <a href="https://ferztyle.me/kubernetes-resource-requests-and-limits-explained-scheduling-throttling-and-oomkill">post 1</a>).</p>
<hr />
<h2>Summary</h2>
<p><code>ferctl top</code> is what the series has been building toward; the Kubernetes theory from post 1, the local cluster from post 2, the client-go patterns from post 3, and the Cobra CLI foundation from post 4, all combined into a single tool with real operational value.</p>
<p>Three things to take away:</p>
<ul>
<li><p>The <code>PodRow</code> intermediate type is what decouples the runner from the output layer, swapping tabwriter for JSON in post 6 is a 20-line change because of this design decision</p>
</li>
<li><p>The <code>threshold</code> package is isolated for a reason, reusable across any future ferctl command that needs near-limit detection</p>
</li>
<li><p>Pods without limits show <code>0%</code>, which is itself a useful signal that resource configuration is incomplete</p>
</li>
</ul>
<hr />
<h2>What's next</h2>
<p>In post 6 we extend ferctl with two new features: a namespace-level resource summary for capacity planning, and <code>--output=json</code> for CI pipelines and scripting. The project structure we built here handles both additions without touching any existing files.</p>
<hr />
<h2>Let's connect</h2>
<p>One of the best parts of writing in public is the people you meet along the way, engineers at different stages of their journey, working on similar problems from completely different angles.</p>
<p>If something in this post resonated, if you spotted a bug, or if you just want to talk Go, Kubernetes, platform engineering, jazz, or jiu-jitsu. I'm always happy to hear from you.</p>
<ul>
<li><p><a href="https://www.linkedin.com/in/ferrios/">LinkedIn</a></p>
</li>
<li><p><a href="https://github.com/yourname">GitHub</a></p>
</li>
<li><p><a href="https://x.com/yourhandle">Twitter / X</a></p>
</li>
</ul>
<p><em>Building from Asunción, Paraguay 🇵🇾</em></p>
]]></content:encoded></item><item><title><![CDATA[Building Go CLIs with Cobra: a practical guide]]></title><description><![CDATA[Learn how to build a Go CLI with Cobra: the library behind kubectl, helm, etc. Root commands, subcommands, flags, and a real working example.]]></description><link>https://ferztyle.me/building-go-clis-with-cobra-a-practical-guide</link><guid isPermaLink="true">https://ferztyle.me/building-go-clis-with-cobra-a-practical-guide</guid><category><![CDATA[golang]]></category><category><![CDATA[cobra]]></category><category><![CDATA[Kubernetes]]></category><category><![CDATA[Devops]]></category><category><![CDATA[Platform Engineering ]]></category><dc:creator><![CDATA[Fer]]></dc:creator><pubDate>Tue, 21 Jul 2026 13:04:39 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/61db385c3ce4b2377adfdcda/9a261ebc-81dc-4c91-bbd9-75458da9a9ff.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<blockquote>
<p><strong>Series:</strong> Platform engineering with Go | <strong>Topics:</strong> Go, Cobra, CLI, Platform Engineering</p>
</blockquote>
<p><em>This is part of the</em> <em><strong>Platform Engineering with Go</strong></em> <em>series. This post builds on the client-go patterns from post 3.</em> <a href="https://ferztyle.me/talking-to-kubernetes-from-go-a-practical-client-go-guide"><em>Read post 3 first</em></a> <em>if you haven't yet.</em></p>
<hr />
<h1>kubectl, helm, and the GitHub CLI all have something in common</h1>
<p>They're all built with Cobra.</p>
<p>Cobra is the Go library for building command-line tools. It handles subcommands, flags, help text, shell completions, and argument validation, everything you need to turn a Go program into a proper CLI that behaves the way engineers expect a CLI to behave.</p>
<p>If you've used <code>kubectl get pods</code>, <code>helm install</code>, or <code>gh pr create</code>, you've already used a Cobra CLI without knowing it. In this post, you'll learn how to build one.</p>
<p>By the end, you'll have a working CLI called <code>k8s-info</code> with two subcommands; <code>version</code> and <code>cluster</code>.</p>
<hr />
<h1>Prerequisites</h1>
<ul>
<li>Read posts 1–3 of this <a href="https://ferztyle.me/series/platform-engineering-with-go">series</a> (helpful but not required for this post)</li>
</ul>
<hr />
<h1>Project structure</h1>
<p>As always, we start our project by creating the structure. If you don't know how and why this structure is created, you can learn it <a href="https://ferztyle.me/go-packages-and-modules-explained">here</a>.</p>
<pre><code class="language-plaintext">k8s-info/
├── go.mod
├── Makefile
├── cmd/
│   └── k8s-info/
│       └── main.go              ← 3 lines — just calls Execute()
└── internal/
    └── cmd/
        ├── root.go              ← root command + persistent flags
        ├── version.go           ← "k8s-info version" subcommand
        └── cluster.go           ← "k8s-info cluster" subcommand
</code></pre>
<p>This structure scales. When we build our next command in the next post, we add more files under <code>internal/cmd/</code>, the root command never changes.</p>
<blockquote>
<p>You can find the whole project code <a href="https://github.com/FerRiosCosta/k8s-info">here</a></p>
</blockquote>
<p>Initialize (with your own module name), and install:</p>
<pre><code class="language-bash">mkdir k8s-info &amp;&amp; cd k8s-info
go mod init github.com/yourname/k8s-info

# Install Cobra — the CLI framework
go get github.com/spf13/cobra@v1.10.2

# Install the Kubernetes packages needed for the cluster subcommand
# All three must be pinned to the same version matching your server version
# Since our minikube server is v1.35.1, we use v0.35.1
go get k8s.io/client-go@v0.35.1
go get k8s.io/api@v0.35.1
go get k8s.io/apimachinery@v0.35.1

# Fetch all transitive dependencies and clean up
go get ./...
go mod tidy
</code></pre>
<hr />
<h1>What Cobra actually is</h1>
<p>Before writing any code, it helps to understand how Cobra thinks about a CLI.</p>
<p>Every Cobra CLI is a tree of commands:</p>
<pre><code class="language-plaintext">k8s-info                     ← root command
├── version                  ← subcommand
└── cluster                  ← subcommand
    ├── --namespace           ← local flag (only for cluster)
    └── --output              ← local flag (only for cluster)
</code></pre>
<p>The root command is the entry point, it's what runs when you type just <code>k8s-info</code>. Subcommands are registered on the root with <code>AddCommand()</code>. Flags can be attached to any command, and persistent flags (attached to the root) are inherited by every subcommand.</p>
<p>Cobra handles everything else automatically: <code>--help</code>, error messages, usage text, and shell completion stubs.</p>
<hr />
<h1>The entry point</h1>
<pre><code class="language-go">// cmd/k8s-info/main.go
package main

import "github.com/FerRiosCosta/k8s-info/internal/cmd"

// main is intentionally minimal, all command logic lives in internal/cmd/.
// This keeps the entry point clean and the business logic testable.
func main() {
    cmd.Execute()
}
</code></pre>
<p><mark class="bg-yellow-200 dark:bg-yellow-500/30">Three lines. If your </mark> <code>main.go</code> <mark class="bg-yellow-200 dark:bg-yellow-500/30">is longer than this, something belongs in a package.</mark></p>
<hr />
<h1>The root command</h1>
<pre><code class="language-go">// internal/cmd/root.go
package cmd

import (
    "fmt"
    "os"

    "github.com/spf13/cobra"
)

// kubeconfigPath holds the value of the --kubeconfig persistent flag.
// Declared at package level so every subcommand can read it.
var kubeconfigPath string

// rootCmd is the base command, the one that runs when you type just "k8s-info".
// Every subcommand is registered on it via AddCommand().
var rootCmd = &amp;cobra.Command{
    // Use is the one-line usage shown in help text.
    // The first word must be the binary name.
    Use: "k8s-info",

    // Short is the brief description shown in parent command help.
    Short: "A CLI for inspecting your Kubernetes cluster",

    // Long is the full description shown when you run "k8s-info --help".
    Long: `k8s-info is a platform engineering CLI for inspecting
Kubernetes cluster state. It connects to whatever cluster
your kubeconfig is currently pointing at.`,

    // SilenceUsage prevents Cobra from printing the full usage text
    // on every error, which gets noisy fast. Errors are still shown.
    SilenceUsage: true,
}

func init() {
    // PersistentFlags are inherited by every subcommand automatically.
    // --kubeconfig is something every subcommand might need, so it
    // belongs on the root as a persistent flag.
    rootCmd.PersistentFlags().StringVar(
        &amp;kubeconfigPath,
        "kubeconfig",
        os.Getenv("HOME")+"/.kube/config", // default: ~/.kube/config
        "path to the kubeconfig file",
    )
}

// Execute is the single public entry point called from main.go.
// It parses os.Args, finds the right command, and runs it.
func Execute() {
    if err := rootCmd.Execute(); err != nil {
        fmt.Fprintln(os.Stderr, err)
        os.Exit(1)
    }
}
</code></pre>
<h2>Why SilenceUsage matters</h2>
<p>By default, Cobra prints the full usage text every time an error occurs. This is often more confusing than helpful; the user sees a wall of text when what they really need is just the error message. <code>SilenceUsage: true</code> on the root command suppresses usage on errors for the entire CLI.</p>
<hr />
<h1>Adding subcommands</h1>
<h2>version subcommand</h2>
<pre><code class="language-go">// internal/cmd/version.go
package cmd

import (
    "fmt"

    "github.com/spf13/cobra"
)

// Version is set at build time using ldflags.
// Default to "dev" so it's always meaningful, even without a build.
var Version = "dev"

// versionCmd prints the current version of k8s-info.
var versionCmd = &amp;cobra.Command{
    Use:   "version",
    Short: "Print the k8s-info version",

    // Run is used when the command cannot fail.
    // If your command can return an error, use RunE instead (shown below).
    Run: func(cmd *cobra.Command, args []string) {
        fmt.Printf("k8s-info version %s\n", Version)
    },
}

func init() {
    // Register versionCmd on the root command.
    // After this, "k8s-info version" is a valid command.
    rootCmd.AddCommand(versionCmd)
}
</code></pre>
<h2>cluster subcommand</h2>
<pre><code class="language-go">// internal/cmd/cluster.go
package cmd

import (
    "context"
    "fmt"
    "os"

    "github.com/spf13/cobra"
    metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
    "k8s.io/client-go/kubernetes"
    "k8s.io/client-go/tools/clientcmd"
)

// namespace is a local flag, only available on the cluster subcommand,
// not on version or any future subcommand.
var namespace string

// clusterCmd shows a summary of what's running in the cluster.
var clusterCmd = &amp;cobra.Command{
    Use:   "cluster",
    Short: "Show a summary of running pods in your cluster",
    Example: `  k8s-info cluster
  k8s-info cluster -n kube-system
  k8s-info cluster --namespace default`,

    // RunE is the idiomatic choice when a command can fail.
    // It returns an error, Cobra prints it and exits with code 1.
    // Never call os.Exit inside RunE, let Cobra handle it.
    RunE: func(cmd *cobra.Command, args []string) error {
        // Build the Kubernetes config from the kubeconfig flag.
        // kubeconfigPath is inherited from the root persistent flag.
        config, err := clientcmd.BuildConfigFromFlags("", kubeconfigPath)
        if err != nil {
            return fmt.Errorf("connect to cluster: %w", err)
        }

        clientset, err := kubernetes.NewForConfig(config)
        if err != nil {
            return fmt.Errorf("create client: %w", err)
        }

        // List pods in the given namespace.
        pods, err := clientset.CoreV1().Pods(namespace).List(
            context.Background(),
            metav1.ListOptions{},
        )
        if err != nil {
            return fmt.Errorf("list pods namespace=%q: %w", namespace, err)
        }

        // Count pods by phase.
        var running, pending, failed int
        for _, pod := range pods.Items {
            switch pod.Status.Phase {
            case "Running":
                running++
            case "Pending":
                pending++
            case "Failed":
                failed++
            }
        }

        fmt.Printf("Namespace: %s\n", namespace)
        fmt.Printf("Total pods: %d\n", len(pods.Items))
        fmt.Printf("  Running: %d\n", running)
        fmt.Printf("  Pending: %d\n", pending)
        fmt.Printf("  Failed:  %d\n", failed)

        return nil
    },
}

func init() {
    // Local flags only apply to this subcommand.
    // --namespace with -n shorthand, defaults to "default".
    clusterCmd.Flags().StringVarP(
        &amp;namespace,
        "namespace", "n",
        "default",
        "namespace to inspect",
    )

    rootCmd.AddCommand(clusterCmd)
}
</code></pre>
<hr />
<h1>Persistent flags vs local flags</h1>
<p>This is one of the most important concepts in Cobra and worth understanding clearly before your CLI grows.</p>
<h2>Do you always have to type --kubeconfig?</h2>
<p>No, and this is the part that trips people up. Because <code>--kubeconfig</code> has a default value set:</p>
<pre><code class="language-go">rootCmd.PersistentFlags().StringVar(
    &amp;kubeconfigPath,
    "kubeconfig",
    os.Getenv("HOME")+"/.kube/config", // ← default is already set here
    "path to the kubeconfig file",
)
</code></pre>
<p>...<code>kubeconfigPath</code> is automatically populated with <code>~/.kube/config</code> every time any command runs. You never need to type <code>--kubeconfig</code> unless you want to point at a different file:</p>
<pre><code class="language-bash"># Default kubeconfig, flag not needed at all
k8s-info version
k8s-info cluster -n default

# Non-default kubeconfig, only specify when you need a different path
k8s-info --kubeconfig /path/to/other/config version
k8s-info --kubeconfig /path/to/other/config cluster
</code></pre>
<h2>The real difference between persistent and local</h2>
<p>The distinction that actually matters is this:</p>
<pre><code class="language-plaintext">Persistent flag, declared on rootCmd with PersistentFlags()
    ↓ inherited by ALL subcommands, available everywhere in the CLI
    k8s-info --kubeconfig /other/config version     ✓ works
    k8s-info --kubeconfig /other/config cluster     ✓ works
    k8s-info version --kubeconfig /other/config     ✓ also works (order flexible)

Local flag, declared on a specific command with Flags()
    ↓ only available on THAT specific subcommand
    k8s-info cluster -n kube-system                 ✓ works
    k8s-info version -n kube-system                 ✗ unknown flag: -n
</code></pre>
<p>The last two lines are what matters. <code>-n</code> is a local flag on <code>cluster</code>, it doesn't exist on <code>version</code>. If a user tries to pass it to <code>version</code>, Cobra rejects it with a clear error.</p>
<h2>The rule</h2>
<p>Simple: if every subcommand needs the flag (like <code>--kubeconfig</code>), make it persistent on the root. If only one subcommand needs it (like <code>--namespace</code> for cluster), make it local. When in doubt, start local; you can always promote a flag to persistent later, but removing a persistent flag is a breaking change for your users.</p>
<hr />
<h1>Run vs RunE</h1>
<p>Cobra gives you two options for the command function:</p>
<pre><code class="language-go">// Run, use when the command cannot fail
Run: func(cmd *cobra.Command, args []string) {
    fmt.Println("hello")
},

// RunE, use when the command can return an error
RunE: func(cmd *cobra.Command, args []string) error {
    if err := doSomething(); err != nil {
        return fmt.Errorf("something failed: %w", err)
    }
    return nil
},
</code></pre>
<p><strong>Always prefer</strong> <code>RunE</code> <strong>for anything that does I/O</strong>, file reads, network calls, Kubernetes API calls. The error is printed automatically by Cobra and the process exits with code 1. Never call <code>os.Exit</code> inside <code>RunE</code>; that bypasses any deferred cleanup and makes testing harder.</p>
<hr />
<h1>The Makefile</h1>
<p>A <code>Makefile</code> is a build automation file; it defines named commands called <strong>targets</strong> that you run with <code>make &lt;target&gt;</code>. Instead of typing long <code>go build</code> commands with flags every time, you type <code>make build</code> and the Makefile handles the rest.</p>
<p>Every target follows the same basic anatomy:</p>
<pre><code class="language-plaintext">target_name: optional_dependency
	command to run
</code></pre>
<p>The dependency means "run this target first before mine." If <code>install</code> depends on <code>build</code>, running <code>make install</code> automatically runs <code>make build</code> first, you never have to remember the order.</p>
<p>Two rules that trip up everyone writing their first Makefile:</p>
<ul>
<li><p><strong>Commands must be indented with a real tab character</strong>: spaces look identical but Make rejects them with a cryptic error</p>
</li>
<li><p><code>.PHONY</code> <strong>tells Make these are command names, not filenames</strong>: without it, Make looks for a file called <code>build</code> or <code>install</code> and gets confused when it doesn't find one</p>
</li>
</ul>
<p>Variables work like this:</p>
<pre><code class="language-makefile">BINARY := ferctl        # declare a variable
$(BINARY)               # reference it, expands to "ferctl"
</code></pre>
<p>The <code>@</code> prefix on a command suppresses echoing that line to the terminal, only the output is shown, not the command itself.</p>
<p>Here's the k8s-info Makefile with every line explained:</p>
<pre><code class="language-makefile"># BINARY is the name of the output binary, change this and everything updates.
BINARY  := k8s-info

# VERSION reads the current git tag automatically at build time.
# git describe returns something like "v1.2.0-3-gabcdef" for tagged commits.
# If you're not in a git repo, it falls back to "dev".
VERSION := $(shell git describe --tags --always --dirty 2&gt;/dev/null || echo "dev")

# .PHONY declares these as command names, not file names.
# Without this, Make would look for files called "build", "install", etc.
.PHONY: build install clean

# build compiles the binary for the current platform.
# -ldflags="-s -w" strips debug symbols, reduces binary size by ~30%.
# -X sets a Go package-level variable at build time (explained below).
# -o $(BINARY) names the output file.
build:
	go build \
	  -ldflags="-s -w -X github.com/FerRiosCosta/k8s-info/internal/cmd.Version=$(VERSION)" \
	  -o $(BINARY) \
	  ./cmd/k8s-info/...

# install depends on build, "make install" runs "make build" first automatically.
# Then copies the binary to /usr/local/bin so it's available system-wide.
install: build
	cp $(BINARY) /usr/local/bin/$(BINARY)
	@echo "installed $(BINARY) to /usr/local/bin"
	# @ suppresses printing the echo command, only the output is shown.

# clean removes the compiled binary so you can start fresh.
clean:
	rm -f $(BINARY)
</code></pre>
<p>The <code>-X</code> ldflag is new here compared to previous posts. It sets a Go package-level variable at build time; in this case <code>cmd.Version</code>. When you run <code>make build</code> in a git repository, <code>git describe</code> automatically fills in the version tag. When you run it outside git, it falls back to <code>"dev"</code>.</p>
<p>The targets work together in a natural workflow:</p>
<pre><code class="language-bash">make build    # compile the binary
make install  # compile + install to /usr/local/bin (runs build first)
make clean    # remove the binary and start fresh
</code></pre>
<h2>Understanding versions and git describe</h2>
<p>The <code>VERSION</code> variable in the Makefile uses <code>git describe</code> to automatically read a version from your git history. To understand how this works, it helps to understand what a version actually is in a git project.</p>
<h3>What is a version?</h3>
<p>A version is a named point in your git history, a label that says <em>"this is the code that shipped as v1.0.0"</em>. In git, this is called a <strong>tag</strong>. A tag is just a pointer to a specific commit, with a human-readable name.</p>
<p>Versions typically follow <strong>semantic versioning</strong> (semver):</p>
<pre><code class="language-plaintext">v1.2.3
│ │ └─── patch: bug fixes, no new features
│ └───── minor: new features, backward compatible
└─────── major: breaking changes
</code></pre>
<p>Examples of what each bump means in practice:</p>
<pre><code class="language-plaintext">v1.0.0  → first public release
v1.0.1  → fixed a bug in the cluster command
v1.1.0  → added a new "nodes" subcommand
v2.0.0  → renamed flags, changed output format (breaking)
</code></pre>
<h4>How to create a version in git</h4>
<p>First make sure your code is committed:</p>
<pre><code class="language-shell">git add .
git commit -m "feat: add cluster subcommand"
</code></pre>
<p>Then create a tag:</p>
<pre><code class="language-shell"># Create a tag pointing at the current commit
git tag v1.0.0

# Create a tag with an annotation message (recommended)
git tag -a v1.0.0 -m "First stable release of k8s-info"

# Push the tag to GitHub (tags dont push automatically with git push)
git push origin v1.0.0

# Or push all tags at once
git push origin --tags
</code></pre>
<h3>How git describe uses your tags</h3>
<p><code>git describe</code> reads the most recent tag in your git history and builds a version string from it:</p>
<pre><code class="language-shell">git describe --tags --always --dirty
</code></pre>
<p>The output depends on where you are in your commit history:</p>
<pre><code class="language-plaintext">v1.0.0                    ← exactly on the tagged commit
v1.0.0-3-gabcdef          ← 3 commits after v1.0.0, current hash is abcdef
v1.0.0-3-gabcdef-dirty    ← same, but you have uncommitted changes
abcdef                    ← no tags exist yet, falls back to commit hash
</code></pre>
<p>The flags we use:</p>
<table>
<thead>
<tr>
<th>Flag</th>
<th>What it does</th>
</tr>
</thead>
<tbody><tr>
<td><code>--tags</code></td>
<td>Considers all tags, not just annotated ones</td>
</tr>
<tr>
<td><code>--always</code></td>
<td>Falls back to the commit hash if no tags exist</td>
</tr>
<tr>
<td><code>--dirty</code></td>
<td>Appends <code>-dirty</code> if there are uncommitted changes</td>
</tr>
</tbody></table>
<p>And <code>2&gt;/dev/null || echo "dev"</code> handles the case where git isn't available at all (like in a CI environment without git installed); it silently swallows the error and falls back to <code>"dev"</code>.</p>
<h3>What this means for your binary</h3>
<p>When you run <code>make build</code> with a tagged commit:</p>
<pre><code class="language-shell">git tag -a v1.0.0 -m "first release"
make build
./k8s-info version
# k8s-info version v1.0.0
</code></pre>
<p>When you run it after adding more commits:</p>
<pre><code class="language-shell">git commit -m "fix: handle empty namespace"
make build
./k8s-info version
# k8s-info version v1.0.0-1-gabcdef
</code></pre>
<p>This tells you exactly which commit the binary was built from, invaluable when debugging a production issue and trying to figure out what version is actually running.</p>
<h3>A practical workflow for releasing</h3>
<pre><code class="language-shell"># 1. Make sure everything is committed and tested
git status              # should show nothing uncommitted
make test               # all tests pass

# 2. Create the version tag
git tag -a v1.0.0 -m "Initial release of k8s-info"

# 3. Build the binary, version is embedded automatically
make build
./k8s-info version
# k8s-info version v1.0.0

# 4. Install it
make install

# 5. Push the tag to GitHub
git push origin v1.0.0
</code></pre>
<p>From this point on, anyone who clones your repo and runs <code>make build</code> on that commit gets a binary that reports <code>v1.0.0</code>. No manual version files to maintain, no risk of forgetting to update a constant; git is the source of truth.</p>
<hr />
<h1>Running the CLI</h1>
<p>Build and install:</p>
<pre><code class="language-shell">make install
</code></pre>
<p>Try the commands:</p>
<pre><code class="language-shell"># Show help — generated automatically by Cobra
k8s-info --help

# Show version
k8s-info version
# k8s-info version dev

# Show cluster summary for the default namespace
k8s-info cluster

# Namespace: default
# Total pods: 3
# Running: 3
# Pending: 0
# Failed:  0

# Inspect kube-system
k8s-info cluster -n kube-system

# Namespace: kube-system
# Total pods: 7
# Running: 7
# Pending: 0
# Failed:  0

# Show help for the cluster subcommand
k8s-info cluster --help
</code></pre>
<h2>What Cobra generates automatically</h2>
<p>Run <code>k8s-info --help</code> and notice what you didn't have to write:</p>
<pre><code class="language-plaintext">A CLI for inspecting your Kubernetes cluster

Usage:
  k8s-info [command]

Available Commands:
  cluster     Show a summary of running pods in your cluster
  completion  Generate the autocompletion script for the specified shell
  help        Help about any command
  version     Print the k8s-info version

Flags:
  -h, --help                help for k8s-info
      --kubeconfig string   path to the kubeconfig file (default "/Users/yourname/.kube/config")

Use "k8s-info [command] --help" for more information about a command.
</code></pre>
<p>The <code>completion</code> and <code>help</code> subcommands, the <code>--help</code> flag, the usage text, the default values, all generated for free. That's what using Cobra buys you.</p>
<hr />
<h2>How init() wires everything together</h2>
<p>You may have noticed that every file calls <code>rootCmd.AddCommand()</code> inside an <code>init()</code> function. This is Go's package initialization mechanism; <code>init()</code> runs automatically when the package is imported, before <code>main()</code>.</p>
<pre><code class="language-plaintext">main() calls cmd.Execute()
      │
      ▼
Go initializes the cmd package
      │
      ├── root.go   init() runs → registers --kubeconfig flag
      ├── version.go init() runs → registers versionCmd on root
      └── cluster.go init() runs → registers clusterCmd on root
      │
      ▼
rootCmd.Execute() runs with all subcommands registered
</code></pre>
<p>This is why you can add a new subcommand by creating a new file and calling <code>rootCmd.AddCommand()</code> in its <code>init()</code>, no other file needs to change. The root command picks it up automatically.</p>
<hr />
<h1>Common gotchas</h1>
<h2><strong>Using Run instead of RunE for fallible commands</strong></h2>
<p>If your command calls a Kubernetes API or reads a file and you use <code>Run</code> instead of <code>RunE</code>, you have to handle errors yourself, usually with <code>fmt.Fprintln(os.Stderr, err); os.Exit(1)</code>. This is verbose, inconsistent, and bypasses Cobra's error handling. Always use <code>RunE</code> for anything that can fail.</p>
<h2><strong>Forgetting SilenceUsage</strong></h2>
<p>Without <code>SilenceUsage: true</code>, every error prints the full usage text, which is almost never what you want when a flag value is wrong or a Kubernetes call fails. Add it to the root command and save your users the confusion.</p>
<h2><strong>Persistent flags vs local flags confusion</strong></h2>
<p>If you declare a flag with <code>Flags()</code> on the root command, it's still a local flag, only available directly on the root, not inherited by subcommands. Use <code>PersistentFlags()</code> on the root for flags that should be available everywhere.</p>
<h2><strong>Flag order matters to users</strong></h2>
<p>Cobra parses flags after the command name. This means:</p>
<pre><code class="language-bash">k8s-info --kubeconfig ~/.kube/config cluster -n default   ✓ works
k8s-info cluster --kubeconfig ~/.kube/config -n default   ✓ also works
k8s-info cluster -n default --kubeconfig ~/.kube/config   ✓ also works
</code></pre>
<p>All three are equivalent; Cobra is flexible about flag position. But document a consistent order in your examples to avoid confusing users.</p>
<h2><strong>init() order is not guaranteed across files</strong></h2>
<p>Go guarantees that <code>init()</code> functions within a single file run in order, but the order between files in the same package is not guaranteed. This is fine for Cobra; <code>AddCommand()</code> calls are independent of each other. But don't write <code>init()</code> functions that depend on each other across files.</p>
<hr />
<h1>Summary</h1>
<p>Cobra turns a Go program into a proper CLI in three concepts:</p>
<ul>
<li><p><code>rootCmd</code>: the entry point, owns persistent flags, registers subcommands</p>
</li>
<li><p><code>AddCommand()</code>: how subcommands attach to the tree</p>
</li>
<li><p><code>RunE</code>: the function that runs when a command is invoked, returns an error or nil</p>
</li>
</ul>
<p>The <code>init()</code> pattern means adding a new subcommand is always: create a file, write the command, call <code>rootCmd.AddCommand()</code> in <code>init()</code>. Nothing else changes.</p>
<p>This is exactly the structure the next command uses in post 5; the root command, the persistent <code>--kubeconfig</code> flag, the <code>top</code> subcommand registered in its own file, all wired together by <code>init()</code>.</p>
<hr />
<h2>What's next</h2>
<p>In nex post we take this Cobra foundation and build <code>ferctl top</code> on top of it, adding the metrics-server client, resource threshold warnings, and tabwriter output. The <code>k8s-info cluster</code> command becomes the starting point for the richer <code>ferctl top</code> command.</p>
<hr />
<h2>Let's connect</h2>
<p>One of the best parts of writing in public is the people you meet along the way, engineers at different stages of their journey, working on similar problems from completely different angles.</p>
<p>If something in this post resonated, if you spotted a bug, or if you just want to talk Go, Kubernetes, platform engineering, jazz, or jiu-jitsu. I'm always happy to hear from you.</p>
<ul>
<li><p><a href="https://www.linkedin.com/in/ferrios/">LinkedIn</a></p>
</li>
<li><p><a href="https://github.com/yourname">GitHub</a></p>
</li>
<li><p><a href="https://x.com/yourhandle">Twitter / X</a></p>
</li>
</ul>
<p><em>Building from Asunción, Paraguay 🇵🇾</em></p>
]]></content:encoded></item><item><title><![CDATA[Talking to Kubernetes from Go: a practical client-go guide]]></title><description><![CDATA[Learn how client-go works by building a cluster health reporter in Go. Connecting to a cluster, detecting failing pods, and testing.]]></description><link>https://ferztyle.me/talking-to-kubernetes-from-go-a-practical-client-go-guide</link><guid isPermaLink="true">https://ferztyle.me/talking-to-kubernetes-from-go-a-practical-client-go-guide</guid><category><![CDATA[Go Language]]></category><category><![CDATA[Devops]]></category><category><![CDATA[Kubernetes]]></category><category><![CDATA[Platform Engineering ]]></category><category><![CDATA[client-go]]></category><dc:creator><![CDATA[Fer]]></dc:creator><pubDate>Mon, 13 Jul 2026 13:26:39 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/61db385c3ce4b2377adfdcda/0877e23a-797c-46b8-b147-6cb8f168b03d.jpg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>This is part of the <strong>Platform Engineering with Go</strong> series. This post builds on the minikube cluster set up in post 2. <a href="https://ferztyle.me/setting-up-a-local-kubernetes-cluster-with-minikube">Read post 2 first</a> if you haven't yet.</p>
<hr />
<h1>kubectl is great for humans. But what about programs?</h1>
<p>When you run <code>kubectl get pods</code>, something has to talk to the Kubernetes API server, deserialize the JSON response, and format it for your terminal. That something is client-go, the official Go client library for Kubernetes.</p>
<p>Every tool in the Kubernetes ecosystem is built on it. kubectl itself, helm, ArgoCD, controller-runtime, Tekton. If it talks to a Kubernetes cluster and it's written in Go, it's using client-go.</p>
<p>In this post, we'll learn how client-go works by building something immediately useful: a cluster health reporter. One Go program that connects to your minikube cluster, scans every pod across every namespace, and prints a complete health summary, the kind of view that usually takes four or five kubectl commands to assemble.</p>
<pre><code class="language-shell">Cluster Health Report
Generated: 2026-06-24 14:32:00 UTC

NAMESPACE     TOTAL   RUNNING   FAILING   PENDING
──────────────────────────────────────────────────
default           3         3         0         0
kube-system       6         6         0         0

✓ All pods healthy
</code></pre>
<p>And if something is wrong:</p>
<pre><code class="language-shell">Cluster Health Report
Generated: 2026-06-24 14:32:00 UTC

NAMESPACE     TOTAL   RUNNING   FAILING   PENDING
──────────────────────────────────────────────────
default           3         1         2         0
kube-system       6         6         0         0

FAILING PODS
──────────────────────────────────────────────────
default   go-api-7d6b9f8c4-mn9rt   CrashLoopBackOff   14 restarts
default   go-api-7d6b9f8c4-p8wvz   OOMKilled            3 restarts
</code></pre>
<h2>What you'll learn</h2>
<ul>
<li><p>What client-go is and how it relates to the Kubernetes API.</p>
</li>
<li><p>The four key packages and what each one contains.</p>
</li>
<li><p>How to connect to a cluster, out-of-cluster and in-cluster.</p>
</li>
<li><p>How the Clientset is organized, API groups explained.</p>
</li>
<li><p>How to list, filter, and inspect Kubernetes resources from Go.</p>
</li>
<li><p>How to build the cluster health reporter step by step.</p>
</li>
<li><p>How to test client-go code, two approaches with clear rules for when to use each.</p>
</li>
</ul>
<h2>Prerequisites</h2>
<ul>
<li>minikube running with the <code>go-api</code> deployment from <a href="https://ferztyle.me/setting-up-a-local-kubernetes-cluster-with-minikube">post 2</a></li>
</ul>
<hr />
<h1>What client-go is</h1>
<p>The Kubernetes API is a REST API. When you run <code>kubectl get pods -n default</code>, kubectl makes an HTTP GET request to something like:</p>
<pre><code class="language-plaintext">GET https://kubernetes/api/v1/namespaces/default/pods
</code></pre>
<p>The API server returns JSON. kubectl deserializes it and formats it for your terminal.</p>
<p>client-go is the library that handles all of this in Go: the HTTP calls, TLS, authentication, rate limiting, and deserialization into typed Go structs. Instead of working with raw JSON, you get a <code>*corev1.PodList</code> with typed fields you can navigate in your editor with autocomplete.</p>
<pre><code class="language-plaintext">Your Go program
      │
      │  client-go
      │  ├── kubeconfig loading
      │  ├── TLS + authentication
      │  ├── HTTP client + rate limiting
      │  └── JSON → typed Go structs
      │
      ▼
Kubernetes API server
      │
      ▼
etcd (the cluster's data store)
</code></pre>
<p>Everything you can do with kubectl, you can do with client-go, and more. kubectl is itself a client-go program.</p>
<hr />
<h1>Project structure</h1>
<p>Here is the Go project structure we are going to build; remember, you can see how to organize the code for your own projects <a href="https://ferztyle.me/go-packages-and-modules-explained">here</a>.</p>
<blockquote>
<p><mark class="bg-yellow-200 dark:bg-yellow-500/30">You can find the entire project </mark> <a href="https://github.com/FerRiosCosta/go-k8s-health-reporter/tree/main"><mark class="bg-yellow-200 dark:bg-yellow-500/30">here</mark></a><mark class="bg-yellow-200 dark:bg-yellow-500/30">.</mark></p>
</blockquote>
<pre><code class="language-plaintext">go-k8s-health-reporter/
├── go.mod
├── main.go                  ← entry point — wires dependencies, calls reporter
└── internal/
    ├── reporter/
    │   ├── types.go         ← data types — PodStatus, NamespaceSummary, Report
    │   ├── reporter.go      ← Reporter struct, Generate()
    │   ├── inspector.go     ← pod health detection — inspectPod(), pendingReason()
    │   └── printer.go       ← output formatting — Print(), tabwriter tables
    └── kubernetes/
        └── client.go        ← KubeClient interface + real implementation
</code></pre>
<h2>Installing the packages</h2>
<p>Before writing any code, initialize the module and install the dependencies. The version numbers must match your Kubernetes cluster; since we're running Kubernetes 1.36.2, we use <code>v0.36.2</code> for all three packages. Mixing versions causes compilation errors because the types won't match across packages. Remember to rename the module's name to your own module name.</p>
<pre><code class="language-shell"># Initialize the Go module
mkdir go-k8s-health-reporter &amp;&amp; cd go-k8s-health-reporter
go mod init github.com/FerRiosCosta/go-k8s-health-reporter

# Install the four packages pinned to Kubernetes 1.36.2
go get k8s.io/client-go@v0.36.2
go get k8s.io/api@v0.36.2
go get k8s.io/apimachinery@v0.36.2

# Tidy up — removes unused dependencies and ensures versions are consistent
go mod tidy
</code></pre>
<blockquote>
<p><strong>If you see a</strong> <code>missing go.sum entry</code> <strong>error</strong> after installing the packages, it means some transitive dependencies, packages that client-go depends on, like <code>k8s.io/klog/v2</code>, weren't added to <code>go.sum</code> automatically. Fix it with:</p>
<p>bash</p>
<pre><code class="language-bash">go get ./...
go mod tidy
</code></pre>
<p><code>go get ./...</code> scans all packages in your module and fetches every dependency recursively, including transitive ones. <code>go mod tidy</code> then writes the complete <code>go.sum</code>.</p>
</blockquote>
<p>Why pin to <code>v0.36.2</code> instead of <code>@latest</code>? The client-go versioning scheme directly mirrors Kubernetes releases; <code>v0.36.2</code> corresponds to Kubernetes <code>v1.36.2</code>. Always match your client-go version to your cluster version. If you run <code>@latest</code> you might get a newer client-go version than your cluster supports, which can cause unexpected API behavior.</p>
<p>You can verify your cluster version at any time:</p>
<pre><code class="language-shell">kubectl version

# Client Version: v1.36.2
# Server Version: v1.36.2
</code></pre>
<p>Both should match (ideally). If they don't, pin your packages to match the server version.</p>
<blockquote>
<p><strong>Note:</strong> <code>k8s.io/metrics</code> is not needed for the health reporter in this post, but you will need it for the next posts.</p>
<pre><code class="language-shell">go get k8s.io/metrics@v0.36.2
go mod tidy
</code></pre>
</blockquote>
<p>Here's the <code>go.mod</code>:</p>
<pre><code class="language-plaintext">module github.com/FerRiosCosta/go-k8s-health-reporter

go 1.26

require (
    k8s.io/api          v0.36.2
    k8s.io/apimachinery v0.36.2
    k8s.io/client-go    v0.36.2
)
</code></pre>
<hr />
<h1>The four key packages</h1>
<p>Before writing any code, let's understand the four packages client-go code almost always imports. This is the section that makes every future client-go import immediately readable.</p>
<h2>k8s.io/api: the Go type definitions</h2>
<pre><code class="language-go">import (
    corev1  "k8s.io/api/core/v1"   // Pod, Service, ConfigMap, Secret, Namespace, Node
    appsv1  "k8s.io/api/apps/v1"   // Deployment, StatefulSet, DaemonSet, ReplicaSet
    batchv1 "k8s.io/api/batch/v1"  // Job, CronJob
)
</code></pre>
<p>This package contains the Go struct definitions for every Kubernetes resource. When you write <code>corev1.Pod{}</code> or <code>appsv1.Deployment{}</code>, you're using this package. The aliases (<code>corev1</code>, <code>appsv1</code>) are conventions, the actual package names are just <code>v1</code>, which is too generic to use unaliased.</p>
<h2>k8s.io/apimachinery: the shared building blocks</h2>
<pre><code class="language-go">import (
    metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" // ObjectMeta, ListOptions, Time
    "k8s.io/apimachinery/pkg/api/resource"         // resource.Quantity (CPU, memory)
)
</code></pre>
<p>This package contains types shared across all Kubernetes API groups. <code>metav1.ObjectMeta</code> is the block every resource has: name, namespace, labels, annotations, creation timestamp. <code>metav1.ListOptions</code> lets you filter API calls by label selectors and field selectors. You'll import something from this package in virtually every file that touches the Kubernetes API.</p>
<h2>k8s.io/client-go: the actual client</h2>
<pre><code class="language-go">import (
    "k8s.io/client-go/kubernetes"        // the Clientset — entry point to all APIs
    "k8s.io/client-go/rest"              // rest.Config — holds connection details
    "k8s.io/client-go/tools/clientcmd"   // reads and parses kubeconfig files
)
</code></pre>
<p>This is the main package. <code>kubernetes.NewForConfig()</code> creates the Clientset, your entry point to every Kubernetes API. <code>clientcmd</code> reads the <code>~/.kube/config</code> file that minikube wrote in post 2. <code>rest.Config</code> holds the connection details: API server URL, TLS certificates, auth token.</p>
<h2>k8s.io/metrics: the metrics-server API</h2>
<pre><code class="language-go">import (
    metrics "k8s.io/metrics/pkg/client/clientset/versioned" // metrics Clientset
)
</code></pre>
<p>This is a separate package because metrics-server is an extension API, not part of the core Kubernetes API.</p>
<pre><code class="language-shell"># Install in post 4 — pinned to the same version as the rest
go get k8s.io/metrics@v0.36.2
go mod tidy
</code></pre>
<hr />
<h1>Connecting to the cluster</h1>
<p>Every client-go program starts the same way: build a <code>rest.Config</code>, then create a Clientset from it.</p>
<pre><code class="language-go">// internal/kubernetes/client.go
package kubernetes

import (
    "context"
    "fmt"

    corev1 "k8s.io/api/core/v1"
    metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
    "k8s.io/client-go/kubernetes"
    "k8s.io/client-go/rest"
    "k8s.io/client-go/tools/clientcmd"
)

// KubeClient defines the Kubernetes operations the health reporter uses.
// Wrapping the Clientset behind an interface makes the reporter testable
// without a real cluster, the same pattern used throughout this series.
type KubeClient interface {
    // ListPods returns all pods in the given namespace.
    // An empty namespace string returns pods from all namespaces.
    ListPods(ctx context.Context, namespace string) (*corev1.PodList, error)
}

// client is the real implementation backed by the official Kubernetes Clientset.
// It is unexported, callers always use the KubeClient interface.
type client struct {
    clientset kubernetes.Interface
}

// NewClient creates a KubeClient connected to the cluster in kubeconfig.
func NewClient(kubeconfigPath string) (KubeClient, error) {
    config, err := buildConfig(kubeconfigPath)
    if err != nil {
        return nil, fmt.Errorf("build config: %w", err)
    }

    clientset, err := kubernetes.NewForConfig(config)
    if err != nil {
        return nil, fmt.Errorf("create clientset: %w", err)
    }

    return &amp;client{clientset: clientset}, nil
}

// buildConfig tries in-cluster config first, then falls back to kubeconfig.
// This means the same binary works both locally (reads ~/.kube/config)
// and when deployed as a pod inside a cluster (reads the mounted service account token).
func buildConfig(kubeconfigPath string) (*rest.Config, error) {
    // in-cluster config: reads /var/run/secrets/kubernetes.io/serviceaccount/token
    // automatically mounted inside every pod by Kubernetes.
    if config, err := rest.InClusterConfig(); err == nil {
        return config, nil
    }

    // out-of-cluster config: reads the kubeconfig file from disk.
    // This is the file minikube wrote to ~/.kube/config in post 2.
    return clientcmd.BuildConfigFromFlags("", kubeconfigPath)
}

// ListPods retrieves all pods in the given namespace from the Kubernetes API.
// Passing an empty string returns pods from all namespaces.
func (c *client) ListPods(ctx context.Context, namespace string) (*corev1.PodList, error) {
    pods, err := c.clientset.CoreV1().Pods(namespace).List(ctx, metav1.ListOptions{})
    if err != nil {
        return nil, fmt.Errorf("list pods namespace=%q: %w", namespace, err)
    }
    return pods, nil
}
</code></pre>
<h2>The Clientset and API groups</h2>
<p><code>c.clientset.CoreV1().Pods(namespace).List(ctx, opts)</code>, let's break this chain down because you'll see it everywhere in client-go code:</p>
<pre><code class="language-go">c.clientset           // the Clientset, entry point to all Kubernetes APIs
    .CoreV1()         // select the "core" API group, version 1
    .Pods(namespace)  // select the Pods resource in the given namespace
    .List(ctx, opts)  // call the List operation with options
</code></pre>
<p>Kubernetes organizes resources into API groups. Each group contains related resources:</p>
<pre><code class="language-plaintext">CoreV1()  → Pods, Services, ConfigMaps, Secrets, Nodes, Namespaces
AppsV1()  → Deployments, StatefulSets, DaemonSets, ReplicaSets
BatchV1() → Jobs, CronJobs
</code></pre>
<p>The pattern is always the same: <code>clientset.APIGroup().ResourceType(namespace).Operation()</code>. Once you know this pattern, any client-go call is readable.</p>
<hr />
<h1>Building the cluster health reporter</h1>
<p>Now let's build the reporter. Instead of putting everything in one file, we'll split it across four focused files from the start, each with one clear responsibility.</p>
<pre><code class="language-plaintext">internal/reporter/
├── types.go      ← data types only — PodStatus, NamespaceSummary, Report
├── reporter.go   ← Reporter struct, constructor, Generate()
├── inspector.go  ← pod inspection logic — detects failing and pending states
└── printer.go    ← output formatting — tabwriter tables
</code></pre>
<p>Each file has one reason to change:</p>
<ul>
<li><p>New data field → <code>types.go</code></p>
</li>
<li><p>New data source → <code>reporter.go</code></p>
</li>
<li><p>New failure reason to detect → <code>inspector.go</code></p>
</li>
<li><p>New output format (JSON, CSV) → <code>printer.go</code></p>
</li>
</ul>
<h2>types.go, data types only</h2>
<pre><code class="language-go">// internal/reporter/types.go
package reporter

import "time"

// PodStatus represents the health state of a single pod.
type PodStatus struct {
    Namespace string
    Name      string
    Phase     string // Running, Pending, Failed, Succeeded
    Reason    string // CrashLoopBackOff, OOMKilled, etc. — more specific than Phase
    Restarts  int32  // total restarts across all containers
    IsFailing bool   // true if the pod is in a non-running problem state
    IsPending bool   // true if the pod is waiting to be scheduled or started
}

// NamespaceSummary holds the pod counts for a single namespace.
type NamespaceSummary struct {
    Namespace string
    Total     int
    Running   int
    Failing   int
    Pending   int
}

// Report is the complete cluster health picture.
type Report struct {
    GeneratedAt time.Time
    Namespaces  []NamespaceSummary
    Failing     []PodStatus
    Pending     []PodStatus
}
</code></pre>
<p>Thirty lines. No imports beyond <code>time</code>. If you need to add a field to a pod's health state, you open this file and only this file.</p>
<h3>inspector.go, pod health detection</h3>
<pre><code class="language-go">// internal/reporter/inspector.go
package reporter

import corev1 "k8s.io/api/core/v1"

// inspectPod examines a pod's status and returns a detailed PodStatus.
// It checks container states first, a pod can be in "Running" phase
// while individual containers are in CrashLoopBackOff or OOMKilled.
func inspectPod(pod *corev1.Pod) PodStatus {
    status := PodStatus{
        Namespace: pod.Namespace,
        Name:      pod.Name,
        Phase:     string(pod.Status.Phase),
    }

    // Sum restart counts and check container states.
    // Must check containers before pod phase, a pod can be "Running"
    // while a container inside it is waiting to restart.
    for _, cs := range pod.Status.ContainerStatuses {
        status.Restarts += cs.RestartCount

        if cs.State.Waiting != nil {
            switch cs.State.Waiting.Reason {
            case "CrashLoopBackOff", "OOMKilled", "ImagePullBackOff",
                "ErrImagePull", "CreateContainerConfigError":
                status.Reason = cs.State.Waiting.Reason
                status.IsFailing = true
                return status
            }
        }

        if cs.State.Terminated != nil {
            reason := cs.State.Terminated.Reason
            if reason == "OOMKilled" || cs.State.Terminated.ExitCode != 0 {
                status.Reason = reason
                status.IsFailing = true
                return status
            }
        }
    }

    // Check pod-level phase for broader failure states.
    switch pod.Status.Phase {
    case corev1.PodFailed:
        status.Reason = pod.Status.Reason
        status.IsFailing = true
    case corev1.PodPending:
        status.Reason = pendingReason(pod)
        status.IsPending = true
    }

    return status
}

// pendingReason extracts why a pod is pending from its conditions.
// The PodScheduled condition contains the human-readable scheduling
// failure message; e.g. "0/1 nodes are available: 1 Insufficient memory."
func pendingReason(pod *corev1.Pod) string {
    for _, condition := range pod.Status.Conditions {
        if condition.Type == corev1.PodScheduled &amp;&amp;
            condition.Status == corev1.ConditionFalse {
            return condition.Message
        }
    }
    return string(pod.Status.Phase)
}
</code></pre>
<h3>Understanding container states</h3>
<p>The <code>inspectPod</code> function works by reading <code>pod.Status.ContainerStatuses</code>, a slice that contains one entry per container in the pod. Each entry has a <code>State</code> field that holds exactly <strong>one of three possible states</strong> at any given moment:</p>
<p><strong>Waiting</strong>: the container is not yet running. This is where most failure reasons live:</p>
<table>
<thead>
<tr>
<th>Reason</th>
<th>What it means</th>
</tr>
</thead>
<tbody><tr>
<td><code>ContainerCreating</code></td>
<td>Image is being pulled, or volumes are being mounted</td>
</tr>
<tr>
<td><code>PodInitializing</code></td>
<td>Init containers are still running, main container hasn't started</td>
</tr>
<tr>
<td><code>CrashLoopBackOff</code></td>
<td>Container keeps crashing, Kubernetes is backing off before restarting</td>
</tr>
<tr>
<td><code>ImagePullBackOff</code></td>
<td>Image pull failed, Kubernetes is backing off before retrying</td>
</tr>
<tr>
<td><code>ErrImagePull</code></td>
<td>The immediate image pull error, before backoff kicks in</td>
</tr>
<tr>
<td><code>CreateContainerConfigError</code></td>
<td>Bad config, missing ConfigMap, Secret, or invalid env var</td>
</tr>
<tr>
<td><code>OOMKilled</code></td>
<td>Killed by the OOM killer, waiting to restart</td>
</tr>
</tbody></table>
<p><strong>Running</strong>: the container process is alive. Note that this doesn't mean the application inside it is healthy, it just means the process is executing. Your app could still be returning 500s or stuck in a deadlock.</p>
<p><strong>Terminated</strong>: the container has finished. The most important fields are:</p>
<table>
<thead>
<tr>
<th>Field</th>
<th>What it means</th>
</tr>
</thead>
<tbody><tr>
<td><code>ExitCode</code></td>
<td><code>0</code> = clean exit, anything else = failure</td>
</tr>
<tr>
<td><code>Reason</code></td>
<td><code>Completed</code> (clean) or <code>OOMKilled</code> (killed by OOM killer)</td>
</tr>
</tbody></table>
<p>Common exit codes worth knowing:</p>
<table>
<thead>
<tr>
<th>Exit code</th>
<th>Meaning</th>
</tr>
</thead>
<tbody><tr>
<td><code>0</code></td>
<td>Clean exit, completed successfully</td>
</tr>
<tr>
<td><code>1</code></td>
<td>Application error, the process itself returned an error</td>
</tr>
<tr>
<td><code>137</code></td>
<td><code>SIGKILL</code>, OOM killer fired, or forcefully killed</td>
</tr>
<tr>
<td><code>143</code></td>
<td><code>SIGTERM</code>, graceful shutdown (normal during pod termination)</td>
</tr>
</tbody></table>
<p>This is exactly why <code>inspectPod</code> checks <code>cs.State.Waiting</code> and <code>cs.State.Terminated</code> separately; each state carries different information in different fields.</p>
<h3>Init containers, the hidden failure</h3>
<p>There's one more status field worth knowing about:</p>
<pre><code class="language-go">pod.Status.ContainerStatuses      // current state of main containers
pod.Status.InitContainerStatuses  // current state of init containers
</code></pre>
<p>Init containers run before your main containers and go through the same three states. If an init container is stuck in <code>CrashLoopBackOff</code>, your main container will never start, and <code>pod.Status.ContainerStatuses</code> will be empty, giving you no indication of what's wrong.</p>
<p>The current <code>inspectPod</code> implementation only checks main container statuses. A more complete version would check init containers first:</p>
<pre><code class="language-go">// A more complete inspectPod that also catches stuck init containers.
// This is left as an exercise — the pattern is identical to the main
// container check, just reading from InitContainerStatuses instead.
func inspectPod(pod *corev1.Pod) PodStatus {
    status := PodStatus{
        Namespace: pod.Namespace,
        Name:      pod.Name,
        Phase:     string(pod.Status.Phase),
    }

    // Check init containers first — if one is stuck, main containers
    // will never start and ContainerStatuses will be empty.
    for _, cs := range pod.Status.InitContainerStatuses {
        status.Restarts += cs.RestartCount
        if cs.State.Waiting != nil {
            switch cs.State.Waiting.Reason {
            case "CrashLoopBackOff", "OOMKilled", "ImagePullBackOff",
                "ErrImagePull", "CreateContainerConfigError":
                status.Reason = "init: " + cs.State.Waiting.Reason
                status.IsFailing = true
                return status
            }
        }
    }

    // Then check main containers as before.
    for _, cs := range pod.Status.ContainerStatuses {
        // ... same logic as above
    }

    // ... rest of the function unchanged
}
</code></pre>
<p>Prefixing the reason with <code>"init: "</code> makes it immediately clear in the report that it's an init container failing, not the main application.</p>
<blockquote>
<p>You can add this code block before checking the main container in your project if you want.</p>
</blockquote>
<h2>printer.go, output formatting</h2>
<pre><code class="language-go">// internal/reporter/printer.go
package reporter

import (
    "fmt"
    "io"
    "strings"
    "text/tabwriter"
)

// Print writes the health report as a formatted table to w.
// Accepting io.Writer instead of os.Stdout directly keeps this
// testable — callers can pass a bytes.Buffer to inspect the output.
func (r *Reporter) Print(w io.Writer, report *Report) {
    fmt.Fprintf(w, "Cluster Health Report\n")
    fmt.Fprintf(w, "Generated: %s\n\n",
        report.GeneratedAt.Format("2006-01-02 15:04:05 UTC"),
    )

    printNamespaceSummary(w, report.Namespaces)

    if len(report.Failing) &gt; 0 {
        printFailingPods(w, report.Failing)
        return
    }

    if len(report.Pending) &gt; 0 {
        printPendingPods(w, report.Pending)
        return
    }

    fmt.Fprintf(w, "\n✓ All pods healthy\n")
}

// printNamespaceSummary writes the namespace totals table.
func printNamespaceSummary(w io.Writer, namespaces []NamespaceSummary) {
    tw := tabwriter.NewWriter(w, 0, 0, 3, ' ', 0)
    fmt.Fprintln(tw, "NAMESPACE\tTOTAL\tRUNNING\tFAILING\tPENDING")
    fmt.Fprintln(tw, strings.Repeat("─", 52))
    for _, ns := range namespaces {
        fmt.Fprintf(tw, "%s\t%d\t%d\t%d\t%d\n",
            ns.Namespace, ns.Total, ns.Running, ns.Failing, ns.Pending,
        )
    }
    tw.Flush()
}

// printFailingPods writes the failing pods detail section.
func printFailingPods(w io.Writer, pods []PodStatus) {
    fmt.Fprintf(w, "\nFAILING PODS\n")
    fmt.Fprintln(w, strings.Repeat("─", 52))
    tw := tabwriter.NewWriter(w, 0, 0, 3, ' ', 0)
    for _, p := range pods {
        fmt.Fprintf(tw, "%s\t%s\t%s\t%d restarts\n",
            p.Namespace, p.Name, p.Reason, p.Restarts,
        )
    }
    tw.Flush()
}

// printPendingPods writes the pending pods detail section.
func printPendingPods(w io.Writer, pods []PodStatus) {
    fmt.Fprintf(w, "\nPENDING PODS\n")
    fmt.Fprintln(w, strings.Repeat("─", 52))
    tw := tabwriter.NewWriter(w, 0, 0, 3, ' ', 0)
    for _, p := range pods {
        fmt.Fprintf(tw, "%s\t%s\t%s\n",
            p.Namespace, p.Name, p.Reason,
        )
    }
    tw.Flush()
}
</code></pre>
<h2>reporter.go, orchestration only</h2>
<pre><code class="language-go">// internal/reporter/reporter.go
package reporter

import (
    "context"
    "fmt"
    "time"

    k8s "github.com/FerRiosCosta/go-k8s-health-reporter/internal/kubernetes"
)

// Reporter builds health reports from Kubernetes data.
// It depends on the KubeClient interface, never on a concrete
// client-go type, so it works with both real and fake clients.
type Reporter struct {
    kube k8s.KubeClient
}

// New creates a Reporter with the given KubeClient injected.
func New(kube k8s.KubeClient) *Reporter {
    return &amp;Reporter{kube: kube}
}

// Generate fetches all pods from the cluster and builds a health report.
func (r *Reporter) Generate(ctx context.Context) (*Report, error) {
    // Fetch all pods across all namespaces.
    // Passing "" to ListPods returns pods from every namespace.
    pods, err := r.kube.ListPods(ctx, "")
    if err != nil {
        return nil, fmt.Errorf("fetch pods: %w", err)
    }

    report := &amp;Report{
        GeneratedAt: time.Now().UTC(),
    }

    // Group pods by namespace using a map.
    summaries := make(map[string]*NamespaceSummary)

    for _, pod := range pods.Items {
        // getOrCreate avoids the boilerplate of checking if the
        // namespace key exists before writing to the map.
        summary := getOrCreate(summaries, pod.Namespace)
        summary.Total++

        // inspectPod is defined in inspector.go, same package,
        // no import needed.
        status := inspectPod(&amp;pod)

        switch {
        case status.IsFailing:
            summary.Failing++
            report.Failing = append(report.Failing, status)
        case status.IsPending:
            summary.Pending++
            report.Pending = append(report.Pending, status)
        default:
            summary.Running++
        }
    }

    for _, summary := range summaries {
        report.Namespaces = append(report.Namespaces, *summary)
    }

    return report, nil
}

// getOrCreate returns the existing NamespaceSummary for the given namespace
// or creates a new one and registers it in the map.
// Extracted into its own function to keep Generate() readable.
func getOrCreate(m map[string]*NamespaceSummary, namespace string) *NamespaceSummary {
    if s, ok := m[namespace]; ok {
        return s
    }
    s := &amp;NamespaceSummary{Namespace: namespace}
    m[namespace] = s
    return s
}
</code></pre>
<p>Notice that <code>reporter.go</code> now has no output imports (<code>tabwriter</code>, <code>strings</code>, <code>io</code>) and no Kubernetes type imports beyond what it needs for <code>ListPods</code>. The <code>corev1</code> import moved entirely to <code>inspector.go</code> where it belongs. The <code>reporter</code> package is still one package, Go compiles all four files together, but each file is now independently readable.</p>
<h2>Wire it together in main.go</h2>
<pre><code class="language-go">// main.go
package main

import (
    "context"
    "fmt"
    "os"

    k8s "github.com/FerRiosCosta/go-k8s-health-reporter/internal/kubernetes"
    "github.com/FerRiosCosta/go-k8s-health-reporter/internal/reporter"
)

func main() {
    // Build the Kubernetes client using the kubeconfig minikube wrote in post 2.
    // This is the same file kubectl uses, no extra setup needed.
    kubeconfigPath := os.Getenv("HOME") + "/.kube/config"
    kube, err := k8s.NewClient(kubeconfigPath)
    if err != nil {
        fmt.Fprintf(os.Stderr, "failed to connect to cluster: %v\n", err)
        os.Exit(1)
    }

    // Build the reporter with the client injected.
    r := reporter.New(kube)

    // Generate and print the report.
    ctx := context.Background()
    report, err := r.Generate(ctx)
    if err != nil {
        fmt.Fprintf(os.Stderr, "failed to generate report: %v\n", err)
        os.Exit(1)
    }

    r.Print(os.Stdout, report)
}
</code></pre>
<hr />
<h1>Verifying against minikube</h1>
<p>The best way to verify the health reporter works is to run it against your real minikube cluster. No fakes, no mocks, just your actual cluster from post 2.</p>
<h2>Healthy cluster</h2>
<p>Make sure minikube is running and the <code>go-api</code> deployment from post 2 is up:</p>
<pre><code class="language-shell">kubectl get pods
# NAME                      READY   STATUS    RESTARTS   AGE
# go-api-7d6b9f8c4-xk2pq   1/1     Running   0          2d
# go-api-7d6b9f8c4-mn9rt   1/1     Running   0          2d
# go-api-7d6b9f8c4-p8wvz   1/1     Running   0          2d
</code></pre>
<p>Run the reporter:</p>
<pre><code class="language-shell">go run ./main.go
</code></pre>
<pre><code class="language-plaintext">Cluster Health Report
Generated: 2026-06-29 15:58:43 UTC

NAMESPACE   TOTAL   RUNNING   FAILING   PENDING
────────────────────────────────────────────────────
default                3   3   0   0
kube-system            8   8   0   0
kubernetes-dashboard   2   2   0   0

✓ All pods healthy
</code></pre>
<h2>Simulating a failing pod</h2>
<p>To verify the failing pod detection works we need a pod that reliably OOMKills. Our <code>go-api</code> binary turns out to be too lean to reliably trigger OOMKill at the Docker minimum, the multi-stage Dockerfile produced an extremely efficient binary. That's good engineering, but it makes for a tricky simulation.</p>
<p>Instead, let's deploy a pod that deliberately holds memory using Python's <code>bytearray</code>. Unlike shell tools like <code>dd</code> which stream data through memory and release it immediately, <code>bytearray</code> allocates a contiguous block and holds it, guaranteeing an OOMKill with a tight limit.</p>
<p>Create a file called <code>memory-hog.yaml</code>:</p>
<pre><code class="language-yaml"># memory-hog.yaml
apiVersion: v1
kind: Pod
metadata:
  name: memory-hog
  namespace: default
spec:
  # restartPolicy: Always ensures Kubernetes keeps restarting after each
  # OOMKill, driving the pod into CrashLoopBackOff.
  restartPolicy: Always
  containers:
  - name: hog
    image: python:3.12-alpine
    command: ["python3", "-c"]
    args:
    - |
      import time
      # bytearray allocates 100MB and holds it in physical memory.
      # The moment this runs, usage exceeds the 10Mi limit
      # and the OOM killer fires immediately.
      data = bytearray(100 * 1024 * 1024)
      print("allocated 100MB, holding...", flush=True)
      time.sleep(3600)
    resources:
      requests:
        memory: "10Mi"
      limits:
        memory: "10Mi"
</code></pre>
<p>Apply it:</p>
<pre><code class="language-shell">kubectl apply -f memory-hog.yaml
</code></pre>
<p>Watch the pod:</p>
<pre><code class="language-shell">kubectl get pods -w

# NAME          READY   STATUS             RESTARTS   AGE
# memory-hog   0/1     ContainerCreating  0          1s
# memory-hog   0/1     OOMKilled          0          4s   ← transient
# memory-hog   0/1     CrashLoopBackOff   1          10s  ← stable, run the reporter now
</code></pre>
<p>Once you see <code>CrashLoopBackOff</code>, run the reporter:</p>
<pre><code class="language-shell">go run ./main.go
</code></pre>
<pre><code class="language-shell">Cluster Health Report
Generated: 2026-07-01 21:37:47 UTC

NAMESPACE   TOTAL   RUNNING   FAILING   PENDING
────────────────────────────────────────────────────
kubernetes-dashboard   2   2   0   0
default                4   3   1   0
kube-system            8   8   0   0

FAILING PODS
────────────────────────────────────────────────────
default   memory-hog   CrashLoopBackOff   13 restarts
</code></pre>
<p>The reporter correctly identifies the failing pod, the reason, and the restart count.</p>
<p>Clean up when done:</p>
<pre><code class="language-shell">kubectl delete pod memory-hog
</code></pre>
<h2>Simulating a pending pod</h2>
<p>To verify pending detection, set a memory request higher than your node can provide. Again, both requests and limits must be set together:</p>
<pre><code class="language-shell">kubectl set resources deployment/go-api \
  --requests=memory=100Gi \
  --limits=memory=100Gi \
  -n default
</code></pre>
<p>The pods can't be scheduled, no node has 100Gi available. Run the reporter:</p>
<pre><code class="language-shell">go run ./main.go
</code></pre>
<pre><code class="language-shell">Cluster Health Report
Generated: 2026-07-01 22:03:51 UTC

NAMESPACE   TOTAL   RUNNING   FAILING   PENDING
────────────────────────────────────────────────────
default                4   3   0   1
kube-system            8   8   0   0
kubernetes-dashboard   2   2   0   0

PENDING PODS
────────────────────────────────────────────────────
default   go-api-6ff6496cb5-dnq6m   0/1 nodes are available: 1 Insufficient memory. no new claims to deallocate, preemption: 0/1 nodes are available: 1 Preemption is not helpful for scheduling.
</code></pre>
<p>The reason message comes directly from the pod's scheduling condition, exactly what the <code>pendingReason()</code> function extracts. Restore the correct values when done:</p>
<pre><code class="language-shell">kubectl set resources deployment/go-api \
  --requests=memory=32Mi \
  --limits=memory=64Mi \
  -n default
</code></pre>
<p><strong>Note on testing with fakes:</strong> In a future post we'll cover how to write unit tests for this reporter using interface fakes and client-go's built-in fake clientset, so the test suite runs without a real cluster. For now, minikube is our test environment.</p>
<hr />
<h1>Common gotchas</h1>
<h2><strong>Wrong kubeconfig context</strong></h2>
<p>The most common mistake when starting out with client-go. If you have multiple clusters in your kubeconfig, always verify before running Go code:</p>
<pre><code class="language-shell">kubectl config current-context
# Should print: minikube
</code></pre>
<p>If it shows a production cluster, switch back:</p>
<pre><code class="language-shell">kubectl config use-context minikube
</code></pre>
<h2><strong>Passing "" vs "default" to namespace-scoped resources</strong></h2>
<pre><code class="language-go">// Returns pods from ALL namespaces
clientset.CoreV1().Pods("").List(ctx, metav1.ListOptions{})

// Returns pods from the "default" namespace only
clientset.CoreV1().Pods("default").List(ctx, metav1.ListOptions{})
</code></pre>
<p>These behave completely differently. The empty string means "all namespaces", not "the default namespace." This is one of the most common sources of confusion in client-go code.</p>
<h2><strong>Pod phase vs container state, the big one</strong></h2>
<p>A pod in <code>Running</code> phase can have containers in <code>CrashLoopBackOff</code>. The phase is the pod-level state; the container state is what's actually happening inside. Always check both:</p>
<pre><code class="language-go">// WRONG: misses CrashLoopBackOff pods
if pod.Status.Phase != corev1.PodRunning {
    // handle failing pod
}

// RIGHT: catches CrashLoopBackOff even when phase is Running
for _, cs := range pod.Status.ContainerStatuses {
    if cs.State.Waiting != nil &amp;&amp; cs.State.Waiting.Reason == "CrashLoopBackOff" {
        // handle failing container
    }
}
</code></pre>
<h2><strong>Creating a new Clientset per function call</strong></h2>
<p>client-go's Clientset maintains an internal HTTP connection pool and rate limiter. Creating a new one on every call throws away the connection pool and can trigger API server rate limits. Always create the Clientset once at startup and reuse it:</p>
<pre><code class="language-go">// WRONG: new Clientset every call, no connection reuse
func listPods() {
    clientset, _ := kubernetes.NewForConfig(config)
    clientset.CoreV1().Pods("").List(...)
}

// RIGHT: Clientset created once, reused everywhere
var clientset kubernetes.Interface

func init() {
    clientset, _ = kubernetes.NewForConfig(config)
}

func listPods() {
    clientset.CoreV1().Pods("").List(...)
}
</code></pre>
<h2>API version mismatches, always pin all three packages together</h2>
<p>All three packages, <code>k8s.io/api</code>, <code>k8s.io/apimachinery</code>, and <code>k8s.io/client-go</code>, must be on the same minor version. They are developed and released together as part of each Kubernetes release cycle. Mixing versions causes compile errors because types from one package won't match types expected by another.</p>
<p>The version number maps directly to your Kubernetes cluster: <code>v0.36.2</code> = Kubernetes <code>v1.36.2</code>. Since we're running Kubernetes 1.36.2 in minikube, <code>v0.36.2</code> is the right choice throughout this series:</p>
<pre><code class="language-shell"># WRONG: mixing minor versions causes type mismatch errors at compile time
go get k8s.io/client-go@v0.36.2
go get k8s.io/api@v0.35.0          # different minor version — will break
go get k8s.io/apimachinery@v0.34.0  # different minor version — will break

# RIGHT: all three pinned to match Kubernetes 1.36.2
go get k8s.io/client-go@v0.36.2
go get k8s.io/api@v0.36.2
go get k8s.io/apimachinery@v0.36.2
go mod tidy
</code></pre>
<p>Always verify your cluster version before pinning:</p>
<pre><code class="language-shell">kubectl version 

# Client Version: v1.36.2
# Server Version: v1.36.2
</code></pre>
<blockquote>
<p><strong>If your client and server versions differ</strong>, for example <code>Client Version: v1.36.2</code> and <code>Server Version: v1.35.1</code>, that's completely fine. Kubernetes has an official version skew policy: <code>kubectl</code> can be up to one minor version ahead or behind the server. Pin your client-go packages to match whichever version you're running in the cluster.</p>
</blockquote>
<hr />
<h1>Summary</h1>
<p>client-go is the foundation everything in the Kubernetes Go ecosystem is built on. Four packages, one Clientset, typed access to every resource the API server exposes.</p>
<p>Three things to take away:</p>
<ul>
<li><p>The Clientset pattern: <code>clientset.APIGroup().Resource(namespace).Operation()</code>, is consistent across every resource type. Learn it once, read any client-go code.</p>
</li>
<li><p>Always check container states, not just pod phase, a "Running" pod can have failing containers.</p>
</li>
<li><p>Wrap the Clientset behind an interface from the start, it costs nothing and makes every function that uses it instantly testable.</p>
</li>
</ul>
<h2>What's next</h2>
<p>The health reporter we built here is a real tool. Run it on any cluster, and it gives you immediate operational value. It's also the direct foundation for a new tool we are going to build in the later chapter:<code>ferctl top</code>: a full CLI with Cobra, flags, tabwriter output, and near-limit warnings. The health reporter becomes a subcommand. The <code>KubeClient</code> interface gets extended with metrics.</p>
<p>Every pattern, every import, and every interface in this post appears in the next post.</p>
<hr />
<h2><strong>Let's connect!</strong></h2>
<p>One of the best parts of writing in public is the people you meet along the way, engineers at different stages of their journey, working on similar problems from completely different angles.</p>
<p>If something in this post resonated, if you spotted a bug, or if you just want to talk Go, Kubernetes, Platform Engineering, DevOps, or whatever, I'm always happy to hear from you.</p>
<ul>
<li><p><a href="https://www.linkedin.com/in/ferrios/"><strong>LinkedIn</strong></a></p>
</li>
<li><p><a href="https://github.com/FerRiosCosta"><strong>GitHub</strong></a></p>
</li>
<li><p><a href="https://x.com/ferztyle"><strong>Twitter / X</strong></a></p>
</li>
</ul>
<p><em>Building from Asunción, Paraguay 🇵🇾</em></p>
]]></content:encoded></item><item><title><![CDATA[Setting up a local Kubernetes cluster with minikube]]></title><description><![CDATA[Get a real Kubernetes cluster running on your laptop in under 5 minutes. Install minikube, enable metrics-server, and deploy a Go app.]]></description><link>https://ferztyle.me/setting-up-a-local-kubernetes-cluster-with-minikube</link><guid isPermaLink="true">https://ferztyle.me/setting-up-a-local-kubernetes-cluster-with-minikube</guid><category><![CDATA[Kubernetes]]></category><category><![CDATA[Devops]]></category><category><![CDATA[SRE]]></category><category><![CDATA[Platform Engineering ]]></category><dc:creator><![CDATA[Fer]]></dc:creator><pubDate>Mon, 06 Jul 2026 14:45:32 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/61db385c3ce4b2377adfdcda/e2187910-6641-4add-9268-c16ad21ab1d8.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p><em>This is part of the</em> <em><strong>Platform Engineering with Go</strong></em> <em>series.</em> <a href="https://ferztyle.me/series/platform-engineering-with-go"><em>View all posts in the series</em></a></p>
<hr />
<h1>Every post in this series assumes you have a Kubernetes cluster</h1>
<p>And that's a problem, because most engineers don't have one sitting around they can freely experiment on. Spinning up an EKS cluster just to follow a tutorial costs money, requires an AWS account, and takes longer than you want. Using your production cluster is obviously off the table.</p>
<p>minikube fixes this. It gives you a real, full Kubernetes cluster running on your laptop in under 5 minutes. Same API as production. Free. No cloud account needed. When you're done for the day, you stop it. When things get messy, you delete it and start fresh.</p>
<p>By the end of this post you'll have a local cluster running with metrics-server enabled and a Go app deployed inside it.</p>
<hr />
<h1>What you'll learn</h1>
<ul>
<li><p>What minikube is and how it relates to a real production cluster</p>
</li>
<li><p>How to install minikube on Mac and Linux</p>
</li>
<li><p>How to start, stop, and manage a local cluster</p>
</li>
<li><p>How minikube connects to kubectl and your kubeconfig</p>
</li>
<li><p>How to enable the metrics-server addon</p>
</li>
<li><p>How to deploy a real Go app to your local cluster</p>
</li>
</ul>
<hr />
<h1>Prerequisites</h1>
<ul>
<li><p>Mac or Linux, this post does not cover Windows</p>
</li>
<li><p>Docker installed and running, minikube uses it as the default driver</p>
</li>
</ul>
<p>We'll install kubectl as part of this post, so you don't need it yet.</p>
<hr />
<h1>What minikube actually is</h1>
<p>Before installing anything, it's worth understanding what minikube does, and what it doesn't do.</p>
<p>minikube runs a single-node Kubernetes cluster locally, inside a Docker container (or VM) on your machine. That cluster runs the exact same Kubernetes API as the production clusters you'd find on EKS, GKE, or AKS. The same <code>kubectl</code> commands work. The same YAML manifests work. The same Go code works, which is exactly why it's the right tool for this series.</p>
<p>What minikube is not: a production cluster. It's a single node with no high availability, no cloud integrations, and no autoscaling. It's a development and learning environment, not something you'd run workloads on.</p>
<h2>How it compares to alternatives</h2>
<p>There are several tools for running Kubernetes locally. Here's how they compare so you understand why we're using minikube:</p>
<table>
<thead>
<tr>
<th>Tool</th>
<th>Best for</th>
<th>Why we chose minikube</th>
</tr>
</thead>
<tbody><tr>
<td>minikube</td>
<td>Learning and development</td>
<td>Addons system, excellent docs, most widely used</td>
</tr>
<tr>
<td>kind</td>
<td>CI pipelines</td>
<td>Lighter than minikube, less convenient for local dev</td>
</tr>
<tr>
<td>k3s</td>
<td>Lightweight production</td>
<td>More complex to set up locally</td>
</tr>
<tr>
<td>Docker Desktop K8s</td>
<td>Quick start</td>
<td>Heavier, less control over the cluster</td>
</tr>
</tbody></table>
<p>The addons system is the main reason we use minikube here. Enabling metrics-server is a single command with minikube. Other tools require manual installation and configuration.</p>
<hr />
<h1>Installing minikube</h1>
<h2>Mac</h2>
<pre><code class="language-shell"># Install minikube via Homebrew
brew install minikube

# Verify the install
minikube version
# minikube version: v1.38.1
</code></pre>
<h2>Linux</h2>
<pre><code class="language-shell"># Download the minikube binary
curl -LO https://storage.googleapis.com/minikube/releases/latest/minikube-linux-amd64

# Make it executable and move it to your PATH
chmod +x minikube-linux-amd64
sudo mv minikube-linux-amd64 /usr/local/bin/minikube

# Verify the install
minikube version
# minikube version: v1.32.0
</code></pre>
<hr />
<h1>Installing kubectl</h1>
<p>kubectl is the command-line tool for interacting with Kubernetes clusters. minikube configures it automatically, but you need to install it separately.</p>
<h2>Mac</h2>
<pre><code class="language-shell">brew install kubectl

# Verify
kubectl version --client
# Client Version: v1.36.2
</code></pre>
<h2>Linux</h2>
<pre><code class="language-shell"># Download the latest stable kubectl binary
curl -LO "https://dl.k8s.io/release/$(curl -L -s https://dl.k8s.io/release/stable.txt)/bin/linux/amd64/kubectl"

# Make it executable and move to PATH
chmod +x kubectl
sudo mv kubectl /usr/local/bin/kubectl

# Verify
kubectl version --client
# Client Version: v1.29.0
</code></pre>
<hr />
<h1>Starting your first cluster</h1>
<p>With minikube and kubectl installed, starting a cluster is one command:</p>
<pre><code class="language-shell">minikube start
</code></pre>
<p>You'll see output like this as minikube works through the startup sequence:</p>
<pre><code class="language-plaintext">😄  minikube v1.38.1 on Darwin 26.5.1 (arm64)
✨  Automatically selected the docker driver
❗  Starting v1.39.0, minikube will default to "containerd" container runtime. See #21973 for more info.
📌  Using Docker Desktop driver with root privileges
👍  Starting "minikube" primary control-plane node in "minikube" cluster
🚜  Pulling base image v0.0.50 ...
🔥  Creating docker container (CPUs=2, Memory=8100MB) ...
🐳  Preparing Kubernetes v1.35.1 on Docker 29.2.1 ...
🔗  Configuring bridge CNI (Container Networking Interface) ...
🔎  Verifying Kubernetes components...
    ▪ Using image gcr.io/k8s-minikube/storage-provisioner:v5
🌟  Enabled addons: storage-provisioner, default-storageclass
🏄  Done! kubectl is now configured to use "minikube" cluster and "default" namespace by default
</code></pre>
<p>What happened in those few seconds:</p>
<ul>
<li><p>minikube pulled a Docker image containing a full Kubernetes cluster.</p>
</li>
<li><p>It started a Docker container running that image.</p>
</li>
<li><p>It generated TLS certificates for the API server.</p>
</li>
<li><p>It configured kubectl to talk to this new cluster by writing a new context to <code>~/.kube/config</code></p>
</li>
</ul>
<h2>Configuring resources</h2>
<p>The default CPUs and memory are sometimes not enough, especially once you have several pods running. We recommend starting with a bit more:</p>
<pre><code class="language-shell"># Delete any existing cluster first, then start with more resources
minikube delete
minikube start --cpus=4 --memory=4096
</code></pre>
<h2>Pinning the Kubernetes version</h2>
<p>If you want to match your production cluster's Kubernetes version exactly, (I'm not going to run this; I want the last version 1.35.1):</p>
<pre><code class="language-shell">minikube start --kubernetes-version=v1.28.3
</code></pre>
<h2>Verifying the cluster is running</h2>
<pre><code class="language-shell"># Check the node is Ready
kubectl get nodes

# NAME       STATUS   ROLES           AGE     VERSION
# minikube   Ready    control-plane   4m59s   v1.35.1

# Check the system pods are all running
kubectl get pods -A

# NAMESPACE     NAME                               READY   STATUS    RESTARTS        AGE
# kube-system   coredns-7d764666f9-pzqlt           1/1     Running   0               5m33s
# kube-system   etcd-minikube                      1/1     Running   0               5m39s
# kube-system   kube-apiserver-minikube            1/1     Running   0               5m39s
# kube-system   kube-controller-manager-minikube   1/1     Running   0               5m39s
# kube-system   kube-proxy-2l7h5                   1/1     Running   0               5m33s
# kube-system   kube-scheduler-minikube            1/1     Running   0               5m39s
# kube-system   storage-provisioner                1/1     Running   1 (5m32s ago)   5m38s
</code></pre>
<p>If all pods show <code>Running</code>, your cluster is healthy.</p>
<p>You can also see the docker container running on behalf our minikube cluster</p>
<pre><code class="language-shell">docker ps -a                                                                                                                                                     
# CONTAINER ID   IMAGE                                 COMMAND                  CREATED          STATUS          PORTS                                                                                                                                  NAMES
# de39b5440365   gcr.io/k8s-minikube/kicbase:v0.0.50   "/usr/local/bin/entr…"   10 minutes ago   Up 10 minutes   127.0.0.1:60921-&gt;22/tcp, 127.0.0.1:60923-&gt;2376/tcp, 127.0.0.1:60922-&gt;5000/tcp, 127.0.0.1:60925-&gt;8443/tcp, 127.0.0.1:60924-&gt;32443/tcp   minikube
</code></pre>
<hr />
<h2>Managing your cluster</h2>
<p>You'll use these commands constantly throughout the series:</p>
<pre><code class="language-shell"># Pause the cluster — preserves all state, frees up resources
minikube stop

# Resume where you left off
minikube start

# Delete everything and start completely fresh
# Use this when things get into a bad state
minikube delete

# Check what's currently running
minikube status

# Open the Kubernetes dashboard in your browser
# Useful for getting a visual overview of your cluster
minikube dashboard

# SSH into the minikube node
# Useful for low-level debugging
minikube ssh
</code></pre>
<p>A practical workflow: <code>minikube stop</code> at the end of every session, <code>minikube start</code> when you come back. <code>minikube delete &amp;&amp; minikube start</code> When something is broken, and you want a clean slate.</p>
<hr />
<h1>What is metrics-server?</h1>
<p>Before we enable it, it's worth understanding what metrics-server actually is and where it fits in the Kubernetes ecosystem.</p>
<p>metrics-server is a lightweight, in-memory component that runs inside your Kubernetes cluster and collects resource usage data, including CPU and memory, from every node and pod. It does this by talking to the kubelet (the agent that runs on each node) and scraping the resource stats it exposes.</p>
<pre><code class="language-plaintext">┌─────────────────────────────────────────┐
│           Kubernetes cluster            │
│                                         │
│  ┌──────────┐     scrapes    ┌────────┐ │
│  │  kubelet │ ◄────────────  │metrics │ │
│  │ (node 1) │               │ server │ │
│  └──────────┘               └───┬────┘ │
│                                 │      │
│  ┌──────────┐                   │ exposes
│  │  kubelet │ ◄─────────────────┘      │
│  │ (node 2) │      Metrics API         │
│  └──────────┘           ▲             │
│                          │             │
└──────────────────────────┼─────────────┘
                           │
              kubectl top / your Go code
</code></pre>
<p>The data metrics-server collects is exposed through the <strong>Metrics API</strong>, a standard Kubernetes API endpoint that both <code>kubectl top</code> and, client-go can query. When you run <code>kubectl top pods</code>, kubectl is calling the Metrics API.</p>
<h2>What metrics-server is not</h2>
<p>It's worth being clear about what metrics-server doesn't do, because it's a common source of confusion:</p>
<ul>
<li><p>It does <strong>not</strong> store historical data. It only keeps the most recent sample in memory. If you want trends over time, you need Prometheus.</p>
</li>
<li><p>It does <strong>not</strong> replace Prometheus or Grafana. It's a lightweight source of current usage data, not a full monitoring stack.</p>
</li>
<li><p>It does <strong>not</strong> run by default on most clusters. On EKS, GKE, and AKS it's usually pre-installed, but on self-managed clusters, and on minikube, you have to enable it yourself.</p>
</li>
</ul>
<p>Think of it as the simplest possible answer to the question: "what is my cluster using right now?" For anything more sophisticated, alerting, historical analysis, dashboards, you'd reach for Prometheus.</p>
<hr />
<h1>Enabling metrics-server</h1>
<p>minikube has an add-ons system, a curated list of optional components you can enable with a single command. metrics-server is one of them:</p>
<pre><code class="language-shell"># Enable metrics-server
minikube addons enable metrics-server

# Verify it's running
kubectl get deployment metrics-server -n kube-system

# NAME             READY   UP-TO-DATE   AVAILABLE
# metrics-server   1/1     1            1
</code></pre>
<p>Wait about 60 seconds, then verify it's collecting data:</p>
<pre><code class="language-shell"># Check node resource usage
kubectl top nodes

# NAME       CPU(cores)   CPU%   MEMORY(bytes)   MEMORY%
# minikube   185m         4%     1042Mi          26%

# Check pod resource usage across all namespaces
kubectl top pods -A
</code></pre>
<p>If <code>kubectl top</code> returns <code>error: metrics not available yet</code>, just wait another 30 seconds and try again. metrics-server takes a moment to scrape its first round of data.</p>
<hr />
<h1>Deploying a real Go app to your local cluster</h1>
<p>An empty cluster is fine for testing connections, but what we actually want is a cluster with real pods running, pods we can query with the health reporter.</p>
<p>Let's deploy a simple Go HTTP server properly, built with a multi-stage Dockerfile, loaded into minikube, and deployed with real resource requests and limits.</p>
<h2>Why we use a Dockerfile</h2>
<p>You might wonder why we don't just use <code>go run</code> inside the container for simplicity. The answer ties directly back to post 1: resource management.</p>
<p><code>go run</code> compiles your code at container start, and the Go compiler needs over 1GB of memory just to compile a hello world app. That forces you to set absurdly high memory limits for a tiny service, which defeats the entire purpose of a post about resource management. It also causes OOMKill on any reasonable memory limit, and makes startup slow.</p>
<p>The right approach, and the one every real Go service uses, is to compile the binary at image build time. The running container only needs the binary, not the compiler. Memory usage drops from 1GB to under 20MB:</p>
<pre><code class="language-plaintext">go run approach:     limits.memory: 1024Mi  ← embarrassing for a hello world
Dockerfile approach: limits.memory: 128Mi    ← honest and production-realistic
</code></pre>
<h2>The project structure</h2>
<p>Create a new directory for this example:</p>
<pre><code class="language-shell">mkdir go-api &amp;&amp; cd go-api
</code></pre>
<p>Create three files:</p>
<pre><code class="language-plaintext">go-api/
├── main.go        ← the Go HTTP server
├── Dockerfile     ← multi-stage build
└── deployment.yaml ← Kubernetes manifests
</code></pre>
<h2>The application</h2>
<pre><code class="language-go">// main.go
package main

import (
    "fmt"
    "log/slog"
    "net/http"
    "os"
)

func main() {
    // Handle the root endpoint
    http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
        fmt.Fprintln(w, "hello from Go on Kubernetes!")
    })

    // Health endpoint — used by readiness and liveness probes.
    // Always returns 200 OK as long as the server is running.
    http.HandleFunc("/health", func(w http.ResponseWriter, r *http.Request) {
        w.WriteHeader(http.StatusOK)
    })

    port := os.Getenv("PORT")
    if port == "" {
        port = "8080"
    }

    slog.Info("server starting", "port", port)
    if err := http.ListenAndServe(":"+port, nil); err != nil {
        slog.Error("server failed", "error", err)
        os.Exit(1)
    }
}
</code></pre>
<h2>The Dockerfile</h2>
<p>This is a multi-stage build, one stage compiles the binary, a second minimal stage runs it. The final image contains only the binary and nothing else, no Go toolchain, no compiler, no source code:</p>
<pre><code class="language-shell"># Stage 1: builder
# Uses the full Go image to compile the binary.
# This stage is discarded after the build — it never ships.
FROM golang:1.26-alpine AS builder

WORKDIR /app

# Copy the source code
COPY main.go .

# Initialize a Go module — needed for go build
RUN go mod init github.com/yourname/go-api

# Build a statically linked binary.
# CGO_ENABLED=0 produces a fully static binary with no external dependencies.
# -ldflags="-s -w" strips debug symbols to reduce binary size.
RUN CGO_ENABLED=0 GOOS=linux go build -ldflags="-s -w" -o server .

# Stage 2: runtime
# Uses a minimal Alpine image — no Go toolchain, no compiler.
# The final image is typically under 10MB.
FROM alpine:3.24

# Run as a non-root user — a basic security best practice.
RUN addgroup -S app &amp;&amp; adduser -S app -G app
USER app

WORKDIR /app

# Copy only the compiled binary from the builder stage.
COPY --from=builder /app/server .

EXPOSE 8080

CMD ["./server"]
</code></pre>
<h2>Build the image and load it into minikube</h2>
<p>minikube runs its own Docker daemon, separate from your laptop's Docker. To use a locally built image in minikube, you need to build it inside minikube's Docker environment:</p>
<pre><code class="language-shell"># Point your terminal's Docker CLI at minikube's Docker daemon
eval $(minikube docker-env)

# Build the image — this builds directly inside minikube
docker build -t go-api:latest .

# Verify the image is available inside minikube
docker images | grep go-api
# go-api   latest   a1b2c3d4e5f6   10 seconds ago   14.3MB
</code></pre>
<p>Notice the image size, 14.3MB. Compare that to the <code>golang:1.26-alpine</code> base image which is ~300MB. <strong>Multi-stage builds make a real difference.</strong></p>
<p>When you're done working and want to restore your terminal's Docker CLI to your laptop's Docker:</p>
<pre><code class="language-shell">eval $(minikube docker-env -u)
</code></pre>
<h2>The deployment manifest</h2>
<pre><code class="language-yaml"># deployment.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
  name: go-api
  namespace: default
  labels:
    app: go-api
spec:
  replicas: 3
  selector:
    matchLabels:
      app: go-api
  template:
    metadata:
      labels:
        app: go-api
    spec:
      containers:
      - name: server
        image: go-api:latest

        # imagePullPolicy: Never tells Kubernetes to use the local image
        # and never try to pull it from a registry.
        # Required when using images built inside minikube's Docker daemon.
        imagePullPolicy: Never

        ports:
        - containerPort: 8080

        # Resource requests and limits — from post 1.
        # These are now realistic for a pre-compiled Go binary.
        # A running Go binary uses ~10-20Mi — we give it 64Mi to be safe.
        resources:
          requests:
            cpu: "50m"
            memory: "32Mi"
          limits:
            cpu: "100m"
            memory: "64Mi"

        # Readiness probe — Kubernetes only sends traffic once this passes.
        # initialDelaySeconds is short because a pre-compiled binary
        # starts in milliseconds — no compilation step.
        readinessProbe:
          httpGet:
            path: /health
            port: 8080
          initialDelaySeconds: 5
          periodSeconds: 5

        # Liveness probe — Kubernetes restarts the container if this fails.
        # Always set higher than readinessProbe.initialDelaySeconds.
        livenessProbe:
          httpGet:
            path: /health
            port: 8080
          initialDelaySeconds: 10
          periodSeconds: 10
---
apiVersion: v1
kind: Service
metadata:
  name: go-api
  namespace: default
spec:
  # ClusterIP is the default service type.
  # It gives the service a stable internal IP address only reachable
  # from inside the cluster. This is correct for internal services —
  # we access it locally using kubectl port-forward, not via a public IP.
  type: ClusterIP
  selector:
    app: go-api
  ports:
  - port: 80
    targetPort: 8080
</code></pre>
<h2>Deploy it</h2>
<pre><code class="language-shell"># Apply both the Deployment and Service
kubectl apply -f deployment.yaml

# Watch the pods come up — should be fast since the binary starts instantly
kubectl get pods -w

# NAME                      READY   STATUS    RESTARTS   AGE
# go-api-7d6b9f8c4-xk2pq   1/1     Running   0          8s
# go-api-7d6b9f8c4-mn9rt   1/1     Running   0          8s
# go-api-7d6b9f8c4-p8wvz   1/1     Running   0          9s
</code></pre>
<p>No <code>ContainerCreating</code> delays. No OOMKill. The binary starts in milliseconds.</p>
<h2>Verify it's working</h2>
<pre><code class="language-shell"># Check resource usage — these are the honest numbers for a Go binary
kubectl top pods

# NAME                      CPU(cores)   MEMORY(bytes)
# go-api-7d6b9f8c4-xk2pq   2m           11Mi
# go-api-7d6b9f8c4-mn9rt   2m           10Mi
# go-api-7d6b9f8c4-p8wvz   2m           11Mi
</code></pre>
<p>To hit the service from your terminal, use <code>kubectl port-forward</code>, it works the same way on both Mac and Linux regardless of which minikube driver you're using:</p>
<pre><code class="language-shell"># Forward local port 8080 to the go-api service
# Keep this running in one terminal
kubectl port-forward service/go-api 8080:80

# Forwarding from 127.0.0.1:8080 -&gt; 8080
# Forwarding from [::1]:8080 -&gt; 8080
</code></pre>
<p>In a second terminal:</p>
<pre><code class="language-shell">curl http://localhost:8080
# hello from Go on Kubernetes!
</code></pre>
<p>You should see <code>hello from Go on Kubernetes!</code>, confirming the service is running and routing traffic to your pods correctly. You now have three running pods with real, honest resource usage data available from metrics-server.</p>
<hr />
<h1>How Go connects to this cluster</h1>
<p>This section previews what happens in the next post, so that when you see the first line of Go code, it already makes sense.</p>
<p>When <code>minikube start</code> ran, it wrote a new entry to your <code>~/.kube/config</code> file. Here's the relevant section it added:</p>
<pre><code class="language-yaml"># ~/.kube/config (relevant section)
contexts:
- context:
    cluster: minikube
    namespace: default
    user: minikube
  name: minikube       # ← the context name

current-context: minikube  # ← currently active context
</code></pre>
<p>This is the same file kubectl reads when you run any <code>kubectl</code> command. It's also the file our Go code will read using <code>BuildConfigFromFlags</code>:</p>
<pre><code class="language-go">// This is how our Go program will connect to minikube
// in the next post — reads the same ~/.kube/config file
config, err := clientcmd.BuildConfigFromFlags("", os.Getenv("HOME")+"/.kube/config")
</code></pre>
<p>No extra setup. No credentials to manage. The Go program connects to exactly the same cluster kubectl connects to, because both read the same kubeconfig.</p>
<h2>Verifying the context before running Go code</h2>
<p>Before running any Go code that talks to Kubernetes, always verify which cluster you're pointing at:</p>
<pre><code class="language-shell"># Which context is currently active?
kubectl config current-context
# minikube

# List all available contexts (useful if you have multiple clusters)
kubectl config get-contexts

# CURRENT   NAME       CLUSTER    AUTHINFO   NAMESPACE
# *         minikube   minikube   minikube   default
#           prod-eks   eks-prod   aws-user   production
</code></pre>
<p>The <code>*</code> marks the active context. If you ever accidentally point at a production cluster while running your Go code, the <code>get-contexts</code> output makes it obvious.</p>
<p>To switch between contexts:</p>
<pre><code class="language-shell"># Switch to a different context
kubectl config use-context prod-eks

# Switch back to minikube
kubectl config use-context minikube
</code></pre>
<hr />
<h1>Common gotchas</h1>
<h2><strong>minikube service tunnel on Mac with Docker driver</strong></h2>
<p>On Mac, minikube runs inside a Docker container with its own internal network. Running <code>minikube service go-api --url</code> creates a temporary tunnel and warns:</p>
<pre><code class="language-plaintext">Services [default/go-api] have type "ClusterIP" not meant to be exposed,
however for local development minikube allows you to access this!
❗  Because you are using a Docker driver on darwin, the terminal needs to be open to run it.
</code></pre>
<p>This isn't an error, but the tunnel only works while that terminal stays open. Use <code>kubectl port-forward</code> instead, it's more portable, works the same on Mac and Linux, and doesn't need a dedicated terminal window.</p>
<h2><strong>Docker not running</strong></h2>
<p>minikube uses Docker as its default driver. If Docker isn't running when you call <code>minikube start</code>, you'll see:</p>
<pre><code class="language-plaintext">X Exiting due to PROVIDER_DOCKER_NOT_RUNNING: Docker Desktop is not running
</code></pre>
<p>Start Docker first, then retry <code>minikube start</code>.</p>
<h2><strong>Not enough resources: pods stuck in Pending</strong></h2>
<p>If your pods stay in <code>Pending</code> state, the most common cause is insufficient resources. Check with:</p>
<pre><code class="language-shell">kubectl describe pod &lt;pod-name&gt; | grep -A5 Events
# Warning  FailedScheduling  Insufficient memory
</code></pre>
<p>Fix it by giving minikube more resources:</p>
<pre><code class="language-shell">minikube delete
minikube start --cpus=4 --memory=8192
</code></pre>
<h2><strong>minikube IP changes on restart</strong></h2>
<p>Every time you <code>minikube delete &amp;&amp; minikube start</code>, minikube may get a different IP address for the API server. If you ever hardcode the API server URL anywhere in your Go code, it will break after a restart. Always use <code>BuildConfigFromFlags</code> with the kubeconfig path, it reads the current IP dynamically from the config file.</p>
<hr />
<h1>Summary</h1>
<p>You now have everything you need to follow the rest of this series:</p>
<ul>
<li><p>A local Kubernetes cluster running minikube</p>
</li>
<li><p>metrics-server enabled and collecting data</p>
</li>
<li><p>A Go app deployed with 3 replicas and proper resource configuration</p>
</li>
<li><p>kubectl configured and pointing at your local cluster</p>
</li>
</ul>
<p>Three things to remember as you work through the series:</p>
<ul>
<li><p><code>minikube stop</code> at the end of every session, don't leave it consuming resources in the background</p>
</li>
<li><p><code>minikube delete</code> when things get into a broken state, a clean cluster takes less than 2 minutes to rebuild</p>
</li>
<li><p><code>kubectl config current-context</code> before running any Go code, always know which cluster you're talking to</p>
</li>
</ul>
<hr />
<h2>What's next</h2>
<p>In the next post we write our first Go program that connects to this cluster using client-go, the official Kubernetes Go client. We'll query the pods we just deployed, detect failing ones, and build something immediately useful: a cluster health reporter that gives you a full picture of your cluster's state in a single command.</p>
<hr />
<h2><strong>Let's connect!</strong></h2>
<p>One of the best parts of writing in public is the people you meet along the way, engineers at different stages of their journey, working on similar problems from completely different angles.</p>
<p>If something in this post resonated, if you spotted a bug, or if you just want to talk Go, Kubernetes, Platform Engineering, DevOps, or whatever, I'm always happy to hear from you.</p>
<ul>
<li><p><a href="https://www.linkedin.com/in/ferrios/"><strong>LinkedIn</strong></a></p>
</li>
<li><p><a href="https://github.com/FerRiosCosta"><strong>GitHub</strong></a></p>
</li>
<li><p><a href="https://x.com/ferztyle"><strong>Twitter / X</strong></a></p>
</li>
</ul>
<p><em>Building from Asunción, Paraguay 🇵🇾</em></p>
]]></content:encoded></item><item><title><![CDATA[Kubernetes resource requests and limits explained: scheduling, throttling, and OOMKill]]></title><description><![CDATA[How Kubernetes requests and limits actually work: how the scheduler uses them, what causes CPU throttling and OOMKill, how to set them for production.]]></description><link>https://ferztyle.me/kubernetes-resource-requests-and-limits-explained-scheduling-throttling-and-oomkill</link><guid isPermaLink="true">https://ferztyle.me/kubernetes-resource-requests-and-limits-explained-scheduling-throttling-and-oomkill</guid><category><![CDATA[Devops]]></category><category><![CDATA[Kubernetes]]></category><category><![CDATA[SRE]]></category><category><![CDATA[k8s]]></category><category><![CDATA[Platform Engineering ]]></category><dc:creator><![CDATA[Fer]]></dc:creator><pubDate>Thu, 02 Jul 2026 01:03:07 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/61db385c3ce4b2377adfdcda/87d7a06d-3f30-4a14-95fa-d7d40643c912.jpg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p><em>This is part of the</em> <em><strong>Platform engineering with Go</strong></em> <em>series: a growing collection of posts on Kubernetes, Go tooling, and infrastructure automation.</em> <a href="https://ferztyle.me/series/platform-engineering-with-go"><em>View all posts in the series</em></a></p>
<hr />
<h1>The 3am incident nobody talks about</h1>
<p>It's 3am. Your on-call phone goes off. A service is down in production. You log in, check the pods, and see this:</p>
<pre><code class="language-bash">kubectl get pods -n production

NAME                    READY   STATUS             RESTARTS   AGE
api-7d6b9f8c4-xk2pq    0/1     OOMKilled          14         2d
api-7d6b9f8c4-mn9rt    0/1     OOMKilled          14         2d
api-7d6b9f8c4-p8wvz    0/1     OOMKilled          14         2d
</code></pre>
<p>You restart the pods. They come back. Five minutes later, they die again.</p>
<p>The problem could be several things: limits set too low for the actual workload, no limits set at all so the pod consumed memory freely until the node ran out, a traffic spike the pod wasn't provisioned for, or yes, a memory leak in the application itself. In all cases, the result is the same: memory consumption exceeded the allowed ceiling, the OOM killer fired, the pod died, and Kubernetes restarted it into the same situation. Fourteen times.</p>
<p>This is one of the most common production incidents in Kubernetes, and one of the most preventable. But preventing it requires understanding what requests and limits actually do, what happens when memory consumption exceeds them, and how to configure them correctly for your actual workload.</p>
<p>That's what this post is about.</p>
<hr />
<blockquote>
<p>No Go knowledge required: this post has zero code</p>
</blockquote>
<hr />
<h1>Requests vs limits, two completely different things</h1>
<p>Before anything else, the most important concept to internalize: requests and limits are not two versions of the same thing. They serve entirely different purposes and are enforced by entirely different components of Kubernetes.</p>
<pre><code class="language-yaml"># A pod spec with both requests and limits set
resources:
  requests:
    cpu: "250m"     # 250 millicores = 0.25 CPU cores
    memory: "256Mi" # 256 mebibytes
  limits:
    cpu: "500m"     # 500 millicores = 0.5 CPU cores
    memory: "512Mi" # 512 mebibytes
</code></pre>
<p>Here's what each one actually does:</p>
<p><strong>Requests</strong> are a promise to the scheduler. When you set <code>requests.memory: 256Mi</code>, you're telling Kubernetes: "I need at least 256Mi of memory reserved for this pod on whatever node it runs on.. The scheduler uses this value to decide which node to place the pod on. Once scheduled, that 256Mi is considered reserved on that node, even if the pod is only using 50Mi at the moment.</p>
<p><strong>Limits</strong> are a ceiling enforced by the runtime. When you set <code>limits.memory: 512Mi</code>, you're telling Kubernetes: "This pod is never allowed to use more than 512Mi of memory." If it tries to exceed that ceiling, the kernel kills it. No warning. No graceful shutdown. Just gone.</p>
<p><strong>The key insight:</strong> requests affect scheduling; limits affect runtime behavior. They are read by different components at different times for entirely different reasons.</p>
<hr />
<h1>How the scheduler uses requests to place pods</h1>
<p>The Kubernetes scheduler's job is to find a node for each new pod. It does this by looking at each node's allocatable resources and comparing them against the sum of all pod requests already scheduled there.</p>
<p>A node's allocatable resources are not the same as its total capacity. Some resources are always reserved for the operating system and Kubernetes system components:</p>
<pre><code class="language-bash">kubectl describe node my-node

# Look for the Allocatable section:
Allocatable:
  cpu:     3800m   # 3.8 cores available to pods (out of 4 total)
  memory:  7Gi     # 7Gi available to pods (out of 8Gi total)
</code></pre>
<p>The scheduler adds up the requests of all pods already on a node and compares that sum against the allocatable resources. If the remaining capacity is less than the new pod's request, the node is skipped.</p>
<p>Here's the critical subtlety: <strong>the scheduler cares about requests, not actual usage.</strong></p>
<pre><code class="language-plaintext">Node: 4 CPU allocatable

Pod A: requests 1 CPU → actual usage: 0.2 CPU
Pod B: requests 1 CPU → actual usage: 0.1 CPU
Pod C: requests 1 CPU → actual usage: 0.8 CPU

From the scheduler's perspective: 3 out of 4 CPU are "used"
From the kernel's perspective: only 1.1 CPU are actually being consumed

New pod requesting 1.5 CPU → scheduler says NO (only 1 CPU remaining)
</code></pre>
<p>This creates an important tension: if your requests are set too high relative to actual usage, your nodes look full when they're actually mostly idle, and new pods can't be scheduled. This is called poor bin packing, and it wastes money.</p>
<p>On the other hand, if your requests are too low, too many pods get scheduled onto the same node. When they all start consuming resources simultaneously, the node becomes overloaded, and Kubernetes starts evicting pods to relieve the pressure.</p>
<p>Getting requests right is a balancing act between cost efficiency and stability.</p>
<hr />
<h1>CPU limits and throttling: the silent killer</h1>
<p>CPU is what Kubernetes calls a compressible resource. If a pod tries to use more CPU than its limit allows, the Linux kernel doesn't kill it, it throttles it. The pod keeps running, but it gets fewer CPU cycles, so everything it does takes longer.</p>
<p>The throttling mechanism is the <a href="https://docs.kernel.org/scheduler/sched-design-CFS.html">Linux CFS</a> (Completely Fair Scheduler).</p>
<h2>Understanding CPU cycles and scheduling periods</h2>
<p>Before we talk about how throttling works, it helps to understand two concepts that are invisible in day-to-day operations but fundamental to what's happening under the hood.</p>
<h3>What is a CPU cycle?</h3>
<p>Your server's CPU is constantly doing work, executing instructions, processing data, running code. A <strong>CPU cycle</strong> is the smallest unit of that work. A modern CPU completes billions of cycles per second (gigahertz, that's what the "3.2GHz" on a server spec means: 3.2 billion cycles per second).</p>
<p>Think of CPU cycles like minutes of attention from a very fast worker. Your pod's processes need a certain number of those "minutes" to do their job, handle a request, run a query, process a message. The more cycles your pod gets, the faster it runs. The fewer it gets, the slower it runs.</p>
<p>When Kubernetes talks about CPU in millicores (<code>250m</code>, <code>500m</code>, <code>1000m</code>), it's describing what fraction of one CPU core's cycles your pod gets access to:</p>
<pre><code class="language-plaintext">1000m = 1 full CPU core = 100% of one core's cycles
 500m = 0.5 CPU core   = 50% of one core's cycles
 250m = 0.25 CPU core  = 25% of one core's cycles
</code></pre>
<h3>What is a scheduling period?</h3>
<p>A CPU doesn't serve one process at a time from start to finish. It slices time into tiny windows and gives each process a turn. This is called <strong>time-sharing</strong>, and the windows are called <strong>scheduling periods</strong>.</p>
<p>Think of it like a teacher in a classroom. Instead of helping one student for the entire class, the teacher spends 5 minutes with each student in rotation. Every student gets attention, but no single student monopolizes the teacher's time.</p>
<p>The Linux CFS uses scheduling periods of <strong>100 milliseconds</strong> by default. In every 100ms window, the CPU divides its time among all the processes competing for it.</p>
<pre><code class="language-plaintext">100ms scheduling period
│
├── 0ms  - 25ms  → Pod A gets its turn  (250m limit = 25% of 100ms = 25ms)
├── 25ms - 75ms  → Pod B gets its turn  (500m limit = 50% of 100ms = 50ms)
├── 75ms - 100ms → Pod C gets its turn  (250m limit = 25% of 100ms = 25ms)
│
└── (next 100ms period starts)
</code></pre>
<p>Each pod's CPU limit determines how many milliseconds of that 100ms window it's allowed to use:</p>
<pre><code class="language-plaintext">CPU limit of 250m → 25ms of CPU time per 100ms period
CPU limit of 500m → 50ms of CPU time per 100ms period
CPU limit of 1000m (1 full core) → 100ms of CPU time per 100ms period
</code></pre>
<h3>What happens when a pod hits its limit mid-period?</h3>
<p>Here's where throttling kicks in. If a pod uses up its entire allocation before the 100ms period ends, the CFS puts it in a <strong>throttled</strong> state for the rest of that period; it gets zero CPU cycles until the next period starts, regardless of whether other pods are idle.</p>
<pre><code class="language-plaintext">Pod with 250m CPU limit → 25ms of allowed CPU time per 100ms period

Period 1 (0ms to 100ms):
  ├── 0ms:  Pod starts processing a request
  ├── 25ms: Pod has used its full 25ms allocation ← throttled here
  ├── 25ms to 100ms: Pod sits idle, gets zero CPU cycles
  └── 100ms: New period starts, pod gets another 25ms

What the user experiences:
  ├── Request arrives at 0ms
  ├── Pod processes half the request, then waits 75ms doing nothing
  └── Response arrives much later than it should
</code></pre>
<p>The pod didn't crash. It didn't log an error. It just stopped making progress for 75ms out of every 100ms, which is why a throttled service feels sluggish rather than broken. Everything works, just much slower than it should.</p>
<h3>A concrete analogy</h3>
<p>Imagine you're writing a report and your manager says you can only use the shared laptop for 15 minutes every hour. You start writing, but at the 15-minute mark your access is cut off, even if you're mid-sentence. You sit and wait for the next hour to start before you can type another word.</p>
<p>That's exactly what the CFS does to a throttled pod. It doesn't care that you were in the middle of something important. When the quota is up, the process waits, and whatever request it was handling has to wait too.</p>
<h3>Why this is hard to detect</h3>
<p>The reason CPU throttling causes so much confusion is that it's invisible in all the usual places:</p>
<pre><code class="language-shell"># This shows current usage — looks fine
kubectl top pods -n production
NAME                 CPU(cores)   MEMORY(bytes)
api-6d8f9b7c-xk2pq   240m         180Mi

# But the pod might be throttled 80% of the time
# kubectl top shows average usage, not whether that usage caused throttling
</code></pre>
<p>A pod using 240m CPU on average can still be heavily throttled if it regularly bursts above its limit within a single 100ms period. The average looks healthy; the latency tells a different story.</p>
<p>So, this is why this is dangerous: <strong>CPU throttling is completely silent.</strong></p>
<p>There's no error. No log line. No Kubernetes event. Your pod just slows down. Requests take longer. Latency increases. Users notice something is wrong, but nothing in your logs explains why.</p>
<p>The only reliable way to detect throttling is through the <code>container_cpu_cfs_throttled_periods_total</code> metric in Prometheus, which counts how many scheduling periods a container was throttled in. If that number is climbing, throttling is happening regardless of what <code>kubectl top</code> shows.</p>
<p>To detect throttling, you can use the Kubernetes metrics server:</p>
<pre><code class="language-shell"># See current CPU usage vs requests
kubectl top pods -n production

NAME                    CPU(cores)   MEMORY(bytes)
api-7d6b9f8c4-xk2pq    480m         210Mi
api-7d6b9f8c4-mn9rt    498m         198Mi
</code></pre>
<blockquote>
<p>If you see pods consistently near their CPU limit, throttling is likely happening, especially if you're seeing latency spikes that don't correlate with error rates.</p>
</blockquote>
<h3>The CPU limits controversy</h3>
<p>There's an ongoing debate in the Kubernetes community about CPU limits. Some platform teams remove CPU limits entirely for latency-sensitive services, allowing pods to burst freely as long as there's spare capacity on the node.</p>
<p><strong>The argument for removing CPU limits:</strong></p>
<ul>
<li><p>Eliminates throttling completely.</p>
</li>
<li><p>Workloads use spare node capacity efficiently.</p>
</li>
<li><p>Latency becomes predictable because pods are never artificially slowed.</p>
</li>
</ul>
<p><strong>The argument for keeping CPU limits:</strong></p>
<ul>
<li><p>A noisy neighbor pod can consume all spare CPU and starve other pods.</p>
</li>
<li><p>Without limits, a bug in one service can degrade the entire node.</p>
</li>
</ul>
<p>The right answer depends on your workload. For latency-sensitive APIs, consider removing CPU limits and relying on requests alone. For batch workloads, CPU limits are fine. For anything in between, measure throttling first before deciding.</p>
<hr />
<h1>Memory limits and OOMKill: the dangerous one</h1>
<p>Memory is what Kubernetes calls an incompressible resource. Unlike CPU, the kernel cannot throttle memory access, it can't say "you only get 80% of the memory reads you asked for." Memory is binary: either the process has it, or it doesn't.</p>
<p>When a pod's memory usage exceeds its limit, the Linux OOM (Out of Memory) killer terminates one of its processes immediately. No warning. No graceful shutdown. The process is gone. Kubernetes then sees that a container has exited unexpectedly and restarts it, which is where <code>CrashLoopBackOff</code> comes from.</p>
<pre><code class="language-bash"># Detect OOMKill in pod description
kubectl describe pod api-7d6b9f8c4-xk2pq -n production

# Look for this in the output:
Last State:     Terminated
  Reason:       OOMKilled
  Exit Code:    137
  Started:      Mon, 21 Jun 2026 02:14:32 +0000
  Finished:     Mon, 21 Jun 2026 02:14:33 +0000
</code></pre>
<p>Exit code 137 means the process was killed by signal 9 (SIGKILL) from the OOM killer. If you see this, your memory limit is too low for your actual workload.</p>
<h2>OOMKill at the node level</h2>
<p>OOMKill can also happen at the node level, independently of your pod limits. If total memory consumption across all pods on a node approaches the node's total capacity, the Linux kernel's node-level OOM killer activates.</p>
<p>In this case, Kubernetes doesn't wait for the OOM killer. It has its own eviction mechanism, if available memory on a node drops below a configured threshold, Kubernetes starts evicting pods proactively. Which pods get evicted first is determined by QoS class, which we'll cover next.</p>
<hr />
<h1>QoS classes: who dies first under pressure</h1>
<p>Kubernetes automatically assigns every pod a Quality of Service (QoS) class based on how its requests and limits are configured. You don't set this manually; it's derived. Under node pressure, Kubernetes evicts pods in order from lowest to highest QoS class.</p>
<p>There are three classes:</p>
<h2>BestEffort: lowest priority</h2>
<p>A pod is BestEffort when it has no requests or limits set at all:</p>
<pre><code class="language-yaml"># BestEffort, no resources section at all
resources: {}
</code></pre>
<p>BestEffort pods are the first to be evicted under node pressure. They get whatever resources happen to be available, and nothing is guaranteed. Never run production workloads as BestEffort.</p>
<h2>Burstable: middle priority</h2>
<p>A pod is Burstable when it has requests set, but limits are either not set or higher than requests:</p>
<pre><code class="language-yaml"># Burstable, requests set, limits higher than requests
resources:
  requests:
    cpu: "250m"
    memory: "256Mi"
  limits:
    cpu: "500m"
    memory: "512Mi"
</code></pre>
<p>Most production workloads should be Burstable. The pod has guaranteed minimum resources (the requests) but can burst above them when capacity is available. Under eviction pressure, Burstable pods are evicted after BestEffort but before Guaranteed.</p>
<h2>Guaranteed: highest priority</h2>
<p>A pod is Guaranteed when its requests equal its limits for all containers:</p>
<pre><code class="language-yaml"># Guaranteed, requests == limits
resources:
  requests:
    cpu: "500m"
    memory: "512Mi"
  limits:
    cpu: "500m"     # same as request
    memory: "512Mi" # same as request
</code></pre>
<p>Guaranteed pods are the last to be evicted. Kubernetes will sacrifice BestEffort and Burstable pods before touching a Guaranteed pod. Use this for your most critical services, databases, core APIs, and anything where an eviction is catastrophic.</p>
<p>To check a pod's QoS class:</p>
<pre><code class="language-shell">kubectl get pod api-7d6b9f8c4-xk2pq -n production \
  -o jsonpath='{.status.qosClass}'

# Output: Burstable
</code></pre>
<hr />
<h1>A practical framework for setting requests and limits</h1>
<p>Knowing the theory is one thing. Knowing what numbers to put in your YAML is another. Here's a step-by-step framework that works in production:</p>
<h2>Step 1: observe before you configure</h2>
<p>Deploy your workload without limits first (or with very high limits that won't be hit). Let it run under realistic traffic for several days, including peak hours. Collect metrics with <code>kubectl top pods</code> or Prometheus.</p>
<pre><code class="language-shell"># Watch resource usage over time
watch kubectl top pods -n production -l app=api
</code></pre>
<h2>Step 2: set requests at p50 (median) usage</h2>
<p>Your request should reflect typical usage, what the pod uses most often. The p50 (50th percentile) of observed CPU and memory usage is a good starting point.</p>
<p>If your service typically uses 150m CPU and 200Mi memory:</p>
<pre><code class="language-yaml">requests:
  cpu: "150m"
  memory: "200Mi"
</code></pre>
<h2>Step 3: set memory limits at p99 plus a buffer</h2>
<p>Your memory limit should handle traffic spikes without triggering OOMKill. The p99 (99th percentile) plus a 20-30% buffer is a safe starting point:</p>
<pre><code class="language-yaml">limits:
  memory: "350Mi"  # p99 was ~280Mi, plus 25% buffer
</code></pre>
<h2>Step 4: handle CPU limits carefully</h2>
<p>Start at 2-4x your CPU request. Monitor for throttling. If you see consistent throttling in <code>container_cpu_throttled_seconds_total</code>, either raise the limit or remove it for that service.</p>
<pre><code class="language-yaml">limits:
  cpu: "500m"  # 3x the 150m request, gives room to burst
</code></pre>
<h2>Step 5: use LimitRange to enforce defaults at the namespace level</h2>
<p>As a platform engineer, you don't want to rely on every developer remembering to set resources. Use a <code>LimitRange</code> to provide defaults for pods that don't specify them:</p>
<pre><code class="language-yaml"># Enforce default requests and limits for all pods in a namespace
apiVersion: v1
kind: LimitRange
metadata:
  name: default-resource-limits
  namespace: production
spec:
  limits:
  - type: Container
    default:           # applied when no limits are specified
      cpu: "500m"
      memory: "256Mi"
    defaultRequest:    # applied when no requests are specified
      cpu: "100m"
      memory: "128Mi"
    max:               # no pod can exceed these
      cpu: "2"
      memory: "2Gi"
    min:               # no pod can go below these
      cpu: "50m"
      memory: "64Mi"
</code></pre>
<h2>Step 6: use ResourceQuota to cap total namespace consumption</h2>
<p><code>ResourceQuota</code> limits the total resources that can be consumed across all pods in a namespace, useful for multi-tenant clusters and chargeback:</p>
<pre><code class="language-yaml"># Cap total resource consumption for the production namespace
apiVersion: v1
kind: ResourceQuota
metadata:
  name: production-quota
  namespace: production
spec:
  hard:
    requests.cpu: "10"      # total CPU requests across all pods
    requests.memory: "20Gi" # total memory requests across all pods
    limits.cpu: "20"        # total CPU limits across all pods
    limits.memory: "40Gi"   # total memory limits across all pods
    pods: "50"              # maximum number of pods
</code></pre>
<hr />
<h1>Common mistakes</h1>
<h2><strong>Running without any resource configuration (BestEffort)</strong></h2>
<p>This is the most dangerous mistake. With no requests, the scheduler has no visibility into what your pod actually needs. Under node pressure, your pods are the first to be evicted, regardless of how critical your service is.</p>
<h2><strong>Setting limits without requests</strong></h2>
<p>When you set a limit without a request, Kubernetes automatically sets the request equal to the limit, which makes the pod Guaranteed. This isn't always wrong, but it means you're reserving 100% of your limit on the scheduler even if typical usage is much lower. Over time this leads to poor bin packing and wasted capacity.</p>
<h2><strong>Copying the same resource values for every service</strong></h2>
<p>A stateless Go API, a JVM-based service, and a batch data processor have completely different memory profiles. A Go binary might be happy with 128Mi. A JVM service might need 1Gi just for the heap. Tune per workload, not per deployment template.</p>
<h2><strong>Forgetting init containers</strong></h2>
<p>Init containers run before your main container and have their own resource requirements. If you set tight limits on init containers, pod initialization can fail, and Kubernetes will keep retrying. Always check the init container resource usage too:</p>
<pre><code class="language-yaml">initContainers:
- name: db-migrate
  resources:
    requests:
      cpu: "100m"
      memory: "128Mi"
    limits:
      cpu: "200m"
      memory: "256Mi"
</code></pre>
<h2><strong>Setting memory requests too low relative to actual usage</strong></h2>
<p>If your pod's actual memory usage regularly exceeds its request (even if it stays below the limit), it becomes a candidate for eviction under node pressure. The request is not just a scheduling hint, it also affects eviction priority within the Burstable class. Pods whose usage exceeds their request are evicted before pods whose usage stays within their request.</p>
<hr />
<h1>Summary</h1>
<p>Requests and limits are the foundation of stable Kubernetes workloads. Get them wrong, and you'll spend nights chasing OOM kills and throttling-induced latency spikes. Get them right, and your cluster runs efficiently with predictable, stable workloads.</p>
<p>Three things to take away:</p>
<ul>
<li><p>Requests tell the scheduler where to place your pod. Always set them, never run BestEffort in production.</p>
</li>
<li><p>Memory limits tell the kernel when to kill your pod. Set them generously enough to handle traffic spikes, and monitor for OOMKill with <code>kubectl describe pod</code>.</p>
</li>
<li><p>CPU limits are more nuanced. Start with 2-4x your CPU request and remove them for latency-sensitive services if throttling is a problem.</p>
</li>
</ul>
<p>Understanding this is the prerequisite for everything else in platform engineering, autoscaling, capacity planning, chargeback, and multi-tenancy, all of which depend on the resource configuration being correct.</p>
<hr />
<p><strong>P.S.</strong>: Writing this post from Asunción, Paraguay 🇵🇾 where it's hard to concentrate right now. Paraguay just knocked Germany out of the 2026 World Cup on penalties. For the first time in history, Germany lost a penalty shootout. Goalkeeper <a href="https://www.instagram.com/orlando_daniel01/?hl=en">Orlando Gil</a> was a hero. We face France next. Forgive me if there are any bugs or mistakes in this post. I may have been screaming at a television.</p>
<hr />
<h2>Let's connect!</h2>
<p>One of the best parts of writing in public is the people you meet along the way, engineers at different stages of their journey, working on similar problems from completely different angles.</p>
<p>If something in this post resonated, if you spotted a bug, or if you just want to talk Go, Kubernetes, Platform Engineering, DevOps, or whatever, I'm always happy to hear from you.</p>
<ul>
<li><p><a href="https://www.linkedin.com/in/ferrios/">LinkedIn</a></p>
</li>
<li><p><a href="https://github.com/FerRiosCosta">GitHub</a></p>
</li>
<li><p><a href="https://x.com/ferztyle">Twitter / X</a></p>
</li>
</ul>
<p><em>Building from Asunción, Paraguay 🇵🇾</em></p>
]]></content:encoded></item><item><title><![CDATA[Go HTTP middleware explained: what it is, how it works, and how to build your own]]></title><description><![CDATA[Learn how Go HTTP middleware works, why next.ServeHTTP is the key, and how to build request ID, logger, and auth middleware.]]></description><link>https://ferztyle.me/go-http-middleware-explained-what-it-is-how-it-works-and-how-to-build-your-own</link><guid isPermaLink="true">https://ferztyle.me/go-http-middleware-explained-what-it-is-how-it-works-and-how-to-build-your-own</guid><category><![CDATA[Go Language]]></category><category><![CDATA[golang]]></category><category><![CDATA[Golang developer]]></category><category><![CDATA[Web Development]]></category><category><![CDATA[http]]></category><dc:creator><![CDATA[Fer]]></dc:creator><pubDate>Mon, 22 Jun 2026 13:54:47 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/61db385c3ce4b2377adfdcda/579922ed-74ca-44e7-8e1f-7a24fedbfdb9.jpg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<blockquote>
<p>This is part 2 of 2 in the series <strong>Go HTTP middleware from scratch</strong>. If you're new to Go types, → <a href="#">read part 1 first</a>.</p>
</blockquote>
<hr />
<h1>The same code keeps showing up everywhere</h1>
<p>You're building an HTTP server. Every request needs a unique ID for tracing. Every request needs to check authentication. Every request needs its duration logged. The naive approach: copy that code into every handler.</p>
<pre><code class="language-go">// Without middleware — same boilerplate in every single handler
func getUserHandler(w http.ResponseWriter, r *http.Request) {
    // Auth check — copy/pasted from every other handler
    token := r.Header.Get("Authorization")
    if token == "" {
        http.Error(w, "unauthorized", http.StatusUnauthorized)
        return
    }

    // Request ID — copy/pasted from every other handler
    requestID := uuid.New().String()
    log.Printf("requestID=%s handling getUser", requestID)

    // actual handler logic finally starts here...
}
</code></pre>
<p>Do this across 20 handlers, and you have a maintenance nightmare. Change the auth logic once, and you have to update 20 files.</p>
<p>Middleware is the Go way to solve this. Write the cross-cutting logic once, wrap it around your handlers, and never think about it again.</p>
<hr />
<h1>What is this post about</h1>
<ul>
<li><p>What middleware is and how Go's HTTP model makes it natural.</p>
</li>
<li><p>How the http.Handler interface works, the foundation everything builds on.</p>
</li>
<li><p>How to write your own middleware from scratch.</p>
</li>
<li><p>How to chain multiple middleware together.</p>
</li>
<li><p>How to pass data through the chain using context.</p>
</li>
<li><p>Tips for advanced usage: ordering, third-party routers, and common pitfalls.</p>
</li>
</ul>
<hr />
<h1>The foundation: the http.Handler interface</h1>
<p>As I mentioned in <a href="https://ferztyle.me/go-types-explained-the-foundation-you-need-before-writing-http-handlers"><strong>the first part of this serie</strong></a>, everything in Go's HTTP stack is built on one tiny interface:</p>
<pre><code class="language-go">// This is the entire http.Handler interface — just one method.
// Any type that has a ServeHTTP method satisfies it automatically.
type Handler interface {
    ServeHTTP(ResponseWriter, *Request)
}
</code></pre>
<p>If you've read the previous posts in this series, you'll recognize this pattern. Go interfaces are just method signatures. Any Go type with ServeHTTP(ResponseWriter, *Request) is automatically an HTTP handler. No registration, no declaration. If you remember, <code>http.HandlerFunc</code> is a convenience type that lets you turn a plain function into an http.Handler:</p>
<pre><code class="language-go">// HandlerFunc is a function type that also implements http.Handler.
// This is how you write handlers without creating a struct.
type HandlerFunc func(ResponseWriter, *Request)

func (f HandlerFunc) ServeHTTP(w ResponseWriter, r *Request) {
    f(w, r)
}
</code></pre>
<p>This means these two ways of writing a handler are equivalent:</p>
<pre><code class="language-go">// Option A: using http.HandleFunc, to convert a plain function 
// to a HandlerFunc type
http.HandleFunc("/hello", func(w http.ResponseWriter, r *http.Request) {
    fmt.Fprintln(w, "hello")
})

// Option B: a struct implementing http.Handler
type HelloHandler struct{}

func (h HelloHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
    fmt.Fprintln(w, "hello")
}
</code></pre>
<p>Most people use option A for simple handlers. The struct approach becomes useful when your handler needs to hold state (like a database client).</p>
<hr />
<h1>What is middleware?</h1>
<p>Middleware is a function that:</p>
<ol>
<li><p>Accepts an http.Handler.</p>
</li>
<li><p>Returns a new http.Handler.</p>
</li>
<li><p>Does something before and/or after calling the original handler.</p>
</li>
</ol>
<pre><code class="language-go">// This is the shape of every middleware in Go.
// It wraps a handler and returns a new one.
func MyMiddleware(next http.Handler) http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        // Do something BEFORE the handler runs
        // (auth check, logging, adding context...)

        next.ServeHTTP(w, r) // call the actual handler

        // Do something AFTER the handler runs
        // (log the response, record timing...)
    })
}
</code></pre>
<p>The next parameter is the handler this middleware wraps. Calling <code>next.ServeHTTP(w, r)</code> passes control forward, like handing a baton in a relay race.</p>
<h2>The relay race explained</h2>
<p>Here's the mental model that makes middleware click:</p>
<pre><code class="language-plaintext">Request comes in
      │
      ▼
┌─────────────────┐
│   Middleware 1    ← does its work (e.g. logs start time)
│       │         
│       ▼         
│  Middleware 2     ← does its work (e.g. checks auth)
│       │         
│       ▼         
│    Handler        ← does the actual business logic
│       │         
│       ▼         
│  Middleware 2     ← does its work after (e.g. checks result)
│       │         
│       ▼         
│  Middleware 1     ← does its work after (e.g. logs duration)
└─────────────────┘
      │
      ▼
Response goes out
</code></pre>
<p>Each middleware wraps the next layer. Code before next.ServeHTTP runs on the way in. Code after runs on the way out. This is sometimes called the "onion model."</p>
<hr />
<h1>Building three real middleware functions</h1>
<p>Let's build three practical middleware functions and chain them together. You can find the repo <a href="https://github.com/FerRiosCosta/go-middleware-examples">here</a>.</p>
<p>But before writing any code, here's how the project is laid out. You will get a clearer understanding of how a Golang project should be structured if you read this post first about <a href="https://ferztyle.me/go-packages-and-modules-explained">Go Packages</a>. Each middleware gets its own file inside a shared <code>middleware</code> package, and <code>cmd/server/main.go</code> wires everything together.</p>
<pre><code class="language-plaintext">go-middleware-examples/
├── go.mod
├── cmd/
│   └── server/
│       └── main.go            ← entry point — registers routes and chains middleware
└── internal/
    └── middleware/
        ├── requestid.go       ← RequestID middleware + context key + getter
        ├── logger.go          ← Logger middleware + responseWriter wrapper
        ├── auth.go            ← Auth middleware
        └── chain.go           ← Chain helper for readable middleware composition
</code></pre>
<p>A few decisions worth noting:</p>
<ul>
<li><p>All middleware lives under <code>internal/middleware/</code>, it's private to this module. If you later wanted to publish this middleware as a reusable library for other projects, it would move to <code>pkg/middleware/</code> instead.</p>
</li>
<li><p>Each middleware gets its <strong>own file</strong> even though they all declare <code>package middleware</code>. This keeps each one focused and easy to find, <code>requestid.go</code> only ever deals with request IDs, <code>auth.go</code> only ever deals with authentication.</p>
</li>
<li><p>The context key (<code>RequestIDKey</code>) and its getter (<code>GetRequestID</code>) live in the same file as the middleware that sets it (<code>requestid.go</code>). Anything that reads the request ID imports the <code>middleware</code> package and calls <code>middleware.GetRequestID(ctx)</code>, never reaching into the context directly. You can know more about Go contexts <a href="https://ferztyle.me/go-context-package">here</a>.</p>
</li>
<li><p><code>cmd/server/main.go</code> stays thin, it only registers handlers and chains middleware together. No middleware logic lives there.</p>
</li>
</ul>
<p>From the root directory (<code>go-middleware-examples</code>), run the following commands to create your Go project, and install the uuid package:</p>
<pre><code class="language-shell">go mod init github.com/&lt;your-username&gt;/go-middleware-examples
go get github.com/google/uuid
</code></pre>
<p><mark class="bg-yellow-200 dark:bg-yellow-500/30">You can name your project as you want. I usually name my projects according to my GitHub app repo name.</mark></p>
<p>Here's the go.mod for reference:</p>
<pre><code class="language-plaintext">module github.com/FerRiosCosta/go-middleware-examples

go 1.26.3

require github.com/google/uuid v1.6.0 // indirect
</code></pre>
<p>Now let's build each file.</p>
<h2>Request ID middleware</h2>
<p>Please consider the first comment line, which specifies where the file should be created. This middleware attaches a unique ID to every request. Useful for tracing a single request through your logs.</p>
<pre><code class="language-go">// internal/middleware/requestid.go
package middleware

import (
    "context"
    "net/http"

    "github.com/google/uuid"
)

// key is an unexported type for context keys in this package.
// Using a custom type prevents collisions with keys from other packages.
// (Two packages both using the string "requestID" would overwrite each other.)
type key string

// RequestIDKey is the context key for the request ID.
// Exported so handlers in other packages can retrieve it.
const RequestIDKey key = "requestID"

// RequestID generates a unique ID for every incoming request,
// stores it in the context, and adds it to the response headers.
func RequestID(next http.Handler) http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        // Generate a new UUID for this request.
        id := uuid.New().String()

        // Store the ID in a new context derived from the request's context.
        // r.Context() returns the existing context, we build on top of it,
        // not replace it, so any previously set values are preserved.
        ctx := context.WithValue(r.Context(), RequestIDKey, id)

        // Add the ID to the response header.
        // This lets clients (and load balancers) correlate their logs with yours.
        w.Header().Set("X-Request-ID", id)

        // This is the line from the previous explanation:
        // create a copy of the request with the new context attached,
        // then pass it to the next handler in the chain.
        next.ServeHTTP(w, r.WithContext(ctx))
    })
}

// GetRequestID is a helper to retrieve the request ID from a context.
// Handlers call this instead of reaching into the context directly.
func GetRequestID(ctx context.Context) string {
    id, _ := ctx.Value(RequestIDKey).(string)
    return id
}
</code></pre>
<h2>Logger middleware</h2>
<p>Logs every request: method, path, duration, and status code. But, before looking at the full code, let's first try to understand how this logger middleware works under the hood.</p>
<h3>What is http.ResponseWriter?</h3>
<p>Before looking at the code, it helps to understand the type we're about to wrap.</p>
<p><code>http.ResponseWriter</code> is an interface, every handler you write receives one as its first argument. It's how your handler sends a response back to the client: the status code, the headers, and the body.</p>
<pre><code class="language-go">// http.ResponseWriter is an interface with three methods:
type ResponseWriter interface {
    Header() http.Header         // get/set response headers
    Write([]byte) (int, error)   // write the response body
    WriteHeader(statusCode int)  // write the status code (200, 404, 500...)
}
</code></pre>
<p>A typical handler uses it like this:</p>
<pre><code class="language-go">func myHandler(w http.ResponseWriter, r *http.Request) {
    w.WriteHeader(http.StatusOK)        // write the status code
    w.Write([]byte("hello!"))            // write the body
}
</code></pre>
<h3>The problem: you can't read the status code back</h3>
<p>Here's the catch. <code>http.ResponseWriter</code> lets you <strong>write</strong> a status code, but it has no method to <strong>read</strong> it back afterward. There's no <code>w.StatusCode()</code> you can call. Once you write it, it's gone, sent straight to the client over the network.</p>
<p>This is a problem for our <code>Logger</code> middleware. Remember the relay race model: <code>Logger</code> calls <code>next.ServeHTTP(w, r)</code>, waits for the handler to finish, and only then logs the result. But by the time the handler finishes, it has already called <code>w.WriteHeader(404)</code> (or whatever status it chose), and <code>Logger</code> has no way to find out what that status was. The information is gone.</p>
<h3>The solution: wrap it in our own struct</h3>
<p>To solve this, we create our <strong>own</strong> type that:</p>
<ol>
<li><p>Embeds the original <code>http.ResponseWriter</code>, so it still behaves exactly the same way for the handler</p>
</li>
<li><p>Adds a field to remember the status code</p>
</li>
<li><p>Intercepts the one method we care about (<code>WriteHeader</code>) to save the value before passing it through.</p>
</li>
</ol>
<pre><code class="language-go">// responseWriter wraps http.ResponseWriter to capture the status code.
// http.ResponseWriter doesn't expose the status code after it's written,
// so we intercept WriteHeader to save it.
type responseWriter struct {
    http.ResponseWriter            // embed the original, we get all its methods for free
    statusCode         int         // the status code the handler wrote
}
</code></pre>
<p>The embedded <code>http.ResponseWriter</code> is the key part. In Go, embedding a type inside a struct means the outer struct automatically gets all of the embedded type's methods, for free, with no extra code. So our <code>responseWriter</code> already has <code>Header()</code>, <code>Write()</code>, and <code>WriteHeader()</code> just by embedding <code>http.ResponseWriter</code>. As far as the handler is concerned, our <code>responseWriter</code> looks and behaves exactly like a normal <code>http.ResponseWriter</code>, because it satisfies the same interface.</p>
<p>The only thing left to do is override <code>WriteHeader</code>, the one method we actually need to intercept:</p>
<pre><code class="language-go">// WriteHeader intercepts the status code before passing it through.
func (rw *responseWriter) WriteHeader(code int) {
    rw.statusCode = code               // save it for logging
    rw.ResponseWriter.WriteHeader(code) // pass it through to the real writer
}
</code></pre>
<p>This is the trick: when our <code>responseWriter</code> defines its own <code>WriteHeader</code> method, that one <strong>overrides</strong> the embedded version. So when a handler calls <code>w.WriteHeader(404)</code>, it actually calls <em>our</em> version, which saves <code>404</code> into <code>rw.statusCode</code>, then calls the original <code>ResponseWriter.WriteHeader(404)</code> so the client still receives the real response. The handler never notices anything different happened.</p>
<p>Now <code>Logger</code> can read <code>wrapped.statusCode</code> after the handler finishes, something that was impossible with a plain <code>http.ResponseWriter</code>.</p>
<p>Here's the full middleware:</p>
<pre><code class="language-go">// internal/middleware/logger.go
package middleware

import (
    "log/slog"
    "net/http"
    "time"
)

// responseWriter wraps http.ResponseWriter to capture the status code.
// http.ResponseWriter doesn't expose the status code after it's written,
// so we intercept WriteHeader to save it.
type responseWriter struct {
    http.ResponseWriter            // embed the original — we get all its methods for free
    statusCode         int         // the status code the handler wrote
}

// WriteHeader intercepts the status code before passing it through.
func (rw *responseWriter) WriteHeader(code int) {
    rw.statusCode = code               // save it for logging
    rw.ResponseWriter.WriteHeader(code) // pass it through to the real writer
}

// Logger logs each request's method, path, status code, duration,
// and request ID (if set by the RequestID middleware).
func Logger(next http.Handler) http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        // Record when the request arrived.
        start := time.Now()

        // Wrap the ResponseWriter so we can capture the status code.
        wrapped := &amp;responseWriter{
            ResponseWriter: w,
            statusCode:     http.StatusOK, // default to 200 if WriteHeader is never called
        }

        // Call the next handler — this is where the actual work happens.
        next.ServeHTTP(wrapped, r)

        // By the time we reach here, the handler has finished.
        // We can now log everything we know about this request.
        slog.Info("request",
            "method",     r.Method,
            "path",       r.URL.Path,
            "status",     wrapped.statusCode,
            "duration",   time.Since(start).String(),
            "requestID",  GetRequestID(r.Context()), // set by RequestID middleware
        )
    })
}
</code></pre>
<h2>Auth middleware</h2>
<p>Checks for a valid Bearer token before allowing the request through.</p>
<p>This one looks more complicated than <code>RequestID</code> and <code>Logger</code> at first glance, it's a function that returns a function that returns a function. Let's slow down and unpack why, before looking at the full code.</p>
<h3>Why Auth needs an extra layer</h3>
<p><code>RequestID</code> and <code>Logger</code> both have this shape:</p>
<pre><code class="language-go">func RequestID(next http.Handler) http.Handler {
    // ...
}
</code></pre>
<p>One input (<code>next</code>), one output (<code>http.Handler</code>). That's the standard middleware shape we covered earlier.</p>
<p>But <code>Auth</code> needs something extra: a <strong>configurable token</strong>. Every other middleware works the same way no matter what, but <code>Auth</code> needs to know <em>which</em> token counts as valid, and that's different for every app (and usually comes from an environment variable, not a hardcoded value).</p>
<p>So <code>Auth</code> can't just be a middleware, it needs to be a function that <strong>produces</strong> a middleware, once you tell it which token to check:</p>
<pre><code class="language-go">// Auth is NOT middleware itself.
// It's a function that BUILDS a middleware, once you give it a token.
func Auth(validToken string) func(http.Handler) http.Handler {
    // ...
}
</code></pre>
<h3>Breaking down the three layers</h3>
<p>Here's the same function with each layer labeled:</p>
<pre><code class="language-go">//        ┌─── Layer 1: takes your config (the token)
//        │
func Auth(validToken string) func(http.Handler) http.Handler {
    //                        └─── Layer 2: this is what gets returned —
    //                             a real middleware function, with the
    //                             standard func(http.Handler) http.Handler shape

    return func(next http.Handler) http.Handler {
        //     └─── Layer 2 starts here. This is now a normal middleware,
        //          identical in shape to RequestID and Logger.

        return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
            //   └─── Layer 3: the actual handler logic that runs per-request.
            //        This is the same as the inner function in every middleware
            //        you've already seen.

            // ... auth check logic goes here ...
        })
    }
}
</code></pre>
<p>Three layers, three different jobs:</p>
<table>
<thead>
<tr>
<th>Layer</th>
<th>Runs when</th>
<th>Job</th>
</tr>
</thead>
<tbody><tr>
<td>1 — <code>Auth(validToken)</code></td>
<td>Once, at startup</td>
<td>Receives your config (the token)</td>
</tr>
<tr>
<td>2 — <code>func(next http.Handler) http.Handler</code></td>
<td>Once, when you build your middleware chain</td>
<td>Receives the next handler to wrap</td>
</tr>
<tr>
<td>3 — <code>func(w, r)</code></td>
<td>On every single request</td>
<td>Does the actual work — checks the header</td>
</tr>
</tbody></table>
<h3>Why this pattern, and how you use it</h3>
<p>The payoff is that calling <code>Auth</code> looks almost identical to using <code>RequestID</code> or <code>Logger</code>, you just add one extra set of parentheses to pass in the token:</p>
<pre><code class="language-go">// RequestID and Logger take no config, pass them directly
middleware.RequestID
middleware.Logger

// Auth takes config, call it first to get back a real middleware
middleware.Auth("my-secret-token")   // ← this call returns a middleware function
</code></pre>
<p>That's it. <code>Auth("my-secret-token")</code> runs Layer 1 immediately and hands you back Layer 2, a normal <code>func(http.Handler) http.Handler</code>, ready to be used exactly like any other middleware in your <code>Chain</code>:</p>
<pre><code class="language-go">Chain(mux,
    middleware.RequestID,                // sets the request ID first
    middleware.Logger,                   // then logs — sees the ID
    middleware.Auth("my-secret-token"),  // called with () — returns a middleware
)
</code></pre>
<p>If this still feels unfamiliar, it helps to compare it to something simpler, a function that builds a greeting function:</p>
<pre><code class="language-go">// Same shape, much simpler example.
// MakeGreeter takes a name and returns a NEW function
// that already "remembers" that name.
func MakeGreeter(name string) func() string {
    return func() string {
        return "Hello, " + name + "!"
    }
}

sayHiToAlice := MakeGreeter("Alice") // returns a function
fmt.Println(sayHiToAlice())          // "Hello, Alice!"
</code></pre>
<p><code>Auth</code> does the exact same thing, it just returns a middleware function instead of a greeting function. Once you see <code>MakeGreeter</code>, <code>Auth(validToken)</code> stops looking complicated; it's the same "function that builds and returns another function" pattern, just doing more useful work inside.</p>
<p>Now here's the full code with that context in mind:</p>
<pre><code class="language-go">// internal/middleware/auth.go
package middleware

import (
    "net/http"
    "strings"
)

// Auth checks for a valid Bearer token in the Authorization header.
// If the token is missing or invalid, it returns 401 and stops the chain —
// next.ServeHTTP is never called, so the handler never runs.
func Auth(validToken string) func(http.Handler) http.Handler {
    // Return a middleware function — this pattern lets us configure
    // middleware with parameters (the token) while keeping the standard shape.
    return func(next http.Handler) http.Handler {
        return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
            // Read the Authorization header.
            authHeader := r.Header.Get("Authorization")

            // Check the format: "Bearer &lt;token&gt;"
            parts := strings.SplitN(authHeader, " ", 2)
            if len(parts) != 2 || parts[0] != "Bearer" {
                // Respond with 401 and stop. next.ServeHTTP is never called.
                http.Error(w, "missing or malformed token", http.StatusUnauthorized)
                return
            }

            // Validate the token.
            // In a real app you'd verify a JWT or look up the token in a database.
            if parts[1] != validToken {
                http.Error(w, "invalid token", http.StatusUnauthorized)
                return
            }

            // Token is valid — pass the request to the next handler.
            next.ServeHTTP(w, r)
        })
    }
}
</code></pre>
<h2>Chaining middleware together</h2>
<p>Now let's wire everything up. But first, create your own secret token and paste it into your <code>main.go</code> file, you can create it from <a href="https://it-tools.tech/token-generator">here</a>. Remember to also include that token in your request. You can see how to do it in the section about testing the server.</p>
<p>The standard Go way to chain middleware is to nest the calls:</p>
<pre><code class="language-go">// cmd/server/main.go
package main

import (
    "fmt"
    "net/http"

    "github.com/yourname/myapp/internal/middleware"
)

// userHandler is the actual business logic.
// It doesn't know about auth, logging, or request IDs —
// all of that is handled by middleware before it runs.
func userHandler(w http.ResponseWriter, r *http.Request) {
    // Retrieve the request ID that was set by RequestID middleware.
    id := middleware.GetRequestID(r.Context())
    fmt.Fprintf(w, "hello! your request ID is %s\n", id)
}

func main() {
    mux := http.NewServeMux()
    mux.HandleFunc("/user", userHandler)

    // Chain middleware by wrapping from the outside in.
    // The outermost middleware runs first on the way IN,
    // and last on the way OUT.
    //
    // RequestID must wrap Logger — not the other way around.
    // Logger only ever sees the *r it directly receives. If RequestID
    // runs AFTER Logger, Logger is holding the original request,
    // not the enriched one RequestID produces — so the ID would be empty.
    //
    // Execution order for a request:
    //   RequestID → Logger → Auth → userHandler
    //               (then back out in reverse)
    handler := middleware.RequestID(
        middleware.Logger(
            middleware.Auth("your-secret-token")(
                mux,
            ),
        ),
    )

    http.ListenAndServe(":8080", handler)
}
</code></pre>
<h2>Testing the server</h2>
<pre><code class="language-shell"># Start the server
go run ./cmd/server

# Valid request — should return 200 with a request ID
curl -H "Authorization: Bearer your-secret-token" http://localhost:8080/user

# Missing token — should return 401
curl http://localhost:8080/user

# Invalid token — should return 401
curl -H "Authorization: Bearer wrong-token" http://localhost:8080/user
</code></pre>
<p>Server logs:</p>
<pre><code class="language-plaintext">2026/06/21 20:46:13 INFO request method=GET path=/user status=200 duration=7.208µs requestID=e667de2b-310a-4038-9891-2d948613e93b
2026/06/21 20:46:15 INFO request method=GET path=/user status=200 duration=90.667µs requestID=23a61730-4dd2-4b01-8dc5-986fbcb46436
</code></pre>
<p>Every request gets logged. The request ID ties your server log to the <code>X-Request-ID</code> header in the response, if a client reports a bug, they can give you their request ID and you can find exactly that request in your logs.</p>
<hr />
<h1>Best practices</h1>
<h2><strong>Order matters, RequestID before Logger, Logger before Auth</strong></h2>
<p>The outermost middleware runs first on the way in and last on the way out. Two rules drive the order here:</p>
<ul>
<li><p><code>RequestID</code> <strong>must be outermost (or at least before</strong> <code>Logger</code><strong>)</strong>, <code>Logger</code> can only read context values from the exact <code>*http.Request</code> it was handed. <code>context.WithValue</code> and <code>r.WithContext</code> don't mutate the original request, they return a <em>new</em> one. If <code>RequestID</code> runs after <code>Logger</code>, <code>Logger</code> is stuck holding the original, un-enriched request, <code>GetRequestID</code> will always come back empty. If you are new to Go contexts, you can check this <a href="https://ferztyle.me/go-context-package">post</a> about it; it explains everything you need to know about Go contexts.</p>
</li>
<li><p><code>Logger</code> <strong>should wrap</strong> <code>Auth</code>, so that failed (401) requests still get logged, not just successful ones.</p>
</li>
</ul>
<pre><code class="language-go">// Good order
Chain(mux,
    middleware.RequestID, // outermost: enriches the request first
    middleware.Logger,    // sees the enriched request — requestID shows up in logs
    middleware.Auth(...), // innermost: blocks invalid requests, but they're still logged
)
</code></pre>
<pre><code class="language-go">// Bad order — this is the bug you'll hit if you swap these two
Chain(mux,
    middleware.Logger,    // ← runs first, but hasn't seen RequestID's context yet
    middleware.RequestID, // ← enriches the request, but only for handlers AFTER this point
    middleware.Auth(...),
)
// Logger's slog.Info call reads r.Context() from its OWN copy of r —
// which was captured before RequestID ever ran. requestID="" every time.
</code></pre>
<p>The general rule: <strong>any middleware that reads a context value must be positioned <em>after</em> (further in than) the middleware that sets it.</strong></p>
<h2><strong>Never call next.ServeHTTP more than once</strong></h2>
<p>Calling it twice sends a double response, which causes a panic in Go's HTTP stack. Always <code>return</code> after an early exit:</p>
<pre><code class="language-go">// Good — returns after writing the error
if !valid {
    http.Error(w, "unauthorized", http.StatusUnauthorized)
    return // ← critical: stops execution here
}
next.ServeHTTP(w, r)

// Bad — falls through and calls next anyway
if !valid {
    http.Error(w, "unauthorized", http.StatusUnauthorized)
    // missing return — next.ServeHTTP still runs!
}
next.ServeHTTP(w, r)
</code></pre>
<h2><strong>Use unexported context keys</strong></h2>
<p>Always define context keys as a custom unexported type, not a plain string. This prevents key collisions between packages:</p>
<pre><code class="language-go">// Bad — any package using the string "userID" will collide
ctx = context.WithValue(ctx, "userID", id)

// Good — only this package can access this key
type key string
const userIDKey key = "userID"
ctx = context.WithValue(ctx, userIDKey, id)
</code></pre>
<hr />
<h1>Tips for advanced users</h1>
<h2><strong>Tip 1: Use a third-party router for cleaner middleware</strong></h2>
<p>The standard library's <code>http.ServeMux</code> applies middleware to all routes at once. If you need per-route middleware (auth on some routes, not others), a router like <code>chi</code> or <code>gorilla/mux</code> makes this clean:</p>
<pre><code class="language-go">r := chi.NewRouter()

r.Use(middleware.Logger)    // applies to all routes
r.Use(middleware.RequestID) // applies to all routes

r.Group(func(r chi.Router) {
    r.Use(middleware.Auth("secret")) // applies only to routes in this group
    r.Get("/admin", adminHandler)
    r.Get("/users", usersHandler)
})

r.Get("/health", healthHandler) // no auth required
</code></pre>
<h2><strong>Tip 2: Capture response body size</strong></h2>
<p>Extend <code>responseWriter</code> to also track bytes written — useful for monitoring:</p>
<pre><code class="language-go">type responseWriter struct {
    http.ResponseWriter
    statusCode int
    bytes      int
}

func (rw *responseWriter) Write(b []byte) (int, error) {
    n, err := rw.ResponseWriter.Write(b)
    rw.bytes += n // track how many bytes were written
    return n, err
}
</code></pre>
<h2><strong>Tip 3: Recover from panics</strong></h2>
<p>A panic in any handler crashes the goroutine handling that request. A recovery middleware catches it and returns a 500 instead of crashing:</p>
<pre><code class="language-go">func Recovery(next http.Handler) http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        defer func() {
            if err := recover(); err != nil {
                slog.Error("panic recovered", "error", err, "requestID", GetRequestID(r.Context()))
                http.Error(w, "internal server error", http.StatusInternalServerError)
            }
        }()
        next.ServeHTTP(w, r)
    })
}
</code></pre>
<p>Add this as the outermost middleware so it catches panics from every layer:</p>
<pre><code class="language-go">Chain(mux,
    middleware.Recovery,  // outermost — catches panics from every layer below
    middleware.RequestID, // sets the request ID next
    middleware.Logger,    // sees the enriched request — requestID shows up in logs
    middleware.Auth("secret"),
)
</code></pre>
<hr />
<h1>Summary</h1>
<p>Middleware is just a function that wraps a handler and returns a new one. Everything else follows from that.</p>
<p>Three things to take away:</p>
<ul>
<li><p><code>next.ServeHTTP(w, r.WithContext(ctx))</code>, this is the line that passes the request forward with an enriched context. Understanding it unlocks the whole pattern.</p>
</li>
<li><p>Order matters, outermost middleware runs first on the way in, last on the way out. Anything that <em>sets</em> a context value (like <code>RequestID</code>) must come before anything that <em>reads</em> it (like <code>Logger</code>), or the value will be empty.</p>
</li>
<li><p>Always <code>return</code> after early exits, calling <code>next.ServeHTTP</code> after writing an error response causes a double response panic.</p>
</li>
</ul>
<p>The three middleware functions in this post, <code>RequestID</code>, <code>Logger</code>, and <code>Auth</code>, are production-ready. Add <code>Recovery</code> and you have a solid foundation for any Go HTTP server.</p>
<hr />
<h2><strong>Let's connect!</strong></h2>
<p>One of the best parts of writing in public is the people you meet along the way, engineers at different stages of their journey, working on similar problems from completely different angles.</p>
<p>If something in this post resonated, if you spotted a bug, or if you just want to talk Go, Kubernetes, Platform Engineering, DevOps, or whatever, I'm always happy to hear from you.</p>
<ul>
<li><p><a href="https://www.linkedin.com/in/ferrios/"><strong>LinkedIn</strong></a></p>
</li>
<li><p><a href="https://github.com/FerRiosCosta"><strong>GitHub</strong></a></p>
</li>
<li><p><a href="https://x.com/ferztyle"><strong>Twitter / X</strong></a></p>
</li>
</ul>
<p><em>Building from Asunción, Paraguay 🇵🇾</em></p>
]]></content:encoded></item><item><title><![CDATA[Go types explained: the foundation you need before writing HTTP handlers]]></title><description><![CDATA[Learn Go types from scratch: structs, function types, and how methods attach to them. The foundation before write your first HTTP middleware.]]></description><link>https://ferztyle.me/go-types-explained-the-foundation-you-need-before-writing-http-handlers</link><guid isPermaLink="true">https://ferztyle.me/go-types-explained-the-foundation-you-need-before-writing-http-handlers</guid><category><![CDATA[Go Language]]></category><category><![CDATA[golang]]></category><category><![CDATA[#go-development]]></category><category><![CDATA[Web Development]]></category><dc:creator><![CDATA[Fer]]></dc:creator><pubDate>Thu, 11 Jun 2026 21:11:10 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/61db385c3ce4b2377adfdcda/e71bee58-91de-441a-b2ab-9894885b24d4.jpg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h1>A quick introduction to Go types</h1>
<p>According to <a href="https://go.dev/ref/spec#Types">https://go.dev/ref/spec#Types</a>, in Go, a type specifies a set of values, along with operations and methods specific to those values.</p>
<p>This is something fundamental about Go: <strong>you can define your own types based on existing ones</strong>, and those types can have methods attached to them.</p>
<p>You've probably seen this with structs:</p>
<pre><code class="language-go">// A struct type — groups fields together
type User struct {
    Name  string
    Email string
}

// A method attached to the User type
func (u User) Greet() string {
    return "Hello, " + u.Name
}
</code></pre>
<p>But Go lets you do the same thing with <strong>any</strong> type, including functions.</p>
<h2>Function types</h2>
<p>In Go, functions are values. You can assign them to variables, pass them as arguments, and — most importantly here, <strong>define a named type based on a function signature</strong>:</p>
<pre><code class="language-go">// This defines a new type called "Greeter"
// whose underlying type is a function that takes a string and returns a string.
type Greeter func(name string) string
</code></pre>
<p>Now <code>Greeter</code> is a type, just like <code>int</code> or <code>string</code> or <code>User</code>. Any function with the right signature (<code>func(string) string</code>) is automatically a <code>Greeter</code>.</p>
<pre><code class="language-go">// This function matches the Greeter signature
func sayHello(name string) string {
    return "Hello, " + name
}

// So we can assign it to a Greeter variable
var g Greeter = sayHello

fmt.Println(g("Alice")) // Hello, Alice
</code></pre>
<h3>Attaching methods to a function type</h3>
<p>Here's where it gets interesting. Because <code>Greeter</code> is now a named type, <strong>you can attach methods to it</strong>, exactly like you would with a struct:</p>
<pre><code class="language-go">// A method on a function type — this is valid Go
func (g Greeter) Shout(name string) string {
    return strings.ToUpper(g(name)) // call the function, then shout it
}

fmt.Println(g.Shout("Alice")) // HELLO, ALICE
</code></pre>
<p>This might look strange at first. A function with a method? But it makes perfect sense in Go. <code>Greeter</code> is just a type, and any type can have methods.</p>
<hr />
<h1>Why this matters for HTTP handlers</h1>
<p>Now that you understand function types, let's look at how Go's HTTP package uses this exact pattern to make your life easier.</p>
<p>Go's HTTP package has two things that are easy to confuse at first: <code>http.Handler</code> and <code>http.HandlerFunc</code>. They sound almost identical, but they play different roles: one is an interface, and one is a type.</p>
<h2>http.Handler — the interface</h2>
<p>An HTTP handler in GO is an object or function responsible for processing an incoming HTTP request and constructing an HTTP response.</p>
<p><code>http.Handler</code> is the interface that represents anything that can handle an HTTP request. It has exactly one method:</p>
<pre><code class="language-go">// http.Handler is an interface — a contract.
// It says: "I don't care what you are.
// As long as you have a ServeHTTP method, you can handle HTTP requests."
type Handler interface {
    ServeHTTP(ResponseWriter, *Request)
}
</code></pre>
<ul>
<li><p><code>http.ResponseWriter</code>: An interface used to construct and send the HTTP response (setting headers, status codes, and writing the body).</p>
</li>
<li><p><code>*http.Request</code>: A pointer to a struct containing all incoming data (headers, query parameters, URL path, and request body).</p>
</li>
</ul>
<p>So, to be recognized as a handler, a type must implement the <code>http.Handler</code> interface by defining a <code>ServeHTTP</code>.</p>
<p>This is what Go's HTTP server actually works with internally. When you call <code>http.ListenAndServe</code>, the second argument must be an <code>http.Handler</code>:</p>
<pre><code class="language-go">// The second argument is an http.Handler —
// Go's server calls ServeHTTP on it for every incoming request.
http.ListenAndServe(":8080", myHandler)
</code></pre>
<p>Any type that has a <code>ServeHTTP</code> method satisfies this interface automatically. A struct, a function type, anything, as long as it has that one method.</p>
<h2>http.HandlerFunc — the type</h2>
<p>Here's the problem: writing a full struct with a <code>ServeHTTP</code> method for every single handler in your app is verbose. Most of the time, you just want to write a plain function:</p>
<pre><code class="language-go">// This is clean and simple, just a function.
// But it's NOT an http.Handler because it has no ServeHTTP method.
func greetUser(w http.ResponseWriter, r *http.Request) {
    fmt.Fprintln(w, "Hello!")
}
</code></pre>
<p>This function can't be passed to <code>http.ListenAndServe</code> directly, it's not an <code>http.Handler</code>. It has no <code>ServeHTTP</code> method.</p>
<p>This is exactly the problem <code>http.HandlerFunc</code> solves. It's a named function type with a <code>ServeHTTP</code> method attached, which makes it an <code>http.Handler</code>:</p>
<pre><code class="language-go">// HandlerFunc is a named type based on a function signature.
// Any function that matches func(ResponseWriter, *Request)
// is automatically compatible with this type.
type HandlerFunc func(ResponseWriter, *Request)

// ServeHTTP is attached to HandlerFunc.
// It just calls the function itself — f is the function, so f(w, r) runs it.
// This single method is what makes HandlerFunc satisfy http.Handler.
func (f HandlerFunc) ServeHTTP(w ResponseWriter, r *Request) {
    f(w, r)
}
</code></pre>
<p>Now Go can convert your plain function into an <code>http.HandlerFunc</code>, which has <code>ServeHTTP</code>, which satisfies <code>http.Handler</code>.</p>
<p>You can imagine that this is what Go does under the hood:</p>
<pre><code class="language-go">var fn http.HandlerFunc = greetUser  // convert the function to HandlerFunc
var h  http.Handler    = fn          // HandlerFunc satisfies http.Handler
</code></pre>
<p>But, in practice, you never write these steps manually; you use the <code>http.HandleFunc</code> function.</p>
<h3>http.HandleFunc</h3>
<pre><code class="language-go">// Registers the "/hello" route on the default mux.
// http.HandleFunc converts greetUser to HandlerFunc internally —
// you never see that conversion happen.
http.HandleFunc("/hello", greetUser)
</code></pre>
<p><code>http.HandleFunc</code> register a route on the default server mux. It takes a path and a handler function, converts the function to a <code>HandlerFunc</code> internally, and registers it.</p>
<p><code>http.HandleFunc</code> actually uses <code>http.HandlerFunc</code> internally, it's just hiding it from you:</p>
<pre><code class="language-go">// This is roughly what http.HandleFunc does under the hood:
func HandleFunc(pattern string, handler func(ResponseWriter, *Request)) {
    // converts your function to HandlerFunc, then registers it
    DefaultServeMux.Handle(pattern, HandlerFunc(handler))
    //                                ^^^^^^^^^^^^^
    //                                HandlerFunc TYPE doing the conversion
}
</code></pre>
<p>So <code>http.HandleFunc</code> is convenience on top of <code>http.HandlerFunc</code>. When you call <code>http.HandleFunc("/hello", greetUser)</code>, Go silently wraps <code>greetUser</code> in an <code>http.HandlerFunc</code> and registers it. You only need to use <code>http.HandlerFunc</code> directly when you're building something lower-level, like middleware, where you need to return an <code>http.Handler</code> explicitly.</p>
<hr />
<h1>Putting it all together</h1>
<p>Here's the full picture in one example:</p>
<pre><code class="language-go">// A plain function — clean and simple to write
func greetUser(w http.ResponseWriter, r *http.Request) {
    fmt.Fprintln(w, "Hello!")
}

// A struct handler — useful when you need to hold state like a DB client
type UserHandler struct {
    db *sql.DB // injected dependency
}

func (h *UserHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
    // can use h.db here
    fmt.Fprintln(w, "Hello from UserHandler!")
}

func main() {
    mux := http.NewServeMux()

    // http.HandleFunc converts greetUser → HandlerFunc → Handler automatically
    mux.HandleFunc("/hello", greetUser)

    // UserHandler already has ServeHTTP — it satisfies http.Handler directly
    mux.Handle("/user", &amp;UserHandler{db: myDB})

    // Both routes are registered on the same mux —
    // the server calls ServeHTTP on whichever one matches the request path.
    http.ListenAndServe(":8080", mux)
}
</code></pre>
<blockquote>
<p>TIP: Use a plain function (via <code>HandlerFunc</code>) for simple handlers. Use a struct for handlers that need dependencies like a database client or a config object. The server doesn't care which one you chose — it just calls <code>ServeHTTP</code>.</p>
</blockquote>
<hr />
<h1>Summary</h1>
<p>Think of it this way:</p>
<ul>
<li><p><code>http.Handler</code> is the <strong>job description</strong>: <em>"must be able to handle HTTP requests"</em></p>
</li>
<li><p><code>http.HandlerFunc</code> is one <strong>way to fulfill</strong> that job description: <em>"a plain function that handles HTTP requests"</em></p>
</li>
<li><p>Your struct with a <code>ServeHTTP</code> method is another way to fulfill it</p>
</li>
</ul>
<p>The server only knows about <code>http.Handler</code>. It never knows whether you used a struct or a <code>HandlerFunc</code> — and it doesn't need to. That's the power of the interface.</p>
<hr />
<h2>Let's connect!</h2>
<p>One of the best parts of writing in public is the people you meet along the way, engineers at different stages of their journey, working on similar problems from completely different angles.</p>
<p>If something in this post resonated, if you spotted a bug, or if you just want to talk Go, Kubernetes, Platform Engineering, DevOps, or whatever, I'm always happy to hear from you.</p>
<ul>
<li><p><a href="https://www.linkedin.com/in/ferrios/">LinkedIn</a></p>
</li>
<li><p><a href="https://github.com/FerRiosCosta">GitHub</a></p>
</li>
<li><p><a href="https://x.com/ferztyle">Twitter / X</a></p>
</li>
</ul>
<p><em>Building from Asunción, Paraguay 🇵🇾</em></p>
]]></content:encoded></item><item><title><![CDATA[Go Context Package]]></title><description><![CDATA[Go context package, what is it and how to use it right]]></description><link>https://ferztyle.me/go-context-package</link><guid isPermaLink="true">https://ferztyle.me/go-context-package</guid><category><![CDATA[golang]]></category><category><![CDATA[Go Language]]></category><category><![CDATA[gocontext]]></category><dc:creator><![CDATA[Fer]]></dc:creator><pubDate>Tue, 09 Jun 2026 02:54:01 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/61db385c3ce4b2377adfdcda/dfa1c86d-94ec-4e1b-bc77-7125a0cbed1b.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h1>What is context</h1>
<p>Every Go developer encounters <code>context.Context</code> early. It shows up in function signatures everywhere — HTTP handlers, database calls, AWS SDK methods, gRPC stubs. Most beginners copy the pattern without fully understanding it, passing context.Background() everywhere and moving on.</p>
<p>That works until it doesn't. A Lambda that ignores context hangs past its timeout. A database query that ignores context keeps running after the HTTP client disconnected.</p>
<p>Context is a built-in package in the Go standard library that enables the propagation of cancellation signals, deadlines, and values across API boundaries and between processes.</p>
<hr />
<h1>Why Context Exists</h1>
<p>Before <code>context</code> was added to the standard library in Go 1.7, there was no standard way to answer these questions across a call chain:</p>
<ul>
<li><p>Should this operation still be running, or has the caller given up?</p>
</li>
<li><p>Is there a deadline this operation must finish by?</p>
</li>
<li><p>What request-scoped data (trace ID, user ID, auth token) should flow with this call?</p>
</li>
</ul>
<hr />
<h1>What is really a Context?</h1>
<p>The <code>context.Context</code> type is an interface with exactly four methods. Every context implements all four.</p>
<pre><code class="language-go">type Context interface {
    Deadline() (deadline time.Time, ok bool)
    Done() &lt;-chan struct{}
    Err() error
    Value(key any) any
}
</code></pre>
<p>Here's what each one does.</p>
<h2>Deadline() — does this context have an expiry?</h2>
<pre><code class="language-go">deadline, ok := ctx.Deadline()
</code></pre>
<p>Returns the time when this context will automatically cancel, and a boolean indicating whether a deadline was set at all. If you created the context with <code>context.Background()</code> or <code>context.WithCancel()</code>, there's no deadline — <code>ok</code> will be <code>false</code>. If you used <code>context.WithTimeout()</code> or <code>context.WithDeadline()</code>, <code>ok</code> is <code>true</code> and <code>deadline</code> tells you exactly when it expires.</p>
<p>You don't call this often in day-to-day code, but it's useful when you need to decide whether there's enough time left to start an expensive operation.</p>
<h2>Done() — tell me when to stop</h2>
<pre><code class="language-go">case &lt;-ctx.Done():
</code></pre>
<p>Returns a channel that gets closed the moment the context is cancelled or times out. You listen to this channel, typically inside a <code>select</code> statement, to know when to abandon work. Until the context ends, the channel blocks. When it closes, your code unblocks and can clean up.</p>
<p>This is the method you'll use most often in loops and long-running operations.</p>
<h2>Err() — why did we stop?</h2>
<pre><code class="language-go">err := ctx.Err()
</code></pre>
<p>Returns <code>nil</code> while the context is still alive. Once the context ends, it returns one of two sentinel errors:</p>
<ul>
<li><p><code>context.DeadlineExceeded</code> — the timeout fired automatically</p>
</li>
<li><p><code>context.Canceled</code> — someone called <code>cancel()</code> manually</p>
</li>
</ul>
<p>This is how you distinguish between "we ran out of time" and "something upstream decided to abort". Both mean stop, but they mean different things for logging and debugging.</p>
<h2>Value() — carry data across function calls</h2>
<pre><code class="language-go">id := ctx.Value(myKey)
</code></pre>
<p>Retrieves a value stored in the context by key. This is used to pass request-scoped data — like a request ID, a user ID, or an auth token — through a chain of function calls without adding extra parameters to every function signature.</p>
<p>One important rule: use a custom unexported type for your keys (not a plain string), otherwise different packages might accidentally overwrite each other's values.</p>
<hr />
<h1>Context's creation</h1>
<p>With contexts, there is a tree structure. The parent context is located at the root of the context tree, and the newly derived context from the parent context is called the child context. Through the parent context, four types of contexts can be derived using the four <code>With</code> methods, and each new context can continue to derive child contexts, making the whole structure look like a tree.</p>
<img src="https://cdn.hashnode.com/uploads/covers/61db385c3ce4b2377adfdcda/20f75624-d24b-4b7a-a99e-294521158a04.png" alt="" style="display:block;margin:0 auto" />

<h2><strong>Parent Context</strong></h2>
<p>There are two ways to create the parent context: an empty context still with no functionality.</p>
<h3>context.Background()</h3>
<pre><code class="language-go">ctx := context.Background()
</code></pre>
<p>Use this at the top of your program — in <code>main()</code>, in <code>init()</code>, or as the starting point when creating a server. It's the foundation everything else derives from.</p>
<h3>context.TODO()</h3>
<p>Semantically identical to <code>context.Background()</code> at runtime, but signals intent: <em>"I know a context should go here, I haven't figured out which one yet."</em></p>
<pre><code class="language-go">ctx := context.TODO() // placeholder — replace with a real context later
</code></pre>
<p>Use it when you're refactoring code to add context support and haven't wired up the full chain yet. It's a marker for future work, not a production pattern.</p>
<h2><strong>Child Contexts</strong></h2>
<p>To make the context useful, we use one of the following child contexts:</p>
<pre><code class="language-go">func WithCancel(parent Context) (ctx Context, cancel CancelFunc)
func WithDeadline(parent Context, deadline time.Time) (Context, CancelFunc)
func WithTimeout(parent Context, timeout time.Duration) (Context, CancelFunc)
func WithValue(parent Context, key, val interface{}) Context
</code></pre>
<h3>context.WithCancel()</h3>
<p>Returns a copy of the parent context with a new <code>Done</code> channel, plus a <code>cancel</code> function. Calling <code>cancel</code> closes the <code>Done</code> channel and marks the context as canceled.</p>
<pre><code class="language-go">ctx, cancel := context.WithCancel(context.Background())
defer cancel() // always call cancel
</code></pre>
<p><strong>Always call</strong> <code>cancel</code><strong>.</strong> If you don't, the context and everything derived from it leaks until the parent is canceled or the program exits. <code>defer cancel()</code> immediately after creation is the idiomatic pattern.</p>
<h3>context.WithTimeout() and context.WithDeadline()</h3>
<p>These set an automatic cancellation time. <code>WithTimeout</code> takes a duration; <code>WithDeadline</code> takes an absolute <code>time.Time</code>.</p>
<pre><code class="language-go">// Cancel after 5 seconds
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()

// Cancel at a specific moment
deadline := time.Now().Add(5 * time.Second)
ctx, cancel := context.WithDeadline(context.Background(), deadline)
defer cancel()
</code></pre>
<p><code>WithTimeout(parent, d)</code> is shorthand for <code>WithDeadline(parent, time.Now().Add(d))</code>. They behave identically. When the deadline passes, the context's <code>Done</code> channel is closed automatically and <code>Err()</code> returns <code>context.DeadlineExceeded</code>.</p>
<p>Still call <code>defer cancel()</code> even with a timeout — if your operation finishes before the deadline, calling cancel releases the timer resources immediately rather than waiting for it to fire.</p>
<h3>context.WithValue</h3>
<p>Creates a child context from the parent context for value passing. Used for passing context information, such as the unique request ID and trace ID, for link tracing and configuration passing.</p>
<pre><code class="language-go">ctx := context.WithValue(context.Background(), authToken, "XYZ_123")
fmt.Println(ctx.Value(authToken))
</code></pre>
<hr />
<h1>How Cancellation Propagates</h1>
<p>Remember, contexts form a tree. When a parent context is canceled, all contexts derived from it are canceled too — automatically, immediately, without any extra code.</p>
<pre><code class="language-go">parent, cancelParent := context.WithCancel(context.Background())

child1, cancelChild1 := context.WithCancel(parent)
child2, cancelTimeout := context.WithTimeout(parent, 10*time.Second)

// Canceling the parent cancels both children
cancelParent()

// child1.Err() == context.Canceled
// child2.Err() == context.Canceled
</code></pre>
<p>This is the mechanism that makes context useful across a call tree. An HTTP handler creates a context with a timeout. It passes that context to a database call, which passes it to a connection pool, which passes it to a network read. When the HTTP client disconnects, the handler's context is canceled, and that cancellation flows down through every layer automatically.</p>
<hr />
<h1>Real-World Use Cases</h1>
<h2>HTTP Servers: Respecting Client Disconnects</h2>
<p>Go's <code>net/http</code> package attaches a context to every incoming request. The context is canceled when the client disconnects or the server's write deadline fires. Your handler receives it via <code>r.Context()</code>.</p>
<p>The following is a fully runnable example. It simulates a slow <code>db.Search</code> using a <code>select</code> with <code>time.After</code>, shows what happens when the client disconnects mid-query, and adds a middleware that attaches a request ID to the context, so every layer of the call chain can log it without it being passed as an explicit argument. You can find the <a href="https://github.com/FerRiosCosta/slow-query-simulation">repo</a> here:</p>
<pre><code class="language-go">package main

import (
    "context"
    "errors"
    "fmt"
    "log/slog"
    "net/http"
    "os"
    "time"

    "github.com/google/uuid"
)

// contextKey is an unexported type for context keys in this package.
// Using a custom type prevents collisions with keys from other packages
// that might also store something under a plain string like "request_id".
type contextKey string

const keyRequestID contextKey = "request_id"

// withRequestID attaches a request ID to the context.
func withRequestID(ctx context.Context, id string) context.Context {
    return context.WithValue(ctx, keyRequestID, id)
}

// requestIDFromContext retrieves the request ID from the context.
// Returns an empty string if no ID was set — callers should handle that gracefully.
func requestIDFromContext(ctx context.Context) string {
    id, _ := ctx.Value(keyRequestID).(string)
    return id
}

var logger = slog.New(slog.NewTextHandler(os.Stdout, &amp;slog.HandlerOptions{
    ReplaceAttr: func(_ []string, a slog.Attr) slog.Attr {
        if a.Key == slog.TimeKey {
            return slog.Attr{}
        }
        return a
    },
}))

// requestIDMiddleware generates a unique ID for every incoming request,
// attaches it to the context, and sends it back in the response header.
// Every function below the handler can read it from ctx for logging —
// without it being passed as a function argument anywhere.
func requestIDMiddleware(next http.Handler) http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        requestID := uuid.NewString()

        ctx := withRequestID(r.Context(), requestID)
        w.Header().Set("X-Request-ID", requestID)

        next.ServeHTTP(w, r.WithContext(ctx))
    })
}

// Search simulates a slow database query that respects context cancellation.
// It reads the request ID directly from ctx — no extra parameter needed.
func Search(ctx context.Context, query string, delay time.Duration) ([]string, error) {
    requestID := requestIDFromContext(ctx)

    logger.Info("db.Search started",
        "request_id", requestID,
        "query", query,
        "simulated_delay", delay,
    )

    select {
    case &lt;-time.After(delay):
        logger.Info("db.Search completed", "request_id", requestID, "query", query)
        return []string{"result-1", "result-2", "result-3"}, nil

    case &lt;-ctx.Done():
        logger.Warn("db.Search aborted",
            "request_id", requestID,
            "query", query,
            "reason", ctx.Err(),
        )
        return nil, ctx.Err()
    }
}

func searchHandler(w http.ResponseWriter, r *http.Request) {
    requestID := requestIDFromContext(r.Context())

    query := r.URL.Query().Get("q")
    if query == "" {
        query = "gophers"
    }

    delay := 5 * time.Second
    if d := r.URL.Query().Get("delay"); d != "" {
        if parsed, err := time.ParseDuration(d); err == nil {
            delay = parsed
        }
    }

    logger.Info("handler started",
        "request_id", requestID,
        "query", query,
        "client", r.RemoteAddr,
    )

    // r.Context() carries both the cancellation signal AND the request ID value.
    // Search receives one ctx and gets everything it needs from it.
    results, err := Search(r.Context(), query, delay)
    if err != nil {
        if errors.Is(err, context.Canceled) {
            logger.Warn("client disconnected before query finished, no response sent",
                "request_id", requestID,
            )
            return
        }
        logger.Error("unexpected search error", "request_id", requestID, "error", err)
        http.Error(w, "search failed", http.StatusInternalServerError)
        return
    }

    logger.Info("handler finished — sending response",
        "request_id", requestID,
        "result_count", len(results),
    )
    fmt.Fprintf(w, "results: %v\n", results)
}

func main() {
    mux := http.NewServeMux()
    mux.HandleFunc("/search", searchHandler)

    // Wrap the mux — every request gets a request ID attached to its context
    handler := requestIDMiddleware(mux)

    logger.Info("server listening on :8080")
    logger.Info("try: curl -v 'http://localhost:8080/search?q=gophers&amp;delay=5s'")
    logger.Info("cancel with Ctrl+C before 5s to trigger client disconnect")

    if err := http.ListenAndServe(":8080", handler); err != nil {
        logger.Error("server error", "error", err)
        os.Exit(1)
    }
}
</code></pre>
<p>Before running, initialize the module and fetch the <code>uuid</code> package, which is in charge of creating random uuids for the incoming requests:</p>
<pre><code class="language-bash">go mod init example/context-demo
go get github.com/google/uuid
</code></pre>
<h3><strong>To test the cancellation path:</strong></h3>
<pre><code class="language-bash"># Terminal 1 — start the server
go run main.go

# Terminal 2 — send a request with a 5s delay, then hit Ctrl+C before it finishes
curl 'http://localhost:8080/search?q=gophers&amp;delay=5s'
# Press Ctrl+C after ~2 seconds
</code></pre>
<p>You should see in the server logs:</p>
<pre><code class="language-plaintext">level=INFO msg="handler started" request_id=4a1f9c2e-... query=gophers client=127.0.0.1:PORT
level=INFO msg="db.Search started" request_id=4a1f9c2e-... query=gophers simulated_delay=5s
level=WARN msg="db.Search aborted" request_id=4a1f9c2e-... query=gophers reason="context canceled"
level=WARN msg="client disconnected before query finished, no response sent" request_id=4a1f9c2e-...
</code></pre>
<p>Notice the same <code>request_id</code> appears in every log line, from the middleware, through the handler, all the way into <code>Search</code>, without it ever being passed as a function argument. It traveled through the context.</p>
<p>You can also verify the ID was sent back in the response header:</p>
<pre><code class="language-bash">curl -v 'http://localhost:8080/search?q=gophers&amp;delay=5s'| grep X-Request-ID
# X-Request-ID: 4a1f9c2e-...
</code></pre>
<h3><strong>To test the happy path</strong></h3>
<p>Let the query finish before disconnecting:</p>
<pre><code class="language-bash">curl 'http://localhost:8080/search?q=gophers&amp;delay=2s'
# Wait for it to complete
</code></pre>
<pre><code class="language-plaintext">level=INFO msg="handler started" request_id=9b3d7f1a-... query=gophers client=127.0.0.1:PORT
level=INFO msg="db.Search started" request_id=9b3d7f1a-... query=gophers simulated_delay=2s
level=INFO msg="db.Search completed" request_id=9b3d7f1a-... query=gophers
level=INFO msg="handler finished — sending response" request_id=9b3d7f1a-... result_count=3
</code></pre>
<p>The key is the <code>select</code> inside <code>Search</code>. It blocks on two channels simultaneously: <code>time.After(delay)</code> represents the slow query, and <code>ctx.Done()</code> represents the client. Whichever fires first wins. If the client disconnects, <code>ctx.Done()</code> closes and <code>Search</code> returns <code>context.Canceled</code> immediately, without waiting for the timer.</p>
<p>This example shows both things context is good for working together in one flow: the <strong>cancellation signal</strong> (<code>ctx.Done()</code>) stops the query when the client leaves, and the <strong>value</strong> (<code>request_id</code>) flows through every layer for correlated logging, all through the same single <code>ctx</code> argument.</p>
<h2>Database Calls: Enforcing Query Timeouts</h2>
<p>Most database drivers in Go accept a context. Pass one with a timeout to prevent slow queries from holding connections indefinitely.</p>
<pre><code class="language-go">func getUserByID(ctx context.Context, db *sql.DB, userID string) (*User, error) {
    // Give the query 3 seconds — no matter what the caller's deadline is
    queryCtx, cancel := context.WithTimeout(ctx, 3*time.Second)
    defer cancel()

    var user User
    err := db.QueryRowContext(queryCtx,
        "SELECT id, name, email FROM users WHERE id = $1", userID,
    ).Scan(&amp;user.ID, &amp;user.Name, &amp;user.Email)
    if err != nil {
        if errors.Is(err, context.DeadlineExceeded) {
            return nil, fmt.Errorf("user query timed out after 3s: %w", err)
        }
        return nil, fmt.Errorf("querying user %s: %w", userID, err)
    }

    return &amp;user, nil
}
</code></pre>
<p>Notice that <code>queryCtx</code> derives from <code>ctx</code> — the caller's context. If the caller's context is already canceled (client disconnected, Lambda timed out), <code>queryCtx</code> is canceled immediately regardless of the 3-second timeout. The child inherits the parent's cancellation, but can set a <em>tighter</em> deadline on top of it.</p>
<hr />
<h2>Checking for Cancellation in Long Loops</h2>
<p>If your function does significant work in a loop, check <code>ctx.Err()</code> periodically so it can exit early when canceled.</p>
<pre><code class="language-go">func processFiles(ctx context.Context, files []string) error {
    for _, file := range files {
        // Check at the top of each iteration
        if err := ctx.Err(); err != nil {
            return fmt.Errorf("processing canceled after %s: %w", file, err)
        }

        if err := processFile(ctx, file); err != nil {
            return fmt.Errorf("processing %s: %w", file, err)
        }
    }
    return nil
}
</code></pre>
<p>Without this check, a canceled context doesn't stop the loop — it only stops operations that accept and check the context themselves. If <code>processFile</code> takes 500ms and you have 1000 files, a cancellation mid-loop still runs all remaining iterations.</p>
<hr />
<h2>Common Mistakes and Gotchas</h2>
<p><strong>Passing</strong> <code>context.Background()</code> <strong>everywhere.</strong> It works, but it opts every operation out of cancellation and timeout propagation. If your HTTP handler times out, your database queries keep running. Pass the incoming context through your call chain — that's the whole point.</p>
<p><strong>Not calling</strong> <code>cancel()</code><strong>.</strong> Every <code>WithCancel</code>, <code>WithTimeout</code>, and <code>WithDeadline</code> must have its <code>cancel</code> called. The Go runtime cannot garbage-collect a context until cancel is called or the parent is canceled. <code>defer cancel()</code> right after creation is non-negotiable.</p>
<p><strong>Storing contexts in structs.</strong> The Go documentation is explicit: do not store contexts in structs. A context is for a single operation, not for the lifetime of an object. Pass it as the first argument to every function that needs it.</p>
<pre><code class="language-go">// Wrong
type Service struct {
    ctx context.Context // don't do this
}

// Right
func (s *Service) DoWork(ctx context.Context) error { ... }
</code></pre>
<p><strong>Using</strong> <code>context.WithValue</code> <strong>for function dependencies.</strong> If you're pulling a database client out of a context, something has gone wrong. Use dependency injection or package-level variables for clients and config. Context values are for request-scoped metadata.</p>
<p><strong>Ignoring</strong> <code>ctx.Err()</code> <strong>in loops.</strong> Passing a context to a function that calls <code>ctx.Err()</code> isn't enough if your own loop never checks it. Long-running loops need explicit cancellation checks.</p>
<p><strong>Wrapping errors without checking for cancellation.</strong> When a context-aware call fails, check whether the cause is cancellation before deciding how to handle it:</p>
<pre><code class="language-go">if err != nil {
    if errors.Is(err, context.Canceled) || errors.Is(err, context.DeadlineExceeded) {
        // The operation was stopped — not necessarily a bug
        return err
    }
    // Real error — log, alert, or return
    return fmt.Errorf("unexpected error: %w", err)
}
</code></pre>
<hr />
<h2>Summary</h2>
<p>The <code>context</code> package gives every Go operation a standard way to answer three questions: should I keep running, when must I finish by, and what metadata flows with this request?</p>
<p>The key things to take away:</p>
<ul>
<li><p><code>context.Background()</code> is the root — use it at program entry points.</p>
</li>
<li><p><code>WithCancel</code>, <code>WithTimeout</code>, and <code>WithDeadline</code> create derived contexts — always <code>defer cancel()</code>.</p>
</li>
<li><p>Cancellation propagates from parent to child automatically — wire it through your call chain and it works for free.</p>
</li>
<li><p>Pass context as the first argument to every function that does I/O — HTTP, database, AWS SDK, gRPC.</p>
</li>
<li><p><code>WithValue</code> is for cross-cutting metadata like trace IDs, not for dependencies.</p>
</li>
<li><p>Check <code>ctx.Err()</code> explicitly in long-running loops.</p>
</li>
</ul>
<hr />
<h2>Let's connect!</h2>
<p>One of the best parts of writing in public is the people you meet along the way, engineers at different stages of their journey, working on similar problems from completely different angles.</p>
<p>If something in this post resonated, if you spotted a bug, or if you just want to talk Go, Kubernetes, Platform Engineering, DevOps, or whatever, I'm always happy to hear from you.</p>
<ul>
<li><p><a href="https://www.linkedin.com/in/ferrios/">LinkedIn</a></p>
</li>
<li><p><a href="https://github.com/FerRiosCosta">GitHub</a></p>
</li>
<li><p><a href="https://x.com/ferztyle">Twitter / X</a></p>
</li>
</ul>
<p><em>Building from Asunción, Paraguay 🇵🇾</em></p>
]]></content:encoded></item><item><title><![CDATA[Go Packages and Modules explained]]></title><description><![CDATA[Learn how Go packages and modules work, how go.mod and go.sum relate to your code, and how to structure a real Go project with practical examples.]]></description><link>https://ferztyle.me/go-packages-and-modules-explained</link><guid isPermaLink="true">https://ferztyle.me/go-packages-and-modules-explained</guid><category><![CDATA[golang]]></category><category><![CDATA[Golang developer]]></category><category><![CDATA[golang package]]></category><dc:creator><![CDATA[Fer]]></dc:creator><pubDate>Mon, 01 Jun 2026 13:58:58 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/61db385c3ce4b2377adfdcda/da00503c-8623-4aed-8515-53cba26a39e3.jpg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h1>What is a package?</h1>
<p>In Go, every Go program is made up of packages. A package is a directory of <code>.go</code> files that share the same <code>package</code> declaration. The primary purpose of packages is to help you isolate and reuse code.</p>
<pre><code class="language-plaintext">myapp/
├── main.go       ← package main
└── math/
    ├── add.go    ← package math
    └── sub.go    ← package math
</code></pre>
<p>Both <code>add.go</code> and <code>sub.go</code> declare <code>package math</code>. They can call each other's functions directly — no import needed within the same package.</p>
<p>Inside a package, every <code>.go</code> file should begin with a <code>package {name}</code> statement which indicates the name of the package that the file is a part of. Every exported identifier (capitalized name) in that directory is accessible to anyone who imports the package.</p>
<p>Here's what that looks like in practice:</p>
<pre><code class="language-go">// math/add.go
package math

// pi is an unexported variable.
var pi = 3.14159

// Add returns the sum of two integers.
// Exported — starts with a capital letter.
func Add(a, b int) int {
    return a + b
}
</code></pre>
<pre><code class="language-go">// math/sub.go
package math

// Exported — starts with a capital letter.
func Subtract(a, b int) int {
    
    return a-b
}
</code></pre>
<pre><code class="language-go">// main.go
package main

import (
    "fmt"
    "github.com/yourname/myapp/math"
)

func main() {
    fmt.Println(math.Add(3, 4))      // 7
    fmt.Println(math.Subtract(10, 3)) // 7
    // fmt.Println(math.pi) — compile error: unexported
}
</code></pre>
<p>Two rules to remember:</p>
<ul>
<li><p>Capital letter = exported (public). Lowercase = unexported (private to the package).</p>
</li>
<li><p>One package per directory. One directory per package.</p>
</li>
</ul>
<hr />
<h1>What is a module?</h1>
<p>If a package is a folder, a module is the whole project — a tree of packages with a name, a Go version requirement, and a list of external dependencies.</p>
<p>When you start a Go project, you create a module, and inside that module, there will be packages.</p>
<p>Every Go project has exactly one <code>go.mod</code> file at its root. That file defines the module. Here's what a real one looks like:</p>
<pre><code class="language-plaintext">module github.com/yourname/weather-cli

go 1.21

require (
    github.com/aws/aws-sdk-go-v2 v1.24.0
    github.com/aws/aws-sdk-go-v2/service/s3 v1.47.0
    gopkg.in/yaml.v3 v3.0.1
)
</code></pre>
<p>Three things in every <code>go.mod</code>:</p>
<ul>
<li><p><code>module</code> — the module path. This is the base import path for every package in your project. It's usually your GitHub URL, but it can be anything.</p>
</li>
<li><p><code>go</code> — the minimum Go version your code requires.</p>
</li>
<li><p><code>require</code> — the external dependencies your module needs, each pinned to an exact version.</p>
</li>
</ul>
<h2>go.sum — the lockfile</h2>
<p>Alongside <code>go.mod</code> lives <code>go.sum</code>. You never edit this by hand. It contains cryptographic checksums for every dependency (and their dependencies) your module uses:</p>
<pre><code class="language-plaintext">github.com/aws/aws-sdk-go-v2 v1.24.0 h1:xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx=
github.com/aws/aws-sdk-go-v2 v1.24.0/go.mod h1:xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx=
</code></pre>
<p><code>go.sum</code> guarantees that the code you download is bit-for-bit identical to what was there when you first added the dependency. It's your protection against supply chain attacks and "works on my machine" problems. Always commit both <code>go.mod</code> and <code>go.sum</code>.</p>
<h1>Working with modules day to day</h1>
<h2>Creating a new module</h2>
<p>So, let's say you want to start a new project: you create the folder first, then you create your go.mod file, passing your module path to it (github.com/yourname/myapp).</p>
<pre><code class="language-bash">mkdir myapp &amp;&amp; cd myapp
go mod init github.com/yourname/myapp
</code></pre>
<p>This creates <code>go.mod</code> with your module path. That's it — you're ready to write Go.</p>
<h2>Adding a dependency</h2>
<pre><code class="language-bash">go get github.com/aws/aws-sdk-go-v2/service/s3@latest
</code></pre>
<p><code>go get</code> does three things: downloads the package, adds it to <code>go.mod</code>, and updates <code>go.sum</code>. After running it your <code>go.mod</code> will have a new <code>require</code> entry.</p>
<p>You can also just write the import in your code and run <code>go mod tidy</code> — it figures out what's missing and adds it:</p>
<pre><code class="language-bash">go mod tidy
</code></pre>
<p><code>go mod tidy</code> is the command you'll run most often. It adds missing dependencies and removes unused ones, keeping <code>go.mod</code> clean.</p>
<h2>Upgrading a dependency</h2>
<pre><code class="language-bash"># Upgrade to the latest minor/patch version
go get github.com/aws/aws-sdk-go-v2@latest

# Upgrade to a specific version
go get github.com/aws/aws-sdk-go-v2@v1.25.0
</code></pre>
<h2>Removing a dependency</h2>
<p>Remove the import from your code, then run:</p>
<pre><code class="language-bash">go mod tidy
</code></pre>
<p><code>go mod tidy</code> will remove the <code>require</code> entry automatically if nothing in your code imports it anymore.</p>
<h2>Viewing your dependency tree</h2>
<pre><code class="language-bash">go mod graph
</code></pre>
<p>This prints the full dependency graph — your dependencies, their dependencies, and so on. Useful for debugging version conflicts.</p>
<h2>Vendoring dependencies</h2>
<p>For environments without internet access (some CI setups, air-gapped servers), you can vendor all dependencies into a local <code>vendor/</code> directory:</p>
<pre><code class="language-bash">go mod vendor
</code></pre>
<p>After vendoring, <code>go build</code> uses <code>vendor/</code> instead of the module cache. Commit <code>vendor/</code> to your repo and your build never needs to call the internet.</p>
<hr />
<h1>How modules and packages connect</h1>
<p>Let's make the relationship tangible. Say you run:</p>
<pre><code class="language-bash">go get github.com/spf13/cobra@v1.8.0
</code></pre>
<p>Your <code>go.mod</code> now contains:</p>
<pre><code class="language-plaintext">require (
    github.com/spf13/cobra v1.8.0
)
</code></pre>
<p>Cobra is a <strong>module</strong> at <code>github.com/spf13/cobra</code>. Inside that module, there are multiple <strong>packages</strong>:</p>
<pre><code class="language-plaintext">github.com/spf13/cobra          ← the root package
github.com/spf13/cobra/doc      ← generates documentation
github.com/spf13/cobra/completions ← shell completions
</code></pre>
<p>When you import <code>github.com/spf13/cobra</code> in your code, you're importing one specific package from that module. The module is what gets versioned and downloaded; the package is what you actually use in your code.</p>
<pre><code class="language-go">import (
    "github.com/spf13/cobra"     // imports the root package of the cobra module
)
</code></pre>
<p>One <code>require</code> in <code>go.mod</code>, many importable packages available. That's the module/package split.</p>
<hr />
<h1>Package main is special</h1>
<p>Every Go program needs exactly one <code>package main</code> with exactly one <code>main()</code> function. That's the entry point. Everything else is a library package — it exports functions and types but can't be run directly.</p>
<pre><code class="language-go">// This is a runnable program
package main

import "fmt"

func main() {
    fmt.Println("hello from main")
}
</code></pre>
<pre><code class="language-go">// This is a library — can't be run, only imported
package greet

import "fmt"

func Hello(name string) string {
    return fmt.Sprintf("Hello, %s!", name)
}
</code></pre>
<p>You can have multiple <code>package main</code> files in a project — but each one must live in its own directory. This is exactly what the <code>cmd/</code> convention is for, which we'll get to shortly.</p>
<h1>How imports work</h1>
<p>The import path is always: <strong>module path</strong> (from <code>go.mod</code>) <strong>+ directory path</strong> from the module root.</p>
<pre><code class="language-plaintext">module github.com/yourname/myapp   ← module path

myapp/
├── go.mod
└── internal/
    └── config/
        └── config.go              ← import path: github.com/yourname/myapp/internal/config
</code></pre>
<pre><code class="language-go">// Importing your own packages — always use the full module path
import "github.com/yourname/myapp/internal/config"

// Importing from the standard library — no module path needed
import "fmt"
import "net/http"
import "encoding/json"

// Importing a third-party package — use its full module path + sub-path
import "github.com/spf13/cobra"
import "github.com/aws/aws-sdk-go-v2/service/s3"
</code></pre>
<h2>Aliasing imports</h2>
<p>When two packages have the same name, or when a name is too long, you can alias the import:</p>
<pre><code class="language-go">import (
    "fmt"

    // Alias to avoid conflict with standard library math
    gomath "github.com/yourname/myapp/math"

    // Alias for readability
    yaml "gopkg.in/yaml.v3"
)

func main() {
    fmt.Println(gomath.Add(1, 2))
    _ = yaml.Marshal
}
</code></pre>
<h2>The blank identifier import</h2>
<p>Sometimes you import a package only for its side effects — database drivers are the classic example. The <code>_</code> alias tells Go "import this but don't use its name":</p>
<pre><code class="language-go">import (
    "database/sql"
    _ "github.com/lib/pq" // registers the postgres driver via init()
)
</code></pre>
<p>Without the <code>_</code>, Go's compiler would complain about an unused import and refuse to compile.</p>
<hr />
<h1>A practical project structure</h1>
<p>Here's a real structure that scales from small to large. This is what most production Go projects converge on:</p>
<pre><code class="language-plaintext">myapp/
├── go.mod
├── go.sum
├── Makefile
│
├── cmd/
│   ├── server/
│   │   └── main.go     ← the HTTP server entry point
│   └── worker/
│       └── main.go     ← the background worker entry point
│
├── internal/
│   ├── handler/
│   │   ├── handler.go
│   │   └── handler_test.go
│   ├── store/
│   │   ├── postgres.go
│   │   └── store.go
│   └── config/
│       └── config.go
│
└── pkg/
    └── validate/
        ├── validate.go
        └── validate_test.go
</code></pre>
<p>Let's walk through each directory.</p>
<h2>cmd/ — entry points</h2>
<p>One subdirectory per runnable binary. Each contains a single <code>main.go</code>. The <code>main.go</code> should do almost nothing except wire dependencies together and start the program.</p>
<pre><code class="language-go">// cmd/server/main.go
package main

import (
    "log/slog"
    "net/http"
    "os"

    "github.com/yourname/myapp/internal/config"
    "github.com/yourname/myapp/internal/handler"
    "github.com/yourname/myapp/internal/store"
)

func main() {
    cfg := config.Load()

    db, err := store.Connect(cfg.DatabaseURL)
    if err != nil {
        slog.Error("failed to connect to database", "error", err)
        os.Exit(1)
    }

    h := handler.New(db)

    slog.Info("starting server", "port", cfg.Port)
    if err := http.ListenAndServe(":"+cfg.Port, h); err != nil {
        slog.Error("server failed", "error", err)
        os.Exit(1)
    }
}
</code></pre>
<div>
<div>💡</div>
<div>No business logic in <code>main.go</code>. Ever. It's a wiring diagram, not an application.</div>
</div>

<h2>internal/ — private application code</h2>
<p>The <code>internal/</code> directory is enforced by the Go toolchain. Packages inside <code>internal/</code> can only be imported by code in the parent directory tree. Code outside your module cannot import them — not even if they find your repo on the internet.</p>
<p>This is how you keep implementation details private:</p>
<pre><code class="language-go">// internal/config/config.go
package config

import "os"

type Config struct {
    Port        string
    DatabaseURL string
    LogLevel    string
}

// Load reads config from environment variables.
// This is internal — callers outside this module can't import it.
func Load() Config {
    port := os.Getenv("PORT")
    if port == "" {
        port = "8080"
    }
    return Config{
        Port:        port,
        DatabaseURL: os.Getenv("DATABASE_URL"),
        LogLevel:    os.Getenv("LOG_LEVEL"),
    }
}
</code></pre>
<pre><code class="language-go">// internal/store/store.go
package store

import (
    "context"
    "database/sql"
    "fmt"

    _ "github.com/lib/pq"
)

// Store handles database operations.
type Store struct {
    db *sql.DB
}

func Connect(dsn string) (*Store, error) {
    db, err := sql.Open("postgres", dsn)
    if err != nil {
        return nil, fmt.Errorf("open db: %w", err)
    }
    if err := db.Ping(); err != nil {
        return nil, fmt.Errorf("ping db: %w", err)
    }
    return &amp;Store{db: db}, nil
}

// GetUser fetches a user by ID.
func (s *Store) GetUser(ctx context.Context, id string) (string, error) {
    var name string
    err := s.db.QueryRowContext(ctx, "SELECT name FROM users WHERE id = $1", id).Scan(&amp;name)
    if err != nil {
        return "", fmt.Errorf("get user %s: %w", id, err)
    }
    return name, nil
}
</code></pre>
<h2>pkg/ — reusable public code</h2>
<p><code>pkg/</code> contains packages that are safe to import by external projects. Put things here that are genuinely reusable across projects — validation logic, utility functions, shared types. If in doubt, use <code>internal/</code> instead.</p>
<pre><code class="language-go">// pkg/validate/validate.go
package validate

import (
    "errors"
    "strings"
)

// Email returns an error if the given string is not a valid email address.
// Simple check — not RFC 5322 compliant, but good enough for most cases.
func Email(email string) error {
    if email == "" {
        return errors.New("email is required")
    }
    if !strings.Contains(email, "@") || !strings.Contains(email, ".") {
        return errors.New("email is invalid")
    }
    return nil
}

// Required returns an error if the string is empty or whitespace only.
func Required(field, value string) error {
    if strings.TrimSpace(value) == "" {
        return fmt.Errorf("%s is required", field)
    }
    return nil
}
</code></pre>
<hr />
<h1>A practical example: a CLI tool</h1>
<p>GitHub Repository: <a href="https://github.com/FerRiosCosta/weather-cli">https://github.com/FerRiosCosta/weather-cli</a></p>
<p>Let's make this concrete with a small but complete project — a CLI that fetches weather for a city. It shows package structure, separation of concerns, and how packages talk to each other. Let's create the following directory structure:</p>
<pre><code class="language-plaintext">weather-cli/
├── go.mod
├── cmd/
│   └── weather/
│       └── main.go
└── internal/
    ├── api/
    │   └── api.go        ← HTTP client for weather API
    └── display/
        └── display.go    ← formats output for the terminal
</code></pre>
<p>Open your terminal and create the following directories and files:</p>
<pre><code class="language-shell">mkdir weather-cli
cd weather-cli
mkdir -p cmd/weather
touch cmd/weather/main.go
mkdir -p internal/api
touch internal/api/api.go
mkdir -p internal/display
touch internal/display/display.go
</code></pre>
<p>Open VSCode while you are in the weather-cli root directory:</p>
<pre><code class="language-shell">code .
</code></pre>
<p>Go to the <a href="https://openweathermap.org/faq#error401">Openweathermap</a> portal and create an account if you don't have one. Once you have created it, your API key will be enabled after a couple of hours.</p>
<p>Open a new terminal from VScode since we are going to run our program from here, but first we need to export our API KEY.</p>
<pre><code class="language-shell">export WEATHER_API_KEY=&lt;your-api-key&gt;
</code></pre>
<p>Now, initialize your module (or project) by running the following command:</p>
<pre><code class="language-shell">go mod init
</code></pre>
<p>You should see your new go.mod file created now:</p>
<pre><code class="language-go.mod">module github.com/FerRiosCosta/weather-cli

go 1.26.3
</code></pre>
<p>Start filling the files you created with the code below:</p>
<pre><code class="language-go">// internal/api/api.go
package api

import (
	"context"
	"encoding/json"
	"fmt"
	"net/http"
)

// WeatherResponse holds the data we care about from the API.
type WeatherResponse struct {
	City        string  `json:"name"`
	Temperature float64 `json:"main.temp"`
	Description string  `json:"weather.0.description"`
}

// apiResponse mirrors the actual nested JSON structure from OpenWeatherMap.
// Go's JSON decoder doesn't support dot notation like `json:"main.temp"` —
// nested fields require nested structs.
//
// The API returns something like:
//
//	{
//	  "name": "Asuncion",
//	  "main": { "temp": 28.4 },
//	  "weather": [{ "description": "partly cloudy" }]
//	}
type apiResponse struct {
	Name string `json:"name"`
	Main struct {
		Temp float64 `json:"temp"`
	} `json:"main"`
	Weather []struct {
		Description string `json:"description"`
	} `json:"weather"`
}

// Client makes requests to the weather API.
type Client struct {
	apiKey     string
	httpClient *http.Client
}

// NewClient creates and returns a new Client configured with the given API key.
// This is a constructor function — Go doesn't have classes or `new` keywords,
// so by convention we define a function named New&lt;TypeName&gt; to build a struct.
func NewClient(apiKey string) *Client {
	return &amp;Client{
		// Store the API key so every request this client makes can use it.
		// It's set once here and reused — no need to pass it on every call.
		apiKey: apiKey,
		// Create a default HTTP client for making requests.
		// We initialize it here rather than inside GetWeather so it's
		// reused across calls — http.Client maintains a connection pool
		// internally, so reusing it is more efficient than creating a new
		// one each time.
		httpClient: &amp;http.Client{},
	}
}

// GetWeather fetches current weather for the given city.
func (c *Client) GetWeather(ctx context.Context, city string) (*WeatherResponse, error) {
	url := fmt.Sprintf(
		"https://api.openweathermap.org/data/2.5/weather?q=%s&amp;appid=%s&amp;units=metric",
		city, c.apiKey,
	)

	req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
	if err != nil {
		return nil, fmt.Errorf("create request: %w", err)
	}

	resp, err := c.httpClient.Do(req)
	if err != nil {
		return nil, fmt.Errorf("fetch weather: %w", err)
	}
	defer resp.Body.Close()

	if resp.StatusCode != http.StatusOK {
		return nil, fmt.Errorf("unexpected status: %d", resp.StatusCode)
	}

	// Decode into the nested API struct first.
	var raw apiResponse
	if err := json.NewDecoder(resp.Body).Decode(&amp;raw); err != nil {
		return nil, fmt.Errorf("decode response: %w", err)
	}

	// Guard against an empty weather array — the API should always return
	// at least one entry, but defensive code is good code.
	description := ""
	if len(raw.Weather) &gt; 0 {
		description = raw.Weather[0].Description
	}

	// Return the clean, flat struct callers actually care about.
	return &amp;WeatherResponse{
		City:        raw.Name,
		Temperature: raw.Main.Temp,
		Description: description,
	}, nil
}
</code></pre>
<pre><code class="language-go">// internal/display/display.go
package display

import (
    "fmt"
    "io"

    "github.com/yourname/weather-cli/internal/api"
)

// Weather prints a formatted weather summary to w.
func Weather(w io.Writer, data *api.WeatherResponse) {
    fmt.Fprintf(w, "City:        %s\n", data.City)
    fmt.Fprintf(w, "Temperature: %.1f°C\n", data.Temperature)
    fmt.Fprintf(w, "Conditions:  %s\n", data.Description)
}
</code></pre>
<pre><code class="language-go">// cmd/weather/main.go
package main

import (
    "context"
    "log/slog"
    "os"

    "github.com/yourname/weather-cli/internal/api"
    "github.com/yourname/weather-cli/internal/display"
)

func main() {
    if len(os.Args) &lt; 2 {
        fmt.Fprintln(os.Stderr, "usage: weather &lt;city&gt;")
        os.Exit(1)
    }

    city := os.Args[1]
    apiKey := os.Getenv("WEATHER_API_KEY")
    if apiKey == "" {
        slog.Error("WEATHER_API_KEY environment variable is required")
        os.Exit(1)
    }

    client := api.NewClient(apiKey)

    weather, err := client.GetWeather(context.Background(), city)
    if err != nil {
        slog.Error("failed to get weather", "city", city, "error", err)
        os.Exit(1)
    }

    display.Weather(os.Stdout, weather)
}
</code></pre>
<p>Run it:</p>
<pre><code class="language-bash">go run ./cmd/weather Asuncion
</code></pre>
<pre><code class="language-plaintext">City:        Asuncion
Temperature: 28.4°C
Conditions:  partly cloudy
</code></pre>
<p>Notice how each package has one job:</p>
<ul>
<li><p><code>api</code> — knows how to talk to the weather API. Nothing else.</p>
</li>
<li><p><code>display</code> — knows how to format output. Nothing else.</p>
</li>
<li><p><code>cmd/weather/main.go</code> — wires them together. Nothing else.</p>
</li>
</ul>
<p>Adding a second output format (JSON, CSV) means a new file in <code>display/</code>. Adding a second weather provider means a new file in <code>api/</code>. Neither change touches the other.</p>
<hr />
<h1>Common gotchas</h1>
<p><strong>1. Circular imports — Go forbids them</strong></p>
<p>Package A cannot import package B if package B imports package A. Go will refuse to compile.</p>
<pre><code class="language-plaintext">// This will not compile
package a imports package b
package b imports package a  ← circular — error
</code></pre>
<p>The fix: extract the shared type into a third package that neither A nor B imports from each other.</p>
<p><strong>2. Package name vs directory name</strong></p>
<p>The directory name and the package name don't have to match — but they should. The one common exception is <code>main</code>: the directory is usually named after the binary (<code>server</code>, <code>worker</code>, <code>weather</code>), but the package is always <code>package main</code>.</p>
<pre><code class="language-go">// Directory: cmd/server/
// File: main.go
package main  // always "main", not "server"
</code></pre>
<p><strong>3. Trying to have multiple packages in one directory</strong></p>
<p>Every <code>.go</code> file in a directory must declare the same package name (with the exception of <code>_test.go</code> files, which can use <code>package foo_test</code> for black-box testing). This is a compile error:</p>
<pre><code class="language-plaintext">myapp/
├── server.go    ← package server
└── handler.go   ← package handler  ← ERROR: can't mix packages in one directory
</code></pre>
<p><strong>4. Exporting by accident</strong></p>
<p>If you capitalize a function name, it's exported — immediately accessible to anyone who imports the package. This isn't always what you want, especially for internal helpers. Default to lowercase until you know something needs to be public.</p>
<hr />
<h1>Summary</h1>
<p>Go's package and module system is built on a few simple rules that compound into something powerful.</p>
<p>Four things to take away:</p>
<ul>
<li><p>A <strong>package</strong> is a folder — everything in it shares a namespace, capital letters are exported.</p>
</li>
<li><p>A <strong>module</strong> is a versioned collection of packages — defined by <code>go.mod</code>, locked by <code>go.sum</code>.</p>
</li>
<li><p>Use <code>cmd/</code> for entry points, <code>internal/</code> for private code, <code>pkg/</code> for reusable public code.</p>
</li>
<li><p><code>go mod tidy</code> is your best friend — run it whenever you add, remove, or change dependencies.</p>
</li>
</ul>
<p>The project structure in this post is the same one I'll use for every project on this blog. Every Go + Lambda, Go + Kubernetes, and Go + AWS post builds on it. Once it's familiar, you'll recognize it instantly in any Go project you open on GitHub.</p>
<hr />
<h2>Let's connect!</h2>
<p>One of the best parts of writing in public is the people you meet along the way, engineers at different stages of their journey, working on similar problems from completely different angles.</p>
<p>If something in this post resonated, if you spotted a bug, or if you just want to talk Go, Kubernetes, Platform Engineering, DevOps, or whatever, I'm always happy to hear from you.</p>
<ul>
<li><p><a href="https://www.linkedin.com/in/ferrios/">LinkedIn</a></p>
</li>
<li><p><a href="https://github.com/FerRiosCosta">GitHub</a></p>
</li>
<li><p><a href="https://x.com/ferztyle">Twitter / X</a></p>
</li>
</ul>
<p><em>Building from Asunción, Paraguay 🇵🇾</em></p>
]]></content:encoded></item></channel></rss>