<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Abhishek Kushwaha on Medium]]></title>
        <description><![CDATA[Stories by Abhishek Kushwaha on Medium]]></description>
        <link>https://medium.com/@abhishekkushwaha11998?source=rss-5288bcd75b84------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*TndB2jjo4bx5jdlxZPhc3A.jpeg</url>
            <title>Stories by Abhishek Kushwaha on Medium</title>
            <link>https://medium.com/@abhishekkushwaha11998?source=rss-5288bcd75b84------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 20 Nov 2026 07:09:51 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@abhishekkushwaha11998/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[KubeAid: Stop Spending Hours on Kubernetes Debugging]]></title>
            <link>https://medium.com/@abhishekkushwaha11998/kubeaid-stop-spending-hours-on-kubernetes-debugging-77e3eee5d3fa?source=rss-5288bcd75b84------2</link>
            <guid isPermaLink="false">https://medium.com/p/77e3eee5d3fa</guid>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[cli]]></category>
            <category><![CDATA[debugging-tools]]></category>
            <category><![CDATA[debugging]]></category>
            <category><![CDATA[kubernetes]]></category>
            <dc:creator><![CDATA[Abhishek Kushwaha]]></dc:creator>
            <pubDate>Sun, 19 Apr 2026 09:27:06 GMT</pubDate>
            <atom:updated>2026-04-19T09:27:06.329Z</atom:updated>
            <content:encoded><![CDATA[<h4>The Problem: Kubernetes Troubleshooting is Slow and Painful</h4><p>You deploy a service to your Kubernetes cluster. Something breaks. Now what?</p><p>You find yourself jumping between multiple kubectl commands — check pod status, dive into logs, look at recent events, inspect resource requests, hunt for correlated errors across containers. By the time you’ve gathered all the context, 30 minutes have passed. Then you have to figure out the fix.</p><p>This workflow hasn’t changed in years, even though we now have AI.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TLfe_WpUsDsm1YmvUwBVAA.png" /></figure><h4>Introducing KubeAid: Diagnosis in One Command</h4><p>KubeAid is an open-source Kubernetes debugging CLI that does the legwork for you.</p><p>kube-debugger analyze my-app -n default</p><p>In seconds, you get a health score (0–100) based on pod status, events, logs, and resource signals — plus root cause analysis, actionable fix suggestions, and full report export in text, JSON, or HTML.</p><p>GitHub: <a href="https://github.com/Abhicodeitout/KubeAid">https://github.com/Abhicodeitout/KubeAid</a></p><h4>Instant Health Assessment</h4><p>KubeAid scans your pod’s state and gives it a score. A score of 87? Mostly fine. A 32? Something is very wrong — and KubeAid tells you exactly why, including what to run next.</p><h4>AI + Fallback Intelligence</h4><p>KubeAid supports Ollama (local) and Groq (cloud) for AI-assisted diagnostics. When AI is unavailable or disabled, built-in pattern matching kicks in automatically — making it fully CI/CD friendly.</p><h4>Continuous Monitoring with Watch Mode</h4><p>kube-debugger analyze my-app --watch --interval 10</p><p>Keep tabs on your app as you implement fixes. Exit with a specific code when health drops below a threshold — perfect for automated pipelines.</p><h4>CrashLoop Inspector</h4><p>kube-debugger crashloops -n default</p><p>Find all pods in CrashLoopBackOff and inspect their previous container logs without manual pod selection. Saves 5–10 minutes per incident.</p><h4>Reports for Sharing</h4><p>kube-debugger report my-app -f html -o report.html --open</p><p>Export polished HTML, JSON, or text reports. Diff against previous reports to track degradation over time. Create a GitHub issue directly with one flag.</p><h4>Real-World Scenarios</h4><p>Scenario 1 — Emergency Production Issue: Your monitoring alerts at 3 AM. Instead of running 15 commands, you run kube-debugger analyze production-service. 90 seconds later you see a memory leak in a recent deployment. You roll back and get back to sleep.</p><p>Scenario 2 — CI/CD Gate: Set a threshold in your deploy pipeline. If health drops below 80 after deploy, the pipeline fails automatically.</p><p>Scenario 3 — Post-Incident Review: Run a report before and after an incident. Diff the two JSON outputs to show exactly what changed and when recovery started.</p><h4>Installation</h4><p>Homebrew: brew tap abhicodeitout/tap &amp;&amp; brew install kube-debugger</p><p>Go install: go install github.com/Abhicodeitout/KubeAid/kube-debugger@latest</p><p>Supported on Linux, macOS, and Windows.</p><h4>What’s Next for KubeAid</h4><p>We’re building webhook alerts, multi-context cluster diagnostics, custom health score rules, and incident platform integrations. The roadmap is driven entirely by community feedback.</p><h4>Get Involved</h4><p>Star the repo, try it on a non-critical cluster, and file issues with your workflow needs.</p><p><a href="https://github.com/Abhicodeitout/KubeAid">https://github.com/Abhicodeitout/KubeAid</a></p><p>Have a Kubernetes debugging horror story? Drop it in the comments. We want to hear what would make your life easier.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=77e3eee5d3fa" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a learning ready BitTorrent Client from Scratch in Go]]></title>
            <link>https://medium.com/@abhishekkushwaha11998/building-a-learning-ready-bittorrent-client-from-scratch-in-go-79885f387f25?source=rss-5288bcd75b84------2</link>
            <guid isPermaLink="false">https://medium.com/p/79885f387f25</guid>
            <category><![CDATA[learning]]></category>
            <category><![CDATA[go]]></category>
            <category><![CDATA[torrent]]></category>
            <category><![CDATA[golang-development]]></category>
            <category><![CDATA[golang]]></category>
            <dc:creator><![CDATA[Abhishek Kushwaha]]></dc:creator>
            <pubDate>Thu, 16 Apr 2026 13:47:01 GMT</pubDate>
            <atom:updated>2026-04-16T13:47:01.539Z</atom:updated>
            <content:encoded><![CDATA[<p><em>How I implemented the full BitTorrent protocol stack — DHT, magnet links, BEP 9 metadata fetching, adaptive scheduling, and more — in pure Go with zero non-standard dependencies.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/304/1*Zddk_z-gF61n4OFqIyE0cw.jpeg" /></figure><h3>Why Build a BitTorrent Client?</h3><p>Most developers treat BitTorrent as a black box. You drag a .torrent file into qBittorrent, and files appear. But the protocol underneath is a sophisticated distributed system that solves some genuinely hard problems: peer discovery without a central server, content integrity verification, NAT traversal, choking fairness, and tail-completion efficiency.</p><p>I decided to build a fully functional, production-ready BitTorrent client in Go — not a toy, not a tutorial snippet, but something that actually downloads real torrents, including Ubuntu ISOs, from the public swarm. The result is a ~3,000-line codebase that implements the core BitTorrent BEPs (BitTorrent Enhancement Proposals) end to end.</p><p>GitHub: <a href="https://github.com/Abhicodeitout/Bit_torrent">github.com/Abhicodeitout/Bit_torrent</a></p><h3>What It Supports ?</h3><p>Before diving into implementation, here’s a summary of what the client can do:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/452/1*lv4rPTIXFHmQKKD3Ju4Apw.png" /></figure><h3>Architecture at a Glance</h3><pre>User input (.torrent file or magnet link)<br>         │<br>         ├─ .torrent ──► Bencode decode ──► TorrentInfo (pieces, files, trackers)<br>         │<br>         └─ magnet ───► Parse URI ──────────┐<br>                                            │<br>                    ┌───────────────────────▼──────────────────────┐<br>                    │         Peer Discovery (in order)             │<br>                    │  1. HTTP trackers  (BEP 3)                   │<br>                    │  2. UDP trackers   (BEP 15)                  │<br>                    │  3. DHT bootstrap  (BEP 5) — fallback        │<br>                    └───────────────────────┬──────────────────────┘<br>                                            │<br>                    ┌───────────────────────▼──────────────────────┐<br>                    │  BEP 10 Extension Handshake (magnet only)    │<br>                    │  BEP 9  ut_metadata fetch → SHA-1 verify     │<br>                    └───────────────────────┬──────────────────────┘<br>                                            │<br>                    ┌───────────────────────▼──────────────────────┐<br>                    │         Download Engine                       │<br>                    │  • Resume state + piece verification         │<br>                    │  • Rarest-first + endgame scheduling         │<br>                    │  • Long-lived sessions + pipelined requests  │<br>                    │  • Adaptive peer scoring / quarantine        │<br>                    │  • Inbound listener + upload serving         │<br>                    └───────────────────────┬──────────────────────┘<br>                                            │<br>                                   $HOME/Downloads/</pre><p>The project uses a clean internal/ layout with no circular dependencies and only one external library: github.com/jackpal/bencode-go for bencode encoding/decoding.</p><pre>internal/<br>├── dht/         # BEP 5 — Kademlia DHT peer discovery<br>├── protocol/    # Wire protocol, BEP 10 extension, BEP 9 metadata<br>├── tracker/     # HTTP (BEP 3) + UDP (BEP 15) tracker client<br>├── peer/        # Background peer discovery manager + inbound listener<br>├── state/       # Persistent resume state<br>├── types/       # Core data structures + .torrent/.magnet parser<br>├── downloader/  # Adaptive resumable download engine + telemetry<br>├── choke/       # Choking/unchoking round manager<br>├── portmap/     # UPnP + NAT-PMP abstraction<br>├── natpmp/      # NAT-PMP implementation<br>└── upnp/        # UPnP implementation</pre><h3>The BitTorrent Handshake</h3><p>Every peer connection starts with a 68-byte handshake:</p><pre>&lt;1 byte: pstrlen=19&gt;&lt;19 bytes: &quot;BitTorrent protocol&quot;&gt;<br>&lt;8 bytes: reserved (extension flags)&gt;<br>&lt;20 bytes: info_hash&gt;<br>&lt;20 bytes: peer_id&gt;</pre><p>The reserved bytes are what make extensions possible. Bit 20 of byte 6 (0-indexed) signals BEP 10 extension protocol support. Here’s how the client advertises it:</p><pre>func HandshakeExtended(conn net.Conn, infoHash [20]byte, peerID [20]byte) ([20]byte, bool, error) {<br>    reserved := [8]byte{0, 0, 0, 0, 0, 0x10, 0, 0}<br>    if err := WriteHandshakeWithReserved(conn, infoHash, peerID, reserved); err != nil {<br>        return [20]byte{}, false, err<br>    }<br>    remotePeerID, remoteReserved, err := ReadHandshakeFull(conn, infoHash)<br>    if err != nil {<br>        return [20]byte{}, false, err<br>    }<br>    return remotePeerID, remoteReserved[5]&amp;0x10 != 0, nil<br>}</pre><p>After the handshake, all communication happens through length-prefixed messages:</p><pre>&lt;4 bytes: message length&gt;&lt;1 byte: message ID&gt;&lt;payload&gt;</pre><p>The message IDs are standardised: 0=choke, 1=unchoke, 2=interested, 3=not-interested, 4=have, 5=bitfield, 6=request, 7=piece, 8=cancel, 20=extended.</p><h3>Peer Discovery: Three Layers</h3><p>Getting a list of peers to connect to is the first challenge. The client implements three layers, tried in order</p><h4>Layer 1 &amp; 2 — HTTP and UDP Trackers</h4><p>HTTP trackers (BEP 3) are simple: build a URL with info hash, peer ID, port, and event, make a GET request, bencode-decode the response.</p><p>UDP trackers (BEP 15) are faster and more common. The protocol is:</p><ol><li>Connect: send a magic 64-bit connection ID (0x41727101980), get back a real connection ID.</li><li>Announce: send info hash, peer ID, download stats, and event; get back a compact peer list.</li></ol><pre>// Connect phase — get a real connection ID from the tracker<br>connectReq := make([]byte, 16)<br>binary.BigEndian.PutUint64(connectReq[0:], 0x41727101980) // magic<br>binary.BigEndian.PutUint32(connectReq[8:], 0)             // action: connect<br>binary.BigEndian.PutUint32(connectReq[12:], txID)<br><br>conn.Write(connectReq)<br>conn.Read(connectResp)<br>connectionID := binary.BigEndian.Uint64(connectResp[8:])</pre><p>The announce phase then embeds this connection ID, the info hash, peer ID, downloaded/uploaded/left bytes, and the lifecycle event (started, completed, stopped).</p><h4>Layer 3 — DHT (BEP 5): Kademlia Peer Discovery</h4><p>DHT is the most interesting layer — it lets the client find peers <em>without any tracker at all</em>. It uses the Kademlia distributed hash table algorithm.</p><p>Key concepts:</p><ul><li>Every node has a random 160-bit ID.</li><li>Distance between nodes is defined as XOR of their IDs.</li><li>The network is self-organizing: nodes closer in XOR-space know more about keys in that space.</li></ul><p>The lookup algorithm is iterative:</p><ol><li>Start with the 4 public bootstrap nodes (router.bittorrent.com, router.utorrent.com, etc.).</li><li>Send get_peers(info_hash) to the alpha=3 closest unqueried nodes.</li><li>Each node returns either a list of peers (if it knows any), or a list of even-closer nodes.</li><li>Repeat with the new closer nodes until no closer nodes are returned or enough peers are found.</li></ol><pre>// Each round queries alpha=3 nodes in parallel<br>for _, c := range batch {<br>    wg.Add(1)<br>    go func(c *candidate) {<br>        defer wg.Done()<br>        pp, nn, err := krpcGetPeers(c.addr, localID, infoHash, 8*time.Second)<br>        if err != nil { return }<br>        addPeers(pp)<br>        addNodes(nn) // newly discovered nodes are sorted by XOR distance<br>    }(c)<br>}</pre><p>All communication uses KRPC — a bencode-encoded RPC protocol over UDP. The candidate list is kept sorted by XOR distance to ensure the lookup converges on the target.</p><h3>Magnet Links: Fetching Metadata from the Swarm (BEP 9)</h3><p>A magnet link gives you only the info hash and optionally some tracker URLs — no piece hashes, no file list. The torrent <em>metadata</em> (the info dictionary) has to be fetched from peers.</p><p>This is where BEP 10 + BEP 9 come together:</p><ol><li>BEP 10 extension handshake: After the BitTorrent handshake, exchange an extended message (ID 20) advertising which extensions you support. The peer replies with its own capability map, including the extension ID it assigned to ut_metadata.</li><li>BEP 9 ut_metadata: The metadata is split into 16 KiB blocks. Request each block by index, collect all blocks, concatenate, and SHA-1 hash the result — it must equal the info hash from the magnet link.</li></ol><pre>// Extension handshake payload (bencode)<br>{<br>    &quot;m&quot;: {&quot;ut_metadata&quot;: 1},<br>    &quot;metadata_size&quot;: 0<br>}<br><br>// Metadata request (after learning peer&#39;s extension IDs)<br>{<br>    &quot;msg_type&quot;: 0,   // request<br>    &quot;piece&quot;: &lt;block_index&gt;<br>}<br><br>// Assemble and verify<br>sha1.Sum(assembled) == infoHash  // must match</pre><p>The client probes multiple peers in parallel — the first one to return valid metadata wins.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/864/1*Q9kI5vFLYClLi7abXorWAA.png" /></figure><h3>The Download Engine: Adaptive Peer Scheduling</h3><p>Once we have the piece hashes, the actual download begins. This is the most complex part of the codebase.</p><h4>Rarest-First Scheduling</h4><p>To maximize swarm health, the client downloads the pieces that fewest peers have first. This ensures rare pieces are spread widely rather than becoming bottlenecks.</p><h4>Pipelined Block Requests</h4><p>Each piece is split into 16 KiB blocks. Instead of request→wait→receive→request, the client pipelines multiple requests to the same peer:</p><pre>→ Request block 0<br>→ Request block 1<br>→ Request block 2    (all in flight simultaneously)<br>← Receive block 0<br>← Receive block 1<br>→ Request block 3    (refill pipeline)<br>...</pre><p>This keeps the TCP pipe full and is critical for download speed.</p><h4>Adaptive Peer Scoring and Quarantine</h4><p>Not all peers are equal. Peers that time out, send corrupt data, or disconnect frequently get their score reduced and are eventually quarantined — temporarily excluded from new work assignments. This prevents a handful of bad peers from stalling the download.</p><h4>Endgame Mode</h4><p>Near the end of a download, a few pieces are held by only a handful of peers, and stalls are common. The client enters <em>endgame mode</em> when only a small number of pieces remain: it sends the same piece request to <em>multiple</em> peers simultaneously. When one delivers the piece, it sends cancel messages to the others. This dramatically reduces tail-completion time.</p><h4>SHA-1 Integrity Verification</h4><p>Every downloaded piece is verified against the SHA-1 hash from the .torrent file before being written to disk. A corrupt piece is discarded and re-queued. This makes the client robust against faulty peers and network corruption.</p><h4>Resumable Downloads and Persistent State</h4><p>The client saves download progress to a state file alongside the output. On restart, it reads the state file and verifies which pieces are already complete (by re-hashing from disk). Only incomplete pieces are downloaded, allowing interrupted downloads to resume seamlessly.</p><h3>UPnP and NAT-PMP: Becoming Reachable</h3><p>Most home users are behind NAT. Without port mapping, they can connect <em>out</em> to peers, but peers can’t connect <em>in</em> to them. The client implements both UPnP and NAT-PMP to automatically ask the home router to forward an external port to the client:</p><pre>if m, err := portmap.NewMapper(3 * time.Second); err == nil {<br>    if eip, _, err := m.MapPort(uint16(*listenPort)); err == nil {<br>        externalIP = eip  // announce this IP to trackers<br>    }<br>}<br>defer mapper.UnmapPort(uint16(*listenPort))</pre><p>The external IP is then used in tracker announces so remote peers can initiate connections — improving swarm participation.</p><h4>Tracker Lifecycle Events</h4><p>The BitTorrent spec requires clients to announce lifecycle events to trackers:</p><ul><li>started — first announce when the download begins</li><li>periodic — every ~4 minutes during the download (with live downloaded/uploaded/left counters)</li><li>completed — when the download finishes successfully</li><li>stopped — when the client exits (even on error, via defer)</li></ul><p>This is what allows trackers to maintain accurate peer counts and seed ratios.</p><h3>Private Torrent Safety</h3><p>Some torrents include a private=1 flag in the info dictionary. For these torrents, DHT and PEX (peer exchange) must be disabled — the torrent owner wants peer discovery to go through their tracker only. The client checks this flag and enforces the restriction throughout.</p><h4>Using the Client</h4><pre># Build<br>git clone https://github.com/Abhicodeitout/Bit_torrent.git<br>cd Bit_torrent<br>go build -o bin/torrent-client ./cmd/torrent-client/<br><br># Download from a .torrent file<br>./bin/torrent-client ubuntu-24.04.iso.torrent<br><br># Download from a magnet link<br>./bin/torrent-client &quot;magnet:?xt=urn:btih:AABBCCDD...&amp;tr=udp://tracker.opentrackr.org:1337/announce&quot;<br><br># Flags<br>./bin/torrent-client --verbose --listen-port 51413 file.torrent<br>./bin/torrent-client --quiet file.torrent<br>./bin/torrent-client --enable-nat=false file.torrent</pre><p>Files are saved to $HOME/Downloads/. Multi-file torrents are assembled into a subdirectory with the full original directory tree.</p><h3>Lessons Learned</h3><p>1. The protocol is deceptively layered. BEP 3 is the base, but without BEP 10, BEP 9, and BEP 15 you can barely function in the modern swarm. Plan to implement them together.</p><p>2. Peer quality varies enormously. A significant fraction of peers in the swarm are unreachable, silently drop connections, or send garbage. Robust timeout handling, scoring, and quarantine are not optional.</p><p>3. Endgame mode is not optional. Without it, the last few pieces of a large download can take longer than all the previous pieces combined.</p><p>4. Go is an excellent fit. Goroutines make pipelining and parallel peer probing natural. The standard library covers TCP, UDP, crypto/sha1, encoding/binary, and context — the only external dependency needed was a bencode library.</p><p>5. DHT is worth the complexity. The ability to download a torrent with no tracker at all — just a 40-character hex string — is remarkable. The Kademlia paper is dense but the implementation is manageable once you understand XOR distance and iterative lookup.</p><h3>What’s Next</h3><ul><li>Seeding: The upload path for outbound connections is partially implemented. Full seeding support is the next major milestone.</li><li>Web UI: A real-time progress dashboard.</li><li>Streaming: Prioritize pieces in sequential order for media files.</li></ul><h3>Try It</h3><p>The full source is on GitHub: <a href="https://github.com/Abhicodeitout/Bit_torrent">github.com/Abhicodeitout/Bit_torrent</a></p><p>Even you can contribute to this development.</p><p>It builds with a single go build command and has no system dependencies. Tested on Linux, macOS, and Windows against real public torrents.</p><p>If you’re interested in distributed systems, peer-to-peer protocols, or just want to see how Go handles network-heavy concurrent code — clone it, read through it, and download something.</p><p><em>If you found this useful, leave a clap and follow for more systems-programming deep dives.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=79885f387f25" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Kubernetes v1.35: Timbernetes — The World Tree Release]]></title>
            <link>https://medium.com/@abhishekkushwaha11998/kubernetes-v1-35-timbernetes-the-world-tree-release-7229c780749b?source=rss-5288bcd75b84------2</link>
            <guid isPermaLink="false">https://medium.com/p/7229c780749b</guid>
            <category><![CDATA[kubectl]]></category>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[k8s]]></category>
            <category><![CDATA[new-releases]]></category>
            <category><![CDATA[technology]]></category>
            <dc:creator><![CDATA[Abhishek Kushwaha]]></dc:creator>
            <pubDate>Thu, 18 Dec 2025 16:59:52 GMT</pubDate>
            <atom:updated>2025-12-18T16:59:53.612Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>Building stronger roots for the cloud‑native ecosystem</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*Qxd1HadwZecFVbwcZShTSA.webp" /></figure><p>On December 17, 2025, the Kubernetes community released Kubernetes v1.35, codenamed Timbernetes — The World Tree Release. Inspired by the mythological Yggdrasil, the World Tree that connects all realms, this release reflects Kubernetes’ role as the central backbone of modern cloud‑native infrastructure.</p><p>With contributions from 419 developers across more than 85 organizations, Kubernetes v1.35 delivers 60 enhancements across stable, beta, and alpha maturity levels. The focus of this release is clear:</p><ul><li>Greater workload flexibility</li><li>Improved security and identity primitives</li><li>Cleaner, more predictable operations at scale</li></ul><p>Timbernetes is not just an incremental update — it is a structural reinforcement of the Kubernetes ecosystem.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*ZdopftyjGRHRQk2F8zWTVg.jpeg" /></figure><h3>🌳 Why “Timbernetes” Matters</h3><p>The Timbernetes release emphasizes growth with stability. Just as a tree needs deep roots and flexible branches, Kubernetes continues to strengthen its core while enabling modern workload patterns such as AI/ML pipelines, stateful services, and large‑scale distributed systems.</p><p>Key themes of Kubernetes v1.35 include:</p><ul><li>Non‑disruptive resource management</li><li>Native workload identity and security improvements</li><li>Smarter scheduling and traffic control</li><li>Removal of long‑standing technical debt</li></ul><p>Together, these changes make Kubernetes more resilient, secure, and easier to operate in real‑world production environments.</p><h3>✅ Stable Features: Production‑Ready Improvements</h3><p>In‑Place Pod Resource Updates (GA)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BaUmtCHEmlC86wAxuMawjA.jpeg" /></figure><p>One of the most impactful features graduating to General Availability is in‑place Pod resource updates. This allows CPU and memory requests or limits to be modified for running Pods without requiring a restart.</p><p>This is a major operational win, especially for:</p><ul><li>Stateful workloads</li><li>Latency‑sensitive services</li><li>Long‑running batch jobs</li></ul><p>By eliminating unnecessary restarts, teams gain better resource utilization, reduced downtime, and safer performance tuning in production.</p><p><strong>PreferSameNode Traffic Distribution</strong></p><p>Kubernetes Services can now prefer routing traffic to endpoints on the same node before falling back to others. This improves:</p><ul><li>Network latency</li><li>Cache locality</li><li>Overall application performance</li></ul><p>For performance‑critical and node‑local workloads, this feature delivers immediate benefits with minimal configuration changes.</p><h3>🔄 Beta Features: Powerful Capabilities You Can Adopt Today</h3><p><strong>Native Pod Certificates for Workload Identity</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VcY0UA8BpEQj79YqI8gK0Q.png" /></figure><p>Kubernetes v1.35 introduces native Pod certificate provisioning in beta, enabling:</p><ul><li>Automatic certificate issuance and rotation</li><li>Native mTLS support between services</li><li>Reduced reliance on external certificate management tools</li></ul><p>This enhancement moves Kubernetes closer to first‑class zero‑trust networking, simplifying secure service‑to‑service communication.</p><p><strong>Additional Beta Enhancements</strong></p><p>Other notable beta features include:</p><ul><li>Downward API support for node topology labels, improving workload awareness.</li><li>Built‑in storage version migration, simplifying CRD evolution.</li><li>Configurable Horizontal Pod Autoscaler tolerances for fine‑grained scaling control.</li><li>User namespaces in Pods, strengthening container isolation.</li><li>Credential verification for cached images, improving multi‑tenant security.</li></ul><p>These features collectively improve security posture, observability, and operational control.</p><h3>🌱 Alpha Features: Shaping the Future of Kubernetes</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NwAr66Qyb2Pf2bDl6NDASw.jpeg" /></figure><p>Kubernetes v1.35 also introduces several alpha features that hint at the platform’s future direction.</p><p><strong>Gang Scheduling</strong></p><p>Gang scheduling allows a group of Pods to be scheduled together — or not at all. This is critical for:</p><ul><li>AI/ML training workloads.</li><li>High‑performance computing (HPC).</li><li>Distributed batch and data processing.</li></ul><p><strong>Other Alpha Highlights</strong></p><ul><li>Node‑declared features, preventing scheduling mismatches across versions.</li><li>Enhanced /flagz JSON output, improving component observability</li><li>Extended toleration operators for SLA‑aware scheduling</li><li>Mutable resources for suspended Jobs, simplifying recovery workflows</li></ul><p>While experimental, these features address real‑world challenges faced by advanced platform teams.</p><h3>⚠️ Deprecations and Breaking Changes</h3><p>Timbernetes also focuses on cleanup and modernization:</p><ul><li>cgroup v1 support has been fully removed — clusters must run on cgroup v2.</li><li>Ingress NGINX is moving toward archival status, with the Gateway API positioned as the long‑term replacement.</li></ul><p>These changes may require proactive planning, but they result in a cleaner, more future‑proof Kubernetes platform.</p><h3>🛠️ Operational Considerations Before Upgrading</h3><p>Before upgrading to Kubernetes v1.35, teams should:</p><ul><li>Validate node OS compatibility with cgroup v2.</li><li>Test RBAC permissions related to kubectl exec.</li><li>Review memory resize policies for sensitive workloads.</li></ul><p>As with every major release, upgrades should be tested thoroughly in non‑production environments.</p><h3><strong>🌟 Conclusion</strong></h3><p>Kubernetes v1.35: Timbernetes — The World Tree Release represents a meaningful step forward in the platform’s evolution. With production‑ready improvements, maturing security features, and forward‑looking innovations, this release reinforces Kubernetes as the foundation of modern cloud‑native systems.</p><p>For platform engineers, DevOps teams, and cloud architects, v1.35 delivers both immediate operational value and a clear signal of where Kubernetes is headed next.</p><p><em>If you are building or operating Kubernetes at scale, Timbernetes is a release worth exploring.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7229c780749b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ Train an Open-Source LLM with Your Own Data — Simple Guide with Code]]></title>
            <link>https://medium.com/@abhishekkushwaha11998/train-an-open-source-llm-with-your-own-data-simple-guide-with-code-a20f94df2337?source=rss-5288bcd75b84------2</link>
            <guid isPermaLink="false">https://medium.com/p/a20f94df2337</guid>
            <category><![CDATA[finetune-llm]]></category>
            <category><![CDATA[machine-learning-ai]]></category>
            <category><![CDATA[llama-3]]></category>
            <category><![CDATA[llm-training]]></category>
            <category><![CDATA[mistral-7b]]></category>
            <dc:creator><![CDATA[Abhishek Kushwaha]]></dc:creator>
            <pubDate>Fri, 29 Aug 2025 07:24:01 GMT</pubDate>
            <atom:updated>2025-08-29T07:24:01.965Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hIRGDU20TwsvjyIAQfX9_Q.avif" /></figure><h3>🧠 Train an Open-Source LLM with Your Own Data — Simple Guide with Code</h3><p>Want to teach an AI to talk like your business, summarize legal text, or answer questions from your docs? You don’t need to build a model from scratch. You can <strong>fine-tune an existing open-source LLM</strong> (like LLaMA or Mistral) on your own dataset — even with just one GPU.</p><p>Let’s go step-by-step. I’ll walk you through <strong>from zero to fine-tuning</strong>, with real Python code and examples.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*m43zPbw_0EfGOsH8M79-4A.png" /></figure><h3>🔧 What You’ll Need</h3><h4>✅ Tools/Packages to Install:</h4><pre>pip install transformers datasets peft accelerate bitsandbytes trl</pre><ul><li>transformers: To load and fine-tune models.</li><li>datasets: To load your data.</li><li>peft: For efficient fine-tuning (LoRA).</li><li>bitsandbytes: For quantization (makes big models run on small GPUs).</li><li>trl: Trainer for fine-tuning LLMs like ChatGPT-style.</li></ul><h4>🗃 Step 1: Prepare Your Data</h4><p>Your data should look like this (JSON Lines format):</p><pre>{&quot;instruction&quot;: &quot;Translate English to French&quot;, &quot;input&quot;: &quot;I love AI.&quot;, &quot;output&quot;: &quot;J&#39;aime l&#39;IA.&quot;}<br>{&quot;instruction&quot;: &quot;Summarize the text&quot;, &quot;input&quot;: &quot;OpenAI built ChatGPT.&quot;, &quot;output&quot;: &quot;ChatGPT was made by OpenAI.&quot;}</pre><p>Name this file something like data.json.</p><h4>🧠 Step 2: Load a Base Model (like Mistral or LLaMA 2)</h4><p>We’ll use <strong>Mistral-7B-Instruct</strong> — a fast and powerful open-source model.</p><pre>from transformers import AutoModelForCausalLM, AutoTokenizer<br>from peft import get_peft_model, LoraConfig, TaskType<br>model_id = &quot;mistralai/Mistral-7B-Instruct-v0.2&quot;<br>tokenizer = AutoTokenizer.from_pretrained(model_id)<br>model = AutoModelForCausalLM.from_pretrained(<br>    model_id,<br>    load_in_4bit=True,  # saves memory<br>    device_map=&quot;auto&quot;<br>)</pre><h4>💡 Step 3: Apply LoRA for Lightweight Training</h4><p>LoRA helps you <strong>fine-tune big models fast</strong> — without changing all the weights.</p><pre>from peft import LoraConfig, get_peft_model<br>lora_config = LoraConfig(<br>    r=8,<br>    lora_alpha=16,<br>    target_modules=[&quot;q_proj&quot;, &quot;v_proj&quot;],  # fine-tune attention only<br>    lora_dropout=0.05,<br>    bias=&quot;none&quot;,<br>    task_type=TaskType.CAUSAL_LM<br>)<br>model = get_peft_model(model, lora_config)</pre><h4>📚 Step 4: Load Your Dataset</h4><p>Use Hugging Face’s datasets to read and split the JSONL file.</p><pre>from datasets import load_dataset<br>dataset = load_dataset(&quot;json&quot;, data_files=&quot;data.jsonl&quot;, split=&quot;train&quot;)<br>dataset = dataset.train_test_split(test_size=0.1)</pre><h4>🏋️ Step 5: Train the Model (Using TRL’s SFT Trainer)</h4><pre>from trl import SFTTrainer<br>from transformers import TrainingArguments<br>training_args = TrainingArguments(<br>    output_dir=&quot;./finetuned-mistral&quot;,<br>    per_device_train_batch_size=2,<br>    num_train_epochs=3,<br>    logging_steps=10,<br>    save_strategy=&quot;epoch&quot;,<br>    fp16=True,<br>)<br>trainer = SFTTrainer(<br>    model=model,<br>    args=training_args,<br>    train_dataset=dataset[&quot;train&quot;],<br>    eval_dataset=dataset[&quot;test&quot;],<br>    tokenizer=tokenizer,<br>    packing=True,<br>    max_seq_length=512,<br>)<br>trainer.train()</pre><h4>🧪 Step 6: Test It!</h4><p>After training, let’s try it out:</p><pre>prompt = &quot;### Instruction:\nTranslate English to French\n\n### Input:\nI love pizza\n\n### Response:\n&quot;<br>inputs = tokenizer(prompt, return_tensors=&quot;pt&quot;).to(&quot;cuda&quot;)<br>outputs = model.generate(**inputs, max_new_tokens=50)<br>print(tokenizer.decode(outputs[0], skip_special_tokens=True))</pre><h4>💾 Optional: Save and Use the Model Later</h4><pre>model.save_pretrained(&quot;./my-custom-llm&quot;)<br>tokenizer.save_pretrained(&quot;./my-custom-llm&quot;)</pre><p>You can reload it any time with from_pretrained.</p><h3>💡 Bonus Tips</h3><ul><li>If you have a weak GPU (&lt;=12GB), use 4-bit quantization (load_in_4bit=True)</li><li>If your dataset is large, use streaming and gradient checkpointing</li><li>For chat-style output, format your prompts with ### Instruction:\n...\n### Response:</li></ul><h3>🚀 Fine-Tune an Open Source LLM with Your Own Data (Mistral + LoRA Example)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/311/1*sGX66oYAHCpAum7slr5BrA.png" /></figure><h4>📦 Install All Required Packages</h4><pre>pip install transformers datasets peft accelerate bitsandbytes trl</pre><h4>✅ Step 1: Load the Pretrained Model and Tokenizer (Mistral)</h4><pre>from transformers import AutoModelForCausalLM, AutoTokenizer<br>import torch<br>model_id = &quot;mistralai/Mistral-7B-Instruct-v0.2&quot;<br>tokenizer = AutoTokenizer.from_pretrained(model_id)<br>model = AutoModelForCausalLM.from_pretrained(<br>    model_id,<br>    load_in_4bit=True,  # saves memory<br>    device_map=&quot;auto&quot;,  # auto detects GPU<br>    torch_dtype=torch.float16<br>)</pre><h4>💬 Step 2: Generate Output from the Pretrained Model (Before Fine-Tuning)</h4><pre>prompt = &quot;&quot;&quot;### Instruction:<br>Summarize this article in one sentence.### Input:<br>Open-source models like Mistral and LLaMA allow users to customize large language models using their own data.<br>### Response:<br>&quot;&quot;&quot;<br>inputs = tokenizer(prompt, return_tensors=&quot;pt&quot;).to(&quot;cuda&quot;)<br>outputs = model.generate(<br>    **inputs,<br>    max_new_tokens=100,<br>    do_sample=True,<br>    temperature=0.7,<br>    top_p=0.9<br>)<br>response = tokenizer.decode(outputs[0], skip_special_tokens=True)<br>print(response)<br></pre><p>🧠 You now know how the base model behaves before fine-tuning.</p><h4>🗃️ Step 3: Prepare Your Custom Dataset</h4><p>Make a file called data.jsonl with instruction-style entries:</p><pre>{&quot;instruction&quot;: &quot;Translate English to French&quot;, &quot;input&quot;: &quot;Good morning&quot;, &quot;output&quot;: &quot;Bonjour&quot;}<br>{&quot;instruction&quot;: &quot;Summarize&quot;, &quot;input&quot;: &quot;OpenAI built ChatGPT to assist users&quot;, &quot;output&quot;: &quot;ChatGPT is made by OpenAI.&quot;}</pre><h4>🧠 Step 4: Apply LoRA for Efficient Fine-Tuning</h4><pre>from peft import LoraConfig, get_peft_model, TaskType<br>lora_config = LoraConfig(<br>    r=8,<br>    lora_alpha=16,<br>    target_modules=[&quot;q_proj&quot;, &quot;v_proj&quot;],  # specific to Mistral/LLMs<br>    lora_dropout=0.05,<br>    bias=&quot;none&quot;,<br>    task_type=TaskType.CAUSAL_LM<br>)<br>model = get_peft_model(model, lora_config)</pre><h4>📚 Step 5: Load and Prepare Dataset</h4><pre>from datasets import load_dataset<br>dataset = load_dataset(&quot;json&quot;, data_files=&quot;data.jsonl&quot;, split=&quot;train&quot;)<br>dataset = dataset.train_test_split(test_size=0.1)</pre><h4>🏋️ Step 6: Fine-Tune the Model Using SFT Trainer</h4><pre>from transformers import TrainingArguments<br>from trl import SFTTrainer<br>training_args = TrainingArguments(<br>    output_dir=&quot;./finetuned-model&quot;,<br>    per_device_train_batch_size=2,<br>    num_train_epochs=3,<br>    logging_steps=10,<br>    save_strategy=&quot;epoch&quot;,<br>    fp16=True<br>)<br>trainer = SFTTrainer(<br>    model=model,<br>    tokenizer=tokenizer,<br>    train_dataset=dataset[&quot;train&quot;],<br>    eval_dataset=dataset[&quot;test&quot;],<br>    args=training_args,<br>    packing=True,<br>    max_seq_length=512<br>)<br>trainer.train()</pre><h4>🔁 Step 7: Test the Fine-Tuned Model</h4><pre>prompt = &quot;&quot;&quot;### Instruction:<br>Translate English to French.### Input:<br>I love ice cream.<br>### Response:<br>&quot;&quot;&quot;<br>inputs = tokenizer(prompt, return_tensors=&quot;pt&quot;).to(&quot;cuda&quot;)<br>outputs = model.generate(**inputs, max_new_tokens=50)<br>print(tokenizer.decode(outputs[0], skip_special_tokens=True))<br></pre><h4>💾 Step 8: Save the Fine-Tuned Model</h4><pre>model.save_pretrained(&quot;./my-finetuned-llm&quot;)<br>tokenizer.save_pretrained(&quot;./my-finetuned-llm&quot;)</pre><h3>🔄 Step: Load and Generate from Your Fine-Tuned Model</h3><h4>🧠 1. Load the Fine-Tuned Model</h4><pre>from transformers import AutoModelForCausalLM, AutoTokenizer<br>import torch<br>model_path = &quot;./my-finetuned-llm&quot;  # or your custom directory<br>tokenizer = AutoTokenizer.from_pretrained(model_path)<br>model = AutoModelForCausalLM.from_pretrained(<br>    model_path,<br>    device_map=&quot;auto&quot;,<br>    torch_dtype=torch.float16<br>)</pre><h4>💬 2. Prepare Your Prompt</h4><p>Make sure the format matches what your model was fine-tuned on:</p><pre>prompt = &quot;&quot;&quot;### Instruction:<br>Translate English to French.### Input:<br>How are you?<br>### Response:<br>&quot;&quot;&quot;<br></pre><h4>🚀 3. Generate Output from Fine-Tuned Model</h4><pre>inputs = tokenizer(prompt, return_tensors=&quot;pt&quot;).to(&quot;cuda&quot;)<br>outputs = model.generate(<br>    **inputs,<br>    max_new_tokens=100,<br>    do_sample=True,<br>    temperature=0.7,<br>    top_p=0.9<br>)<br>result = tokenizer.decode(outputs[0], skip_special_tokens=True)<br>print(result)</pre><h4>✅ Example Output</h4><pre>### Instruction:<br>Translate English to French.<br>### Input:<br>How are you?<br>### Response:<br>Comment ça va ?</pre><h4>⚠️ Notes</h4><ul><li>Be sure the <strong>prompt format</strong> is consistent with your training data (i.e. same “Instruction/Input/Response” style).</li><li>You can <strong>adjust generation parameters</strong> for better results:</li><li>temperature=0.7 → controls creativity</li><li>top_p=0.9 → limits to top 90% likely words</li><li>max_new_tokens=100 → controls length</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a20f94df2337" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[⚠️ Mastering panic, defer, and recover in Go – From Basics to Advanced]]></title>
            <link>https://medium.com/@abhishekkushwaha11998/%EF%B8%8F-mastering-panic-defer-and-recover-in-go-from-basics-to-advanced-62e3ab18b324?source=rss-5288bcd75b84------2</link>
            <guid isPermaLink="false">https://medium.com/p/62e3ab18b324</guid>
            <category><![CDATA[defer]]></category>
            <category><![CDATA[golang-tutorial]]></category>
            <category><![CDATA[error-handling]]></category>
            <category><![CDATA[go-defer]]></category>
            <category><![CDATA[golang-panic]]></category>
            <dc:creator><![CDATA[Abhishek Kushwaha]]></dc:creator>
            <pubDate>Tue, 26 Aug 2025 10:15:39 GMT</pubDate>
            <atom:updated>2025-08-26T10:15:39.185Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Jsu30GLB3f8YYixaLFNOOg.png" /></figure><p>Go is known for its explicit error handling, but it also provides a less commonly used trio of built-in mechanisms for handling unexpected failures: <strong>panic</strong>, <strong>defer</strong>, and <strong>recover</strong>.</p><p>These are <em>not</em> meant to replace regular error handling — they are tools for dealing with exceptional, unrecoverable, or unexpected conditions.</p><p>In this post, we’ll go from <strong>basic usage</strong> to <strong>advanced patterns</strong>, with practical examples at every step.</p><h3>🧩 Table of Contents</h3><ol><li>What is panic?</li><li>What is defer?</li><li>What is recover?</li><li>How defer, panic, and recover work together</li><li>Advanced patterns (e.g., graceful server recovery)</li><li>When to use (and avoid) panic/recover</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/291/1*x3OCchS8Ule5bt0VaTEJPg.png" /></figure><h3>🔥 1. What Is panic?</h3><p>panic is Go’s way of saying “something went horribly wrong.” It stops the normal execution of the current function and begins unwinding the stack — just like a runtime crash.</p><pre>func causePanic() {<br>    panic(&quot;something bad happened&quot;)<br>}</pre><p>Output:</p><pre>panic: something bad happened<br><br>goroutine 1 [running]:<br>main.causePanic()<br> /path/to/main.go:6 +0x39<br>exit status 2</pre><p>Use panic only for unrecoverable errors — things that indicate a bug or corrupted state (e.g., nil dereference, index out of bounds).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/310/1*-411lqB8cb3Svj5TFFPObg.png" /></figure><h3>⏳ 2. What Is defer?</h3><p>defer is used to delay the execution of a function until the surrounding function returns — no matter how it returns (even via panic).</p><pre>func example() {<br>    defer fmt.Println(&quot;deferred call&quot;)<br>    fmt.Println(&quot;normal call&quot;)<br>}</pre><p>Output:</p><pre>normal call<br>deferred call</pre><p>defer is commonly used for:</p><ul><li>Resource cleanup (file.Close())</li><li>Unlocking mutexes</li><li>Logging exit points</li><li>Recovering from panic</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/275/1*AL7n3M88QnzegHp7wF3o0Q.jpeg" /></figure><h3>🛡️ 3. What Is recover?</h3><p>recover is a built-in function used inside a defer to <strong>catch a panic</strong>. If called outside a defer, it returns nil.</p><pre>func safeCall() {<br>    defer func() {<br>        if r := recover(); r != nil {<br>            fmt.Println(&quot;Recovered from panic:&quot;, r)<br>        }<br>    }()<br>panic(&quot;oh no!&quot;)<br>}</pre><p>Output:</p><pre>Recovered from panic: oh no!</pre><p>recover() effectively &quot;stops&quot; the panic and lets your program continue.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/1*3TV43SvQFm78MyTUdtBY6A.png" /></figure><h3>🔁 4. Putting It All Together</h3><p>Here’s a full example showing the stack unwinding and recovery mechanism:</p><pre>func level1() {<br>    defer fmt.Println(&quot;defer in level1&quot;)<br>    level2()<br>}<br>func level2() {<br>    defer fmt.Println(&quot;defer in level2&quot;)<br>    panic(&quot;something went wrong in level2&quot;)<br>}<br>func main() {<br>    defer func() {<br>        if r := recover(); r != nil {<br>            fmt.Println(&quot;Recovered in main:&quot;, r)<br>        }<br>    }()<br>    level1()<br>    fmt.Println(&quot;Main completed&quot;)<br>}</pre><p><strong>Output:</strong></p><pre>defer in level2<br>defer in level1<br>Recovered in main: something went wrong in level2<br>Main completed</pre><p>Notice how defers run in <strong>LIFO (Last In, First Out)</strong> order, and recover gives you control before the program crashes.</p><h3>🧠 5. Advanced Use Cases</h3><p>Let’s look at some real-world patterns using defer, panic, and recover.</p><h3>✅ A. Graceful Error Handling in Middleware</h3><p>In web servers (like using net/http), you can use recover to prevent panics from crashing your server:</p><pre>func recoverMiddleware(next http.Handler) http.Handler {<br>    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {<br>        defer func() {<br>            if err := recover(); err != nil {<br>                log.Printf(&quot;Recovered from panic: %v&quot;, err)<br>                http.Error(w, &quot;Internal Server Error&quot;, http.StatusInternalServerError)<br>            }<br>        }()<br>next.ServeHTTP(w, r)<br>    })<br>}</pre><p>This catches panics from any handler and returns a 500 without killing the server.</p><h3>✅ B. Clean Up Resources Even After Panic</h3><pre>func openFile() {<br>    f, err := os.Open(&quot;somefile.txt&quot;)<br>    if err != nil {<br>        panic(err)<br>    }<br>defer func() {<br>        fmt.Println(&quot;closing file...&quot;)<br>        f.Close()<br>    }()<br>    // simulate a panic<br>    panic(&quot;unexpected failure&quot;)<br>}</pre><p>Even though there’s a panic, the file still closes thanks to defer.</p><h3>✅ C. Retry Pattern with Recovery</h3><pre>func doWork() {<br>    fmt.Println(&quot;Doing work...&quot;)<br>    panic(&quot;fail&quot;)<br>}<br>func safeRetry(fn func()) {<br>    for i := 0; i &lt; 3; i++ {<br>        func() {<br>            defer func() {<br>                if r := recover(); r != nil {<br>                    fmt.Printf(&quot;Attempt %d failed: %v\n&quot;, i+1, r)<br>                }<br>            }()<br>            fn()<br>        }()<br>    }<br>}<br>func main() {<br>    safeRetry(doWork)<br>}</pre><p>This retries a panic-prone function without crashing the whole app.</p><h3>⚠️ 6. When to Use (and Avoid) panic/recover</h3><h3>✅ Use panic when:</h3><ul><li>There’s a truly unrecoverable error (e.g., invariant violation)</li><li>In main() or init-time setups that must not fail silently</li><li>In testing to fail fast (e.g., t.Fatal() uses panic internally)</li></ul><h3>❌ Avoid panic:</h3><ul><li>For regular control flow</li><li>For expected errors (e.g., “file not found”)</li><li>In public libraries — don’t make consumers recover your panics</li></ul><blockquote><em>Idiomatic Go uses </em><em>error for flow control, and </em><em>panic only when the program </em><strong><em>cannot</em></strong><em> continue.</em></blockquote><h3>🧪 Bonus: panic in Tests</h3><p>You can assert panics in tests:</p><pre>func MustDivide(a, b int) int {<br>    if b == 0 {<br>        panic(&quot;divide by zero&quot;)<br>    }<br>    return a / b<br>}<br>func TestMustDivide(t *testing.T) {<br>    defer func() {<br>        if r := recover(); r == nil {<br>            t.Error(&quot;Expected panic, but didn&#39;t get one&quot;)<br>        }<br>    }()<br>    MustDivide(10, 0)<br>}</pre><h3>🧩 Summary</h3><p>Concept PurposepanicStops normal execution, unwinds stackdeferRuns cleanup code before function exitsrecoverIntercepts a panic to regain control</p><h3>🚀 Final Thoughts</h3><p>While Go is famous for its explicit error handling, the panic/defer/recover trio gives you powerful tools to handle <strong>exceptional</strong> situations — if used responsibly.</p><p>Mastering them means writing more resilient, predictable, and debuggable Go code — especially in production systems or large services.</p><p>✍️ <em>If you found this helpful, consider sharing it with your Go team or dropping a comment on how you use </em><em>panic and </em><em>recover in production.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=62e3ab18b324" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Go 1.25 Is Here: Smarter, Leaner, and Developer-First]]></title>
            <link>https://medium.com/@abhishekkushwaha11998/go-1-25-is-here-smarter-leaner-and-developer-first-e57433795035?source=rss-5288bcd75b84------2</link>
            <guid isPermaLink="false">https://medium.com/p/e57433795035</guid>
            <category><![CDATA[golang-new-features]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[goreleaser]]></category>
            <category><![CDATA[golang-tutorial]]></category>
            <category><![CDATA[golangdevelopmentcompany]]></category>
            <dc:creator><![CDATA[Abhishek Kushwaha]]></dc:creator>
            <pubDate>Wed, 20 Aug 2025 07:25:01 GMT</pubDate>
            <atom:updated>2025-08-20T07:25:01.133Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Released on August 12, 2025</strong>, Go 1.25 brings wide-ranging improvements — spanning the <strong>runtime</strong>, <strong>compiler</strong>, <strong>tooling</strong>, and <strong>standard library</strong> — plus experimental features that are ready for developers to test and help shape the future of the language. <a href="https://go.dev/blog/go1.25?utm_source=chatgpt.com">Go Dev</a></p><p>Here’s a comprehensive breakdown of what’s new and how it can supercharge your Go development workflow.</p><h3>1. Introduction</h3><p>Go 1.25 is now officially available, bringing optimized performance, enhanced diagnostics, refined language semantics, and exciting experimental capabilities. Refer to the official release notes for full details. <a href="https://tip.golang.org/doc/go1.25?utm_source=chatgpt.com">tip.golang.org</a><a href="https://go.dev/blog/go1.25?utm_source=chatgpt.com">Go Dev</a></p><h3>2. Runtime &amp; GC Highlights</h3><p><strong>Container-aware</strong> GOMAXPROCS</p><p>On Linux, Go 1.25 respects <strong>cgroup CPU bandwidth limits</strong>, defaulting GOMAXPROCS accordingly. It adapts dynamically if your resource constraints change—perfect for container workloads. Manual overrides or disabling via GODEBUG are still supported.<a href="https://tip.golang.org/doc/go1.25?utm_source=chatgpt.com">tip.golang.org</a></p><p><strong>Experimental Garbage Collector: </strong>greenteagc</p><p>Enableable via GOEXPERIMENT=greenteagc, this new GC design improves locality and parallelism, delivering an estimated <strong>10–40% reduction in GC overhead</strong> for GC-heavy programs.<a href="https://tip.golang.org/doc/go1.25?utm_source=chatgpt.com">tip.golang.org</a></p><p><strong>Other Runtime Tweaks</strong></p><ul><li><strong>Cleaner panic messages</strong> when a panic is recovered and re-panicked.<a href="https://tip.golang.org/doc/go1.25?utm_source=chatgpt.com">tip.golang.org</a></li><li><strong>VMA annotations on Linux</strong> for better memory diagnostics, can be disabled with decoratemappings=0.<a href="https://tip.golang.org/doc/go1.25?utm_source=chatgpt.com">tip.golang.org</a></li></ul><h3>3. Tooling &amp; Language Refinements</h3><p>go build -asan:<strong> Leak Detection by Default</strong></p><p>Memory leaks from C code (via cgo) are now highlighted at program exit — helpful for memory safety. Turn it off with ASAN_OPTIONS=detect_leaks=0.<a href="https://tip.golang.org/doc/go1.25?utm_source=chatgpt.com">tip.golang.org</a></p><p><strong>Smarter </strong><strong>go Command</strong></p><ul><li>Fewer prebuilt binaries; tools are compiled on demand via go tool.<a href="https://tip.golang.org/doc/go1.25?utm_source=chatgpt.com">tip.golang.org</a></li><li>go.mod now supports an ignore directive to exclude directories (e.g., tooling or vendor) from pattern matching, while still including them in module zips.<a href="https://tip.golang.org/doc/go1.25?utm_source=chatgpt.com">tip.golang.org</a></li><li>go doc -http starts a local documentation server and opens it in your browser.<a href="https://tip.golang.org/doc/go1.25?utm_source=chatgpt.com">tip.golang.org</a></li><li>go version -m -json emits BuildInfo in structured JSON—a developer-friendly addition.<a href="https://tip.golang.org/doc/go1.25?utm_source=chatgpt.com">tip.golang.org</a></li><li>Support for subdirectory-based module roots via &lt;meta ... subdir&gt; tags simplifies working with monorepos.<a href="https://tip.golang.org/doc/go1.25?utm_source=chatgpt.com">tip.golang.org</a></li><li>work pattern now matches all packages across modules in workspace mode.<a href="https://tip.golang.org/doc/go1.25?utm_source=chatgpt.com">tip.golang.org</a></li><li>Updating the go line in go.mod or go.work now avoids auto-adding a toolchain version for a cleaner look.<a href="https://tip.golang.org/doc/go1.25?utm_source=chatgpt.com">tip.golang.org</a></li></ul><p><strong>New </strong>go vet <strong>Analyzers</strong></p><p>Two fresh static-check tools:</p><ul><li>waitgroup warns about incorrect use of sync.WaitGroup.Add.</li><li>hostport flags potentially IPv6-breaking address formats like fmt.Sprintf(&quot;%s:%d&quot;, host, port), nudging you to use net.JoinHostPor</li></ul><h3>4. Compiler &amp; Linker Upgrades</h3><p><strong>DWARF v5 Debugging</strong></p><p>Go’s compiler and linker now produce DWARF v5 debug info — smaller and faster link times. You can disable it using GOEXPERIMENT=nodwarf5. <a href="https://go.dev/doc/go1.25?utm_source=chatgpt.com">Go Dev</a></p><p><strong>Immediate Nil-pointer Panics</strong></p><p>Go 1.25 fixes a spec violation by forcing nil-pointer dereferences to panic immediately. For example, calling a method on a nil file handle will now promptly crash. <a href="https://go.dev/doc/go1.25?utm_source=chatgpt.com">Go Dev</a></p><p><strong>More Stack Allocation for Slices</strong></p><p>The compiler now moves more slices’ backing data to the stack — increasing speed. Debugging .s or .o might require -gcflags=all=-d=variablemakehash=n. <a href="https://go.dev/doc/go1.25?utm_source=chatgpt.com">Go Dev</a></p><p><strong>New Linker Option</strong>: -funcalign=N</p><p>Align function entries with a custom alignment. Default unchanged and platform-dependent. <a href="https://go.dev/doc/go1.25?utm_source=chatgpt.com">Go Dev</a></p><h3>5. Standard Library &amp; Testing Enhancements</h3><p>testing/synctest <strong>Package</strong></p><p>Supports deterministic concurrency testing with “fake clock” bubbles and the ability to wait until goroutines block. <a href="https://go.dev/doc/go1.25?utm_source=chatgpt.com">Go Dev</a></p><p><strong>Experimental </strong>encoding/json/v2</p><p>Enable with GOEXPERIMENT=jsonv2 to use both encoding/json/v2 and encoding/json/jsontext, offering faster decoding and new configuration options. The encoding/json package leans on the new system under the hood.<a href="https://tip.golang.org/doc/go1.25?utm_source=chatgpt.com">tip.golang.org</a></p><p><strong>Standard Library Improvements</strong></p><p>A host of updates, including:</p><ul><li><strong>archive/tar:</strong> symlink support with ReadLinkFS.<a href="https://tip.golang.org/doc/go1.25?utm_source=chatgpt.com">tip.golang.org</a></li><li><strong>crypto:</strong> Faster FIPS mode signing; new interfaces (MessageSigner); improved hashing performance.<a href="https://tip.golang.org/doc/go1.25?utm_source=chatgpt.com">tip.golang.org</a></li><li><strong>net/http:</strong> New CrossOriginProtection for CSRF defenses using modern Fetch metadata—no tokens required.<a href="https://tip.golang.org/doc/go1.25?utm_source=chatgpt.com">tip.golang.org</a></li><li><strong>net:</strong> IP-based MX records support; IPv6 multicast on Windows; FileConn and related helpers added.<a href="https://tip.golang.org/doc/go1.25?utm_source=chatgpt.com">tip.golang.org</a></li><li><strong>os &amp; fs:</strong> Extended filesystem ops (Chmod, Symlink, etc.) on Root.<a href="https://tip.golang.org/doc/go1.25?utm_source=chatgpt.com">tip.golang.org</a></li><li><strong>reflect:</strong> TypeAssert() to avoid allocations.<a href="https://tip.golang.org/doc/go1.25?utm_source=chatgpt.com">tip.golang.org</a></li><li><strong>regexp/syntax:</strong> Supports more Unicode category names and is case-insensitive.<a href="https://tip.golang.org/doc/go1.25?utm_source=chatgpt.com">tip.golang.org</a></li><li><strong>runtime:</strong> Parallel cleanup functions; better diagnostics via checkfinalizers=1.<a href="https://tip.golang.org/doc/go1.25?utm_source=chatgpt.com">tip.golang.org</a></li><li><strong>runtime/trace:</strong> FlightRecorder captures recent execution state—great for post-mortems.<a href="https://tip.golang.org/doc/go1.25?utm_source=chatgpt.com">tip.golang.org</a></li><li><strong>sync:</strong> WaitGroup.Go(f) simplifies launching and counting goroutines. <a href="https://tip.golang.org/doc/go1.25?utm_source=chatgpt.com">tip.golang.org</a></li><li><strong>testing enhancements:</strong> T.Attr, Output, and safer AllocsPerRun. <a href="https://tip.golang.org/doc/go1.25?utm_source=chatgpt.com">tip.golang.org</a></li><li><strong>fstest and MapFS:</strong> Now handle symlinks correctly. <a href="https://tip.golang.org/doc/go1.25?utm_source=chatgpt.com">tip.golang.org</a></li><li><strong>unicode:</strong> New categories (Cn, LC) and aliases. <a href="https://tip.golang.org/doc/go1.25?utm_source=chatgpt.com">tip.golang.org</a></li><li><strong>unique:</strong> Better memory reclamation for interned values. <a href="https://tip.golang.org/doc/go1.25?utm_source=chatgpt.com">tip.golang.org</a></li></ul><h3>6. Example Code Snippets</h3><p><strong>A</strong>. <strong>Handle Goroutines Cleaner with</strong> WaitGroup.Go</p><pre>var wg sync.WaitGroup<br><br>wg.Go(func() {<br>    doSomething()<br>})<br><br>wg.Wait()</pre><p>Simpler than the traditional Add/Done/Wait pattern.</p><p>B. <strong>Deterministic Testing with</strong> testing/synctest</p><pre>import (<br>    &quot;context&quot;<br>    &quot;testing&quot;<br>    &quot;time&quot;<br>    &quot;testing/synctest&quot;<br>)<br><br>func TestTimeout(t *testing.T) {<br>    synctest.Run(func() {<br>        ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)<br>        defer cancel()<br><br>        errCh := make(chan error)<br>        go func() {<br>            errCh &lt;- simulate(ctx, 6*time.Second)<br>        }()<br><br>        synctest.Wait() // all goroutines block<br><br>        synctest.Wait() // simulate timeout elapse<br><br>        if err := &lt;-errCh; err != context.DeadlineExceeded {<br>            t.Fatalf(&quot;expected DeadlineExceeded, got %v&quot;, err)<br>        }<br>    })<br>}</pre><p><strong>C.</strong> <strong>JSON v2: Skip Zero Struct Fields</strong></p><pre>import (<br>    &quot;encoding/json/v2&quot;<br>    &quot;encoding/json/jsontext&quot;<br>    &quot;fmt&quot;<br>    &quot;log&quot;<br>)<br><br>type Person struct {<br>    Name string `json:&quot;name&quot;`<br>    Age  int    `json:&quot;age,omitempty&quot;`<br>}<br><br>func main() {<br>    p := Person{Name: &quot;Alice&quot;, Age: 0}<br>    b, err := json.Marshal(p,<br>        json.OmitZeroStructFields(true),<br>        jsontext.WithIndent(&quot;  &quot;))<br>    if err != nil {<br>        log.Fatal(err)<br>    }<br>    fmt.Println(string(b))<br>}</pre><p><strong>D.</strong> <strong>Prompt Nil-pointer Panic Catching</strong></p><pre>import &quot;os&quot;<br><br>func main() {<br>    f, _ := os.Open(&quot;missing.file&quot;)<br>    _ = f.Name() // Will panic immediately on nil<br>}</pre><p>Fix bugs by checking err before using results.</p><h3>7. Why Go 1.25 Matters</h3><ul><li><strong>Performance Gains</strong>: Smarter GC, container-aware runtime, DWARF‑5.</li><li><strong>Enhanced Safety &amp; Debugging</strong>: Leak detection, immediate panics, improved tracing.</li><li><strong>Refined Workflow</strong>: Clean tooling (e.g., go doc -http), better error detection via vet.</li><li><strong>Experiment-Driven Innovation</strong>: JSON v2, greenteagc, FlightRecorder — driven by feedback.</li></ul><h3>8. What You Can Do Next</h3><ul><li>Try the experiments:</li><li>GOEXPERIMENT=greenteagc go build ...</li><li>GOEXPERIMENT=jsonv2 go run ...</li><li>Launch go doc -http in your terminal for docs in-browser.</li><li>Leverage go vet to catch subtle issues early.</li><li>Hook into FlightRecorder when debugging.</li><li>File feedback and issues — your voice improves Go!</li></ul><h3>Final Thought</h3><p>Go 1.25 is a thoughtful leap forward: smarter, faster, and deeply practical. With performance boosts under the hood and new developer-friendly tooling and APIs, it pushes the language forward while retaining Go’s simplicity and clarity.</p><p>Happy coding — go explore Go 1.25!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e57433795035" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[⚙️ Concurrency Patterns in Go: Beyond Goroutines]]></title>
            <link>https://medium.com/@abhishekkushwaha11998/%EF%B8%8F-concurrency-patterns-in-go-beyond-goroutines-aaac225fabda?source=rss-5288bcd75b84------2</link>
            <guid isPermaLink="false">https://medium.com/p/aaac225fabda</guid>
            <category><![CDATA[golang-concurrency]]></category>
            <category><![CDATA[go-concurrency]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[concurrency]]></category>
            <dc:creator><![CDATA[Abhishek Kushwaha]]></dc:creator>
            <pubDate>Sat, 16 Aug 2025 13:52:41 GMT</pubDate>
            <atom:updated>2025-08-16T13:52:41.213Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Go (Golang)</strong> has become a favorite among developers for building scalable, high-performance systems — and at the heart of this power lies its elegant support for <strong>concurrency</strong>. While most developers get started with go func(), true mastery comes from understanding and using Go’s <strong>concurrency patterns</strong> effectively.</p><p>In this blog, we’ll dive into common and powerful concurrency patterns in Go that will level up your programs from “it works” to “it scales.”</p><h3>🧠 Why Concurrency in Go Feels Natural</h3><p>Go’s concurrency model is based on <strong>CSP</strong> (Communicating Sequential Processes), which promotes <strong>sharing data by communicating</strong>, not by sharing memory.</p><p>Key building blocks:</p><ul><li>go keyword: Starts a goroutine.</li><li>chan: Channel for communication.</li><li>select: Wait on multiple channel operations.</li></ul><p>Let’s explore how to combine these into powerful patterns.</p><h3>1. 🔄 Fan-Out, Fan-In</h3><p><strong>Use case</strong>: Distribute work across multiple goroutines (fan-out), then combine results into one channel (fan-in).</p><pre>func worker(id int, jobs &lt;-chan int, results chan&lt;- int) {<br>    for j := range jobs {<br>        fmt.Printf(&quot;worker %d processing job %d\n&quot;, id, j)<br>        time.Sleep(time.Second)<br>        results &lt;- j * 2<br>    }<br>}</pre><pre>jobs := make(chan int, 100)<br>results := make(chan int, 100)<br><br>// Fan-out: multiple workers<br>for w := 1; w &lt;= 3; w++ {<br>    go worker(w, jobs, results)<br>}<br><br>for j := 1; j &lt;= 5; j++ {<br>    jobs &lt;- j<br>}<br>close(jobs)<br><br>// Fan-in: collect results<br>for a := 1; a &lt;= 5; a++ {<br>    fmt.Println(&quot;Result:&quot;, &lt;-results)<br>}</pre><p>✅ <strong>Benefits</strong>: Prevents indefinite blocking. Essential for real-world applications.</p><h3>2. ⏰ Timeout with select and time.After</h3><p><strong>Use case</strong>: Avoid hanging on a slow operation.</p><pre>select {<br>case res := &lt;-slowChan:<br>    fmt.Println(&quot;Received:&quot;, res)<br>case &lt;-time.After(2 * time.Second):<br>    fmt.Println(&quot;Timeout!&quot;)<br>}</pre><p>✅ <strong>Benefits</strong>: Prevents indefinite blocking. Essential for real-world applications.</p><h3>3. ✅ Worker Pool</h3><p><strong>Use case</strong>: Limit the number of concurrent tasks.</p><pre>func worker(id int, tasks &lt;-chan int, wg *sync.WaitGroup) {<br>    defer wg.Done()<br>    for task := range tasks {<br>        fmt.Printf(&quot;Worker %d processing %d\n&quot;, id, task)<br>        time.Sleep(time.Second)<br>    }<br>}</pre><pre>tasks := make(chan int, 10)<br>var wg sync.WaitGroup<br><br>// Start fixed number of workers<br>for i := 1; i &lt;= 3; i++ {<br>    wg.Add(1)<br>    go worker(i, tasks, &amp;wg)<br>}<br><br>// Send tasks<br>for i := 1; i &lt;= 5; i++ {<br>    tasks &lt;- i<br>}<br>close(tasks)<br><br>wg.Wait()</pre><p>✅ <strong>Benefits</strong>: Controls resource usage, avoids spawning too many goroutines.</p><h3>4. 📡 Publish-Subscribe (Fan-Out to Multiple Listeners)</h3><p><strong>Use case</strong>: Broadcast messages to multiple subscribers.</p><pre>type subscriber chan string<br><br>func publish(subs []subscriber, msg string) {<br>    for _, sub := range subs {<br>        go func(ch subscriber) {<br>            ch &lt;- msg<br>        }(sub)<br>    }<br>}</pre><pre>sub1 := make(subscriber)<br>sub2 := make(subscriber)<br>subs := []subscriber{sub1, sub2}<br><br>go func() {<br>    for msg := range sub1 {<br>        fmt.Println(&quot;Sub1:&quot;, msg)<br>    }<br>}()<br>go func() {<br>    for msg := range sub2 {<br>        fmt.Println(&quot;Sub2:&quot;, msg)<br>    }<br>}()<br><br>publish(subs, &quot;New blog post is out!&quot;)</pre><p>✅ <strong>Benefits</strong>: Clean broadcasting mechanism without tight coupling.</p><h3>5. 🧼 Pipeline Pattern</h3><p><strong>Use case</strong>: Transform data in stages, like a factory line.</p><pre>func gen(nums ...int) &lt;-chan int {<br>    out := make(chan int)<br>    go func() {<br>        for _, n := range nums {<br>            out &lt;- n<br>        }<br>        close(out)<br>    }()<br>    return out<br>}<br><br>func square(in &lt;-chan int) &lt;-chan int {<br>    out := make(chan int)<br>    go func() {<br>        for n := range in {<br>            out &lt;- n * n<br>        }<br>        close(out)<br>    }()<br>    return out<br>}</pre><pre>for n := range square(gen(2, 3, 4)) {<br>    fmt.Println(n)<br>}</pre><p>✅ <strong>Benefits</strong>: Composable and testable stages of data processing.</p><h3>⚠️ Common Pitfalls</h3><ol><li><strong>Leaking goroutines</strong>: Always close channels and use select with timeouts.</li><li><strong>Deadlocks</strong>: Don’t block on a channel without a guarantee of a sender/receiver.</li><li><strong>Race conditions</strong>: Use sync.Mutex or channels to protect shared state.</li></ol><h3>🧰 Tools to Debug Concurrency</h3><ul><li>go run -race: Detect race conditions.</li><li><strong>pprof</strong>: Profile goroutines.</li><li>sync.WaitGroup, sync.Mutex: Coordinate safely.</li></ul><h3>🚀 Final Thoughts</h3><p>Go makes concurrency <strong>easy to start</strong> but <strong>hard to master</strong>. Understanding patterns like fan-out/fan-in, worker pools, and pipelines allows you to write <strong>idiomatic</strong>, <strong>scalable</strong>, and <strong>safe</strong> concurrent programs.</p><p>If you’re building web servers, background job processors, or real-time systems, these patterns are essential tools in your Go toolbox.</p><h3>✍️ Want to Learn More?</h3><ul><li><a href="https://go.dev/blog/pipelines">https://go.dev/blog/pipelines</a></li><li><a href="https://go.dev/blog/pipelines">Go Proverbs</a>: “Do not communicate by sharing memory; share memory by communicating.”</li><li><a href="https://pkg.go.dev/golang.org/x/sync/errgroup">golang.org/x/sync/errgroup</a> for structured goroutines.</li></ul><p>💬 Have you used these patterns in your projects? What’s your favorite concurrency trick in Go? Drop a comment below or share your own snippets!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=aaac225fabda" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Bubble Sort: A Step-by-Step Guide]]></title>
            <link>https://medium.com/@abhishekkushwaha11998/understanding-bubble-sort-a-step-by-step-guide-39c022eaed2f?source=rss-5288bcd75b84------2</link>
            <guid isPermaLink="false">https://medium.com/p/39c022eaed2f</guid>
            <category><![CDATA[bubble-sort]]></category>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[data-structure-algorithm]]></category>
            <category><![CDATA[data-structures]]></category>
            <dc:creator><![CDATA[Abhishek Kushwaha]]></dc:creator>
            <pubDate>Wed, 24 Jul 2024 14:15:08 GMT</pubDate>
            <atom:updated>2024-07-24T14:15:08.008Z</atom:updated>
            <content:encoded><![CDATA[<h4>Bubble sort is one of the simplest sorting algorithms, yet it provides a fundamental understanding of how sorting algorithms operate. In this blog post, we’ll dive into the logic behind bubble sort, its implementation, efficiency considerations, and practical use cases.</h4><h4>What is Bubble Sort?</h4><p>Bubble sort is a straightforward comparison-based sorting algorithm. It repeatedly steps through the list, compares adjacent elements, and swaps them if they are in the wrong order. The pass through the list is repeated until the list is sorted.</p><h4>Step-by-Step Breakdown of Bubble Sort</h4><p>Let’s walk through the basic steps involved in bubble sort:</p><ol><li><strong>Initialization:</strong></li></ol><ul><li>Start with an unsorted array of elements.</li></ul><p><strong>2. Iterate through the Array:</strong></p><ul><li>Begin with the first element (index 0) and compare it with the next element (index 1).</li><li>If the current element is greater than the next element, swap them.</li></ul><p><strong>3. Continue Comparisons:</strong></p><ul><li>Move to the next pair of elements (index 1 and index 2), and repeat the comparison and swap if necessary.</li><li>Continue this process until you reach the end of the array.</li></ul><p><strong>4. Repeat Until Sorted:</strong></p><ul><li>After completing one pass through the array, the largest unsorted element is guaranteed to be in its correct position.</li><li>Repeat the process for the remaining elements (excluding the last sorted element) until the entire array is sorted.</li></ul><h3>Example of Bubble Sort in Action</h3><p>Let’s consider a simple example to illustrate the bubble sort process:</p><p><strong>Initial Array:</strong> [5, 3, 8, 2, 7]</p><ol><li><strong>First Pass:</strong></li></ol><ul><li>Compare 5 and 3 → swap (Resulting Array: [3, 5, 8, 2, 7])</li><li>Compare 5 and 8 → no swap</li><li>Compare 8 and 2 → swap (Resulting Array: [3, 5, 2, 8, 7])</li><li>Compare 8 and 7 → swap (Resulting Array: [3, 5, 2, 7, 8])</li></ul><p><strong>2. Second Pass:</strong></p><ul><li>Compare 3 and 5 → no swap</li><li>Compare 5 and 2 → swap (Resulting Array: [3, 2, 5, 7, 8])</li><li>Compare 5 and 7 → no swap</li><li>Compare 7 and 8 → no swap</li></ul><p><strong>3. Third Pass:</strong></p><ul><li>Compare 3 and 2 → swap (Resulting Array: [2, 3, 5, 7, 8])</li><li>Compare 3 and 5 → no swap</li><li>Compare 5 and 7 → no swap</li><li>Compare 7 and 8 → no swap</li></ul><p><strong>4. Fourth Pass:</strong></p><ul><li>Compare 2 and 3 → no swap</li><li>Compare 3 and 5 → no swap</li><li>Compare 5 and 7 → no swap</li><li>Compare 7 and 8 → no swap</li></ul><p>Now, the array [2, 3, 5, 7, 8] is sorted.</p><h3>Efficiency of Bubble Sort</h3><p>Bubble sort has a time complexity of O(n²) in the worst and average cases, where n is the number of elements in the array. This makes it inefficient for large datasets compared to more advanced sorting algorithms like quicksort or merge sort.</p><h3>Practical Use Cases</h3><p>Despite its inefficiency for large datasets, bubble sort can be useful in scenarios where simplicity and ease of implementation are prioritized over performance. It’s also valuable for educational purposes, helping beginners grasp fundamental sorting concepts.</p><h3>Conclusion</h3><p>Bubble sort provides a foundational understanding of sorting algorithms through its straightforward approach of repeatedly comparing adjacent elements and swapping them if they are in the wrong order. While not suitable for large datasets due to its O(n²) time complexity, it remains a valuable algorithm to learn for its simplicity and educational value.</p><p>By mastering bubble sort, you lay a solid foundation for understanding more complex sorting algorithms and gain insights into how computers organize and manipulate data efficiently.</p><h3>HAPPY READING :))</h3><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=39c022eaed2f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Demystifying Git: A Beginner’s Guide to Version Control]]></title>
            <link>https://medium.com/@abhishekkushwaha11998/demystifying-git-a-beginners-guide-to-version-control-d81e31d1f916?source=rss-5288bcd75b84------2</link>
            <guid isPermaLink="false">https://medium.com/p/d81e31d1f916</guid>
            <dc:creator><![CDATA[Abhishek Kushwaha]]></dc:creator>
            <pubDate>Wed, 10 Jul 2024 12:28:10 GMT</pubDate>
            <atom:updated>2024-07-10T12:28:10.058Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Introduction:</strong> In the world of software development, managing changes to your codebase is crucial. Imagine working on a project with multiple collaborators — how do you ensure everyone’s changes are tracked, conflicts are resolved, and previous versions can be restored if needed? This is where Git, a distributed version control system, comes to the rescue. In this article, we’ll explore Git from the ground up, understanding its basic concepts, essential commands, and practical tips to get you started.</p><p><strong>1. What is Git?</strong> At its core, Git is a version control system that tracks changes in your codebase over time. It allows multiple developers to collaborate on projects without overwriting each other’s work, making it easier to manage code revisions and coordinate teamwork effectively.</p><p><strong>2. Why Git?</strong> Unlike traditional centralized version control systems, Git is distributed. This means every developer has a complete copy of the project repository on their local machine, including its full history. This distributed nature offers several advantages:</p><ul><li>Speed: Most operations are performed locally, without the need to communicate with a central server.</li><li>Flexibility: Branching and merging are lightweight and straightforward, enabling efficient parallel development.</li><li>Backup and Recovery: Each developer’s copy serves as a full backup, ensuring no loss of data even if the central server goes down.</li></ul><p><strong>3. Getting Started with Git: Installation and Setup</strong> Let’s dive into the practical side. First things first — install Git on your machine. Here’s how you can do it:</p><ul><li><strong>Windows:</strong> Download the Git installer from <a href="https://git-scm.com/">git-scm.com</a> and follow the installation instructions.</li><li><strong>macOS:</strong> Git comes pre-installed on macOS. You can check its version by opening Terminal and running git --version.</li><li><strong>Linux:</strong> Use your distribution’s package manager (e.g., apt for Debian/Ubuntu, yum for Fedora) to install Git.</li></ul><p>Once installed, configure Git with your name and email address:</p><pre>git config --global user.name &quot;Your Name&quot;<br>git config --global user.email &quot;your.email@example.com&quot;</pre><p><strong>4. Git Basics: Commands and Workflow</strong> Git operates with three main stages in its workflow:</p><ul><li><strong>Working Directory:</strong> Your local sandbox where you modify files.</li><li><strong>Staging Area (Index):</strong> A temporary space where you prepare changes before committing them.</li><li><strong>Repository (HEAD):</strong> Your project’s complete history and all committed changes.</li></ul><p>Here are some fundamental Git commands to get you started:</p><ul><li>Initialize a new Git repository:</li></ul><pre>git init</pre><ul><li>Add changes to the staging area:</li></ul><pre>git add &lt;file_name&gt;</pre><ul><li>Commit changes to the repository:</li></ul><pre>git commit -m &quot;Commit message&quot;</pre><ul><li>Check the status of your working directory:</li></ul><pre>git status</pre><ul><li>View commit history:</li></ul><pre>git log</pre><p><strong>5. Branching and Merging</strong> One of Git’s most powerful features is branching. It allows you to create independent lines of development within the same repository. Here’s how you can work with branches:</p><ul><li>Create a new branch:</li></ul><pre>git branch &lt;branch_name&gt;</pre><ul><li>Switch to a different branch:</li></ul><pre>git checkout &lt;branch_name&gt;</pre><ul><li>Merge changes from one branch to another:</li></ul><pre>git merge &lt;branch_name&gt;</pre><p><strong>6. Collaborating with Git: Remote Repositories</strong> To collaborate with others, you’ll need to connect your local repository to a remote repository hosted on platforms like GitHub or GitLab:</p><ul><li>Add a remote repository:</li></ul><pre>git remote add origin &lt;remote_repository_url&gt;</pre><ul><li>Push changes to the remote repository</li></ul><pre>git push -u origin &lt;branch_name&gt;</pre><ul><li>Pull changes from the remote repository</li></ul><pre>git pull origin &lt;branch_name&gt;</pre><p><strong>7. Best Practices and Tips</strong> To make the most out of Git, consider these best practices:</p><ul><li>Commit early and often, with clear and concise messages.</li><li>Use branches for new features or bug fixes, keeping your main branch clean.</li><li>Learn to resolve merge conflicts gracefully when merging branches.</li></ul><p><strong>8. Beyond the Basics: Advanced Git Topics</strong> Once you’re comfortable with the basics, explore advanced Git topics such as:</p><ul><li>Tagging releases for stable versions:</li></ul><pre>git tag &lt;tag_name&gt;</pre><ul><li><strong>Undoing Changes:</strong> Git provides several ways to undo changes, depending on your needs:</li><li><strong>Reset:</strong> Discard commits and move the HEAD pointer to a specified state.</li></ul><pre>git reset &lt;commit_hash&gt;</pre><ul><li><strong>Revert:</strong> Create a new commit that undoes specified changes.</li></ul><pre>git revert &lt;commit_hash&gt;</pre><ul><li><strong>Git Workflows:</strong> Explore different workflows to manage your Git repository effectively, such as:</li><li><strong>GitFlow:</strong> A branching model that defines a strict branching model designed around the project release.</li><li><strong>GitHub Flow:</strong> A simpler workflow where all changes happen on branches, and pull requests are used to merge into the main branch.</li><li><strong>Git Hooks:</strong> Customize Git’s behavior by using hooks, which are scripts triggered by Git events (e.g., before commit, after commit).</li><li>Example of a pre-commit hook that runs a script to lint your code:</li></ul><pre>#!/bin/bash <br>npm run lint</pre><ul><li><strong>Interactive Rebase:</strong> Rewrite commit history interactively to reorder, squash, edit, or drop commits before pushing to a remote repository.</li></ul><pre>git rebase -i &lt;base_branch&gt;</pre><ul><li><strong>Cherry-pick:</strong> Apply specific commits from one branch to another, useful for selectively merging changes without merging the entire branch.</li></ul><pre>git cherry-pick &lt;commit_hash&gt;</pre><ul><li><strong>Stashing:</strong> Temporarily store changes that are not ready to be committed, allowing you to switch branches or pull changes without committing incomplete work.</li></ul><pre>git stash <br>git stash apply</pre><ul><li><strong>Submodules:</strong> Manage external repositories as submodules within your main project repository, useful for including dependencies or libraries.</li></ul><pre>git submodule add &lt;repository_url&gt;<br>git submodule update --init</pre><ul><li><strong>Git Bisect:</strong> Efficiently find the commit that introduced a bug by performing a binary search through your commit history.</li></ul><pre>git bisect start git bisect bad git bisect good &lt;commit_hash&gt;</pre><ul><li><strong>Reflog:</strong> View a log of all Git actions performed locally, useful for recovering lost commits or branches.</li></ul><pre>git reflog</pre><p><strong>Additional Tips and Best Practices:</strong></p><ul><li><strong>Squashing Commits:</strong> Combine multiple commits into a single commit to maintain a cleaner and more understandable commit history</li></ul><pre>git rebase -i HEAD~&lt;number_of_commits&gt;</pre><p><strong>Alias:</strong> Create shortcuts for frequently used Git commands to increase productivity and reduce typing.</p><pre>git config --global alias.co checkout <br>git config --global alias.br branch</pre><ul><li><strong>Git Archive:</strong> Export the contents of a Git repository as a zip or tar archive without including the .git directory</li></ul><pre>git archive --format=zip --output=&lt;archive_name&gt;.zip &lt;branch_name&gt;</pre><p><strong>9. Conclusion</strong> Mastering Git takes practice, but it’s an essential skill for any developer. By understanding its core concepts, mastering essential commands, and embracing best practices, you’ll be well-equipped to manage and collaborate on projects efficiently.</p><p><strong>10. Call to Action</strong> Ready to dive deeper into Git? Start by creating your first repository, experimenting with different commands, and exploring more advanced features. Share your experiences and questions in the comments below, and stay tuned for more articles on software development and Git.</p><h3>Happy reading :) !!!</h3><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d81e31d1f916" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Go : Building API with MySQL and Gin .]]></title>
            <link>https://medium.com/@abhishekkushwaha11998/go-building-api-with-mysql-and-gin-d5a8ef70348f?source=rss-5288bcd75b84------2</link>
            <guid isPermaLink="false">https://medium.com/p/d5a8ef70348f</guid>
            <category><![CDATA[database]]></category>
            <category><![CDATA[go-programming]]></category>
            <category><![CDATA[go-mysql]]></category>
            <category><![CDATA[go]]></category>
            <category><![CDATA[gin]]></category>
            <dc:creator><![CDATA[Abhishek Kushwaha]]></dc:creator>
            <pubDate>Sat, 17 Dec 2022 08:57:16 GMT</pubDate>
            <atom:updated>2022-12-17T09:10:03.091Z</atom:updated>
            <content:encoded><![CDATA[<h3>Go : Building API with MySQL and Gin</h3><p>Hi Everyone Namaste! :) :)</p><p>In this Article , i will be building a API in Go , using Gin framework and MySQL database connectivity. <br>In my Previous articles i have discussed about writing Go API using Gin framework.</p><p>If not read !! very sad , Don’t Worry you will get it under my published section of the profile.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1015/1*WJn3ltSQK_e1F4-aia368w.png" /><figcaption>Author</figcaption></figure><p>I hope many would have understood by seeing above image what i am talking about and many would also know what is MySQL . So i will not deep dive in explaining basic concepts .</p><h3>Let start to make it !</h3><h4>Prerequisites before starting to build API.</h4><ol><li>You must have Go installed in you system.</li><li>You should have MySQL server installed in the system.</li><li>You should have an IDE to work on , it’s not very urgent but it makes things simpler and all things are in one place . I am using Vs Code for this API.</li><li>Rest Client would be install for testing .</li></ol><p>I think yes this all are fine .</p><h3>Lets Create an Database</h3><ol><li>I will be creating and simple movie data set to workout around this API . So let go to mysql using below command.</li></ol><pre>sudo mysql</pre><p>2. we will create data base name movies using below command .</p><pre>CREATE DATABASE movies;</pre><p>3. After creating database now we will use movies database to create our table , So to use database movies we will use below command</p><pre> use movies;</pre><p>4. Now we have create table in which we will be storing our data so to create table with name movies use below command.</p><pre>CREATE TABLE `movies` (  `id` int(5) DEFAULT NULL, `title` varchar(255) DEFAULT NULL, `director` varchar(255) DEFAULT NULL ) ENGINE=InnoDB<br> DEFAULT CHARSET= utf8;</pre><p>Once you run this command and after that run below one</p><pre>SHOW tables; </pre><p>you will see table with name movies moving further when you will run</p><pre>DESCRIBE movies;</pre><p>we will see table some thing like</p><pre>mysql&gt; DESCRIBE movies<br>    -&gt; ;<br>+----------+--------------+------+-----+---------+-------+<br>| Field    | Type         | Null | Key | Default | Extra |<br>+----------+--------------+------+-----+---------+-------+<br>| id       | int          | YES  |     | NULL    |       |<br>| title    | varchar(255) | YES  |     | NULL    |       |<br>| director | varchar(255) | YES  |     | NULL    |       |<br>+----------+--------------+------+-----+---------+-------+<br>3 rows in set (0.00 sec)</pre><p>5. Lets add value in the tables for that we will use below commands,</p><pre>mysql&gt; INSERT INTO movies VALUES(&#39;01&#39;,&#39;jurrasic Park&#39;,&#39;steven Spielberg&#39;);<br>Query OK, 1 row affected (0.43 sec)<br><br>mysql&gt; SELECT * FROM movies<br>    -&gt; ;<br>+------+---------------+------------------+<br>| id   | title         | director         |<br>+------+---------------+------------------+<br>|    1 | jurrasic Park | steven Spielberg |<br>+------+---------------+------------------+<br>1 row in set (0.00 sec)<br><br>mysql&gt; INSERT INTO movies VALUES(&#39;02&#39;,&#39;Avengers Endgame&#39;,&#39;russo brothers&#39;);<br>Query OK, 1 row affected (0.31 sec)<br><br>mysql&gt; SELECT * FROM movies<br>    -&gt; ;<br>+------+------------------+------------------+<br>| id   | title            | director         |<br>+------+------------------+------------------+<br>|    1 | jurrasic Park    | steven Spielberg |<br>|    2 | Avengers Endgame | russo brothers   |<br>+------+------------------+------------------+<br>2 rows in set (0.00 sec)</pre><p>Similarly we can use this command for different values .</p><p>Now as our data base is ready we can start to build our API .</p><h3>Lets create our API</h3><ol><li>First we will create an directory for example sqltest which i have made and similarly you can choose your name .</li></ol><pre>mkdir sqltest</pre><p>2. After making directory we will get into directory sqltest and initialize it .</p><pre>go mod init sqltest</pre><p>3. Now we will create a file main.go and one folder models which will be having out struct model and database functions which we will call through main.go file to perform operations.</p><pre>**sqltest - main folder<br>  -&gt;**models - <br>     -model.go - having stuct feilds<br>     - modeldb.go - have db functions which will be called in main.go<br>  - main.go - will have routers and handlers <br>  - go.mod - go modules which we will call throughout the API or say dependency<br>  - go.sum  -  generated file<br>  - test.http - rest.client file to test the API</pre><p>4. So , lets start working on our main.go file . which will be having router and handlers which will be calling functions for database execution according to our calls .</p><p>So we will 1st declare API endpoints .</p><pre>package main<br><br>import (<br> &quot;Sqltest/models&quot;<br> &quot;net/http&quot;<br><br> &quot;github.com/gin-gonic/gin&quot;<br>)<br><br>func main() {<br> router := gin.Default()<br> router.GET(&quot;/movies&quot;, listmoviesHandler)<br> router.POST(&quot;/movies&quot;, createmoviesHandler)<br> router.GET(&quot;/movies/:id&quot;, getmoviesbyid)<br> router.Run(&quot;localhost:8085&quot;)</pre><p>Here , i am using Gin framework so its very much simple to get , on each endpoints we are calling CRUD methods to perform handler functions. which are listmoviesHandler, createmoviesHandler, getmoviesbyid .</p><p>So each of the respective handler functions in the main.go are as follows:</p><p><strong>listmoviesHanlder</strong></p><p>This listmoviesHandler() calls the models.ListMoviesHandler function and will return an array of the Moviestruct from MySQL database. If the returned result is nil , we will send a response of 404, else we will use Indented.JSON which will return the values in movies1</p><pre>func listmoviesHandler(c *gin.Context) {<br> movies1 := models.ListMoviesHandler()<br> if movies1 == nil || len(movies1) == 0 {<br>  c.AbortWithStatus(http.StatusNotFound)<br> } else {<br>  c.IndentedJSON(http.StatusOK, movies1)<br> }<br><br>}</pre><p><strong>createmovieHandler</strong></p><p>This createmovieHandler() function adds a product from JSON received in the request body . It uses the Context.BindJSON to bind JSON data to the Moviestruct .</p><p>if there will be error in binding it will give you an error or else will append the mov in database movies</p><pre>func createmoviesHandler(c *gin.Context) {<br> var mov models.Movie<br><br> if err := c.BindJSON(&amp;mov); err != nil {<br>  c.AbortWithStatus(http.StatusBadRequest)<br> } else {<br>  models.CreateMoviesHandler(mov)<br>  c.IndentedJSON(http.StatusCreated, mov)<br> }<br>}</pre><p><strong>getmoviebyid</strong></p><p>This getmoviebyid() returns a movie which its ID is specified in the request parameter &quot;id&quot; and it calls the respective models.GetMoviesbyID function which returns the Movie struct when it’s found in the database.</p><pre>func getmoviesbyid(c *gin.Context) {<br> id := c.Param(&quot;id&quot;)<br><br> mov := models.GetMoviesbyID(id)<br><br> if mov == nil {<br>  c.AbortWithStatus(http.StatusNotFound)<br> } else {<br>  c.IndentedJSON(http.StatusOK, mov)<br> }<br>}</pre><p>5. Lets get into the folder models and create a file model.go in which we will create Movie struct in a separate package from the main. This is i am doing for code reusibility :)</p><pre>package models<br><br>type Movie struct {<br> ID       string `json:&quot;ID&quot;`<br> Title    string `json:&quot;title&quot;`<br> Director string `json:&quot;director&quot;`<br>}<br><br>func SampleMovies() []Movie {<br> var movies1 = []Movie{<br>  {ID: &quot;3&quot;, Title: &quot;AVATAAR&quot;, Director: &quot;JBCAKBLC&quot;},<br> }<br> return movies1<br>}</pre><p>So , we have declared struct similar to our MySQL table .</p><p><strong>Note: We use capital letter for the </strong><strong>Movie struct and all its feild names ad we want all them to be exported and usable by other packages , In Go name that is to be exported must begin with a capital letter.</strong></p><p>6. As our model.go is ready to rock , Now under models folder we will create one more file that is modeldb.go</p><p>To start with we will import the required packages database/sql package , which is generic interface for Go to deal with SQL database. Plus we will import MySQL driver with _ which is for initialising.</p><p><a href="https://github.com/go-sql-driver/mysql">GitHub - go-sql-driver/mysql: Go MySQL Driver is a MySQL driver for Go&#39;s (golang) database/sql package</a></p><p>Similar to main.go for 3 handler functions i will be creating 3 Database functions to call and there name you must have seen in the above code which i shared while making main.go</p><pre>package models<br><br>import (<br> &quot;database/sql&quot;<br><br> _ &quot;github.com/go-sql-driver/mysql&quot;<br><br> &quot;fmt&quot;<br>)<br><br>const dbuser = &quot;xxxx&quot;<br>const dbname = &quot;XXXX&quot;</pre><p>Let’s start with our database function.</p><p><strong>ListMoviesHandler</strong></p><p>This ListMovieHandler function in modeldb.go which returns an array Movie struct or nil on error.</p><pre>func ListMoviesHandler() []Movie {<br> db, err := sql.Open(&quot;mysql&quot;, dbuser+&quot;@tcp(127.0.0.1:3306)/&quot;+dbname)<br><br> if err != nil {<br>  fmt.Println(&quot;Err&quot;, err.Error())<br>  return nil<br> }<br><br> defer db.Close()<br><br> results, err := db.Query(&quot;SELECT * FROM movies&quot;)<br><br> if err != nil {<br>  fmt.Println(&quot;Err&quot;, err.Error())<br>  return nil<br><br> }<br> movies1 := []Movie{}<br> for results.Next() {<br>  var mov Movie<br>  err = results.Scan(&amp;mov.ID, &amp;mov.Title, &amp;mov.Director)<br><br>  if err != nil {<br>   panic(err.Error())<br>  }<br>  movies1 = append(movies1, mov)<br> }<br> return movies1<br>}</pre><p><strong>CreateMoviedHandler</strong></p><p>This function which takes Movie struct as its argument and insert the product into the database .</p><pre>func CreateMoviesHandler(movies Movie) {<br> db, err := sql.Open(&quot;mysql&quot;, dbuser+&quot;@tcp(127.0.0.1:3306)/&quot;+dbname)<br> if err != nil {<br>  fmt.Println(&quot;Err&quot;, err.Error())<br> }<br><br> defer db.Close()<br> insert, err := db.Query(<br>  &quot;INSERT INTO movies (id,title,director) VALUES (?,?,?)&quot;,<br>  movies.ID, movies.Title, movies.Director)<br><br> if err != nil {<br>  fmt.Println(&quot;Err&quot;, err.Error())<br> }<br> defer insert.Close()<br>}</pre><p><strong>GetMoviesbyID</strong></p><p>This function returns a Movie struct if it is present or nil if it is not found .</p><pre>func GetMoviesbyID(id string) *Movie {<br> db, err := sql.Open(&quot;mysql&quot;, dbuser+&quot;@tcp(127.0.0.1:3306)/&quot;+dbname)<br> mov := &amp;Movie{}<br> if err != nil {<br>  fmt.Println(&quot;Err&quot;, err.Error())<br>  return nil<br> }<br> defer db.Close()<br><br> results, err := db.Query(&quot;SELECT * FROM movies where id=?&quot;, id)<br><br> if err != nil {<br>  fmt.Println(&quot;Err&quot;, err.Error())<br>  return nil<br> }<br><br> if results.Next() {<br>  err = results.Scan(&amp;mov.ID, &amp;mov.Title, &amp;mov.Director)<br>  if err != nil {<br>   return nil<br>  }<br> } else {<br>   return nil<br> }<br> return mov<br> }<br><br>}</pre><p>7. Now i will create test.http file for testing the API , So our file will be something like this .</p><pre>GET http://localhost:8085/movies<br>###<br><br>POST http://localhost:8085/movies<br>Content-Type: application/json<br><br>{<br>   &quot;id&quot; : &quot;5&quot;,<br>   &quot;title&quot; : &quot;Micheal  Boy&quot;,<br>   &quot; director&quot; : &quot;Tansformers dark of the mood&quot;,<br>}<br>###<br><br>GET http://localhost:8085/movies/1<br>###<br></pre><p>In above rest Client file so here we are using it as client and we will be calling methods GET, POST, GET as you can check out in main.go which method calls which function and which handler function calls functions for database operation in models.modeldb.go</p><h3>Lets Test it Out !!</h3><p>To test our API</p><ol><li>We will execute</li></ol><pre>go build main.go<br>go mod tidy / go get .<br>go run main.go</pre><p>So as you run go run main.go you can see something like below will be coming if your main file executed well on the specified port under Run method.</p><pre><br>[GIN-debug] [WARNING] Creating an Engine instance with the Logger and Recovery middleware already attached.<br><br>[GIN-debug] [WARNING] Running in &quot;debug&quot; mode. Switch to &quot;release&quot; mode in production.<br> - using env:   export GIN_MODE=release<br> - using code:  gin.SetMode(gin.ReleaseMode)<br><br>[GIN-debug] GET    /movies                   --&gt; main.listmoviesHandler (3 handlers)<br>[GIN-debug] POST   /movies                   --&gt; main.createmoviesHandler (3 handlers)<br>[GIN-debug] DELETE /movies/:id               --&gt; main.deletemoviesHandler (3 handlers)<br>[GIN-debug] GET    /movies/:id               --&gt; main.getmoviesbyid (3 handlers)<br>[GIN-debug] [WARNING] You trusted all proxies, this is NOT safe. We recommend you to set a value.<br>Please check https://pkg.go.dev/github.com/gin-gonic/gin#readme-don-t-trust-all-proxies for details.<br>[GIN-debug] Listening and serving HTTP on localhost:8085</pre><p>This shows that on port :8085 is ready to lsiten and serve my endpoint calls.</p><p>2. Now we will run 1st method listmoviesHandler that is under /movies to execute that method we will execute the below method using test.http</p><p>file.</p><pre>Send Request<br>GET http://localhost:8085/movies<br>###</pre><p>Now we will click on send request open in the test.http file .</p><p><strong>OUTPUT</strong></p><pre>HTTP/1.1 200 OK<br>Content-Type: application/json; charset=utf-8<br>Date: Sat, 17 Dec 2022 08:31:22 GMT<br>Content-Length: 372<br>Connection: close<br><br>[<br>  {<br>    &quot;ID&quot;: &quot;1&quot;,<br>    &quot;title&quot;: &quot;jurassic park&quot;,<br>    &quot;director&quot;: &quot;steven Spielberg&quot;<br>  },<br>  {<br>    &quot;ID&quot;: &quot;2&quot;,<br>    &quot;title&quot;: &quot;Avengers Endgame&quot;,<br>    &quot;director&quot;: &quot;russo brothers&quot;<br>  },<br>]</pre><p>As we have seen in Database movies creation we get the whole data .</p><p>3. Similarly we will perform for /movies to call createmovieHandler function to add value in database.</p><pre>Send Request<br>POST http://localhost:8085/movies<br>Content-Type: application/json<br><br>{<br>   &quot;id&quot; : &quot;3&quot;,<br>   &quot;title&quot; : &quot;Micheal  Boy&quot;,<br>   &quot; director&quot; : &quot;Tansformers dark of the mood&quot;,<br>}<br>###</pre><p>on clicking Send Request for POST we will get</p><p><strong>OUTPUT</strong></p><pre>HTTP/1.1 201 Created<br>Content-Type: application/json; charset=utf-8<br>Date: Sat, 17 Dec 2022 08:40:31 GMT<br>Content-Length: 66<br>Connection: close<br><br>{<br>  &quot;ID&quot;: &quot;3&quot;,<br>  &quot;title&quot;: &quot;Micheal  Boy&quot;,<br>  &quot;director&quot;: &quot;Transformers dark of the mood&quot;<br>}</pre><p>Now we can again call listmovieHandler function method to see the list all the movies.</p><pre>HTTP/1.1 200 OK<br>Content-Type: application/json; charset=utf-8<br>Date: Sat, 17 Dec 2022 08:31:22 GMT<br>Content-Length: 372<br>Connection: close<br><br>[<br>  {<br>    &quot;ID&quot;: &quot;1&quot;,<br>    &quot;title&quot;: &quot;jurassic park&quot;,<br>    &quot;director&quot;: &quot;steven Spielberg&quot;<br>  },<br>  {<br>    &quot;ID&quot;: &quot;2&quot;,<br>    &quot;title&quot;: &quot;Avengers Endgame&quot;,<br>    &quot;director&quot;: &quot;russo brothers&quot;<br>  },<br>  {<br>  &quot;ID&quot;: &quot;3&quot;,<br>  &quot;title&quot;: &quot;Micheal  Boy&quot;,<br>  &quot;director&quot;: &quot;Transformers dark of the mood&quot;<br>  }<br>]<br></pre><p>Yeah !!</p><p>8. Now we will try to call third and last function getmoviebyid to get the specific movie with :id so similarly above 2 methods we need to click n send request option in test.http file .</p><pre>Send Request<br>GET http://localhost:8085/movies/2<br>###</pre><p>we are trying to fetch value of :id = 2 from our database</p><p><strong>OUTPUT</strong></p><pre>HTTP/1.1 200 OK<br>Content-Type: application/json; charset=utf-8<br>Date: Sat, 17 Dec 2022 08:48:18 GMT<br>Content-Length: 84<br>Connection: close<br><br>{<br>  &quot;ID&quot;: &quot;2&quot;,<br>  &quot;title&quot;: &quot;Avengers Endgame&quot;,<br>  &quot;director&quot;: &quot;russo brothers&quot;<br>}</pre><p>That’s it ..:)</p><p>we have made it .</p><p>Similarly, you can implement <strong>DELETE</strong> method also .</p><p><strong><em>Do clap on the article if you liked it . Mention topics in comments on which i should write on coming next articles .</em></strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d5a8ef70348f" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>