<?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 Steven on Medium]]></title>
        <description><![CDATA[Stories by Steven on Medium]]></description>
        <link>https://medium.com/@stev3npy?source=rss-4b256497da11------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*qLI1sdgtTZKDxEeKl9FowA.jpeg</url>
            <title>Stories by Steven on Medium</title>
            <link>https://medium.com/@stev3npy?source=rss-4b256497da11------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 22:01:22 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@stev3npy/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[The Go Paradox: Why Go’s Simplicity Creates Complexity]]></title>
            <link>https://medium.com/@stev3npy/the-go-paradox-why-gos-simplicity-creates-complexity-f835ba08156f?source=rss-4b256497da11------2</link>
            <guid isPermaLink="false">https://medium.com/p/f835ba08156f</guid>
            <category><![CDATA[backend]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Steven]]></dc:creator>
            <pubDate>Sun, 15 Mar 2026 19:11:57 GMT</pubDate>
            <atom:updated>2026-03-15T19:11:57.928Z</atom:updated>
            <content:encoded><![CDATA[<h4>When “easy to learn” meets “hard to master”</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GwSGvcuaRJiYXUnf5ZCapA.jpeg" /></figure><p>I still remember the first time I wrote a program in Go. It was a QR code generator with a GUI, maybe 50 lines of code and it worked on the first compile.No dependency hell, no complex build configuration, just a binary that ran anywhere. I was sold. “Finally,” I thought, “a language that respects my time.”</p><p>Four years and several production services later, I’ve developed a more nuanced relationship with Go. Don’t get me wrong I still reach for it by default. But I’ve come to realize something that isn’t immediately obvious when you’re learning the language</p><p><strong>But simplicity in a programming language can be deceptive. </strong>Go’s simplicity is actually a form of complexity in disguise.</p><p>Let me explain what I mean by that, starting with that QR code generator.</p><h3>My First Program: A Case Study in Hidden Complexity</h3><p>Here’s the code (slightly simplified from my original):</p><pre>func main() {<br> myApp := app.New()<br> myWindow := myApp.NewWindow(&quot;QR Code Generator&quot;)<br><br> input := widget.NewEntry()<br> input.SetPlaceHolder(&quot;Enter data to encode&quot;)<br><br> qrCodeContainer := container.NewVBox()<br><br> generateButton := widget.NewButton(&quot;Generate QR Code&quot;, func() {<br>  data := input.Text<br>  if data == &quot;&quot; {<br>   dialog.ShowInformation(&quot;Error&quot;, &quot;Please enter data to encode&quot;, myWindow)<br>   return<br>  }<br><br>  // Generate QR code and save to file<br>  err := qrcode.WriteFile(data, qrcode.Medium, 256, &quot;qrcode.png&quot;)<br>  if err != nil {<br>   dialog.ShowInformation(&quot;Error&quot;, &quot;Failed to generate QR code&quot;, myWindow)<br>   log.Fatalf(&quot;Failed to generate QR code: %v&quot;, err)<br>  }<br><br>  file, err := os.Open(&quot;qrcode.png&quot;)<br>  if err != nil {<br>   dialog.ShowInformation(&quot;Error&quot;, &quot;Failed to open generated QR code&quot;, myWindow)<br>   log.Fatalf(&quot;Failed to open QR code image: %v&quot;, err)<br>  }<br>  defer file.Close()<br><br>  // Display the QR code image in the container<br>  img := canvas.NewImageFromFile(&quot;qrcode.png&quot;)<br>  img.FillMode = canvas.ImageFillContain<br>  img.SetMinSize(fyne.NewSize(256, 256))<br>  qrCodeContainer.Objects = []fyne.CanvasObject{img}<br>  qrCodeContainer.Refresh()<br> })<br><br> content := container.NewVBox(<br>  widget.NewLabel(&quot;QR Code Generator&quot;),<br>  input,<br>  generateButton,<br>  qrCodeContainer,<br> )<br> myWindow.SetContent(content)<br> myWindow.Resize(fyne.NewSize(300, 400))<br><br> myWindow.ShowAndRun()<br>}</pre><p>When I wrote this, I thought Go was incredibly straightforward. But looking back, I can see the seeds of complexity hiding in plain sight.</p><p><strong>The error handling repetition:</strong> Every operation that can fail needs its own if err != nil block. In this small program, that&#39;s fine. In a larger application, this pattern becomes noise that hides the actual logic.</p><p><strong>The resource management dance:</strong> Notice defer file.Close()? That&#39;s Go&#39;s elegant solution to resource cleanup. But it&#39;s also a subtle trap, once multiple files or resources are involved, I’d need to reason about which defer runs and when, especially if errors occur mid-function.</p><p><strong>The GUI callback complexity:</strong> That button callback is doing <em>everything </em>I/O, error handling, GUI updates, and resource cleanup. Go’s lack of shorthand lambdas means even simple inline functions need full syntax. And because there’s no built-in async/await, if qrcode.WriteFile was slow, it would freeze the GUI. I didn&#39;t realize this at the time because my test data was small.</p><p>This program worked perfectly for what I needed. But it also taught me habits I’d later need to unlearn: mixing I/O with UI logic, using log.Fatalf in user-facing code (which kills the entire program instead of gracefully handling the error), and treating defer as magic cleanup dust.</p><h3>The Philosophy: Simplicity Is Complicated</h3><p>Go’s creators, led by Rob Pike, have always been transparent about the language’s philosophy. In his famous talk <strong>“Simplicity is Complicated,”</strong> Pike argued that Go achieves simplicity not by being simple to implement, but by hiding complexity behind clean abstractions .</p><p>The garbage collector, goroutines, interfaces…All of these features feel effortless to use because enormous engineering complexity lives beneath the surface. As Pike puts it: “Go is actually complex, but it <em>feels</em> simple” .</p><p>This is the <strong>Go Paradox</strong>.</p><p>The language optimizes for reading code over writing code, and for compiler simplicity over developer convenience. Most of the time, this trade-off works beautifully. But sometimes the gap between <em>“feels simple”</em> and <em>“actually simple”</em> becomes a trap.</p><h3>The Traps Hidden in Simplicity</h3><p>Once you start building real systems in Go, certain patterns start to appear. The language still feels simple, but some design choices introduce <strong>unexpected complexity over time</strong>. Here are a few that caught me off guard;</p><h3>Trap #1: The Zero Value “Gotcha”</h3><p>Here’s a riddle that stumped me months after that first program:</p><pre>var s []int<br>s = append(s, 42) // Works fine!<br><br>var m map[string]int<br>m[&quot;key&quot;] = 42 // Panic: assignment to entry in nil map</pre><p>Both s and m are uninitialized. Both are technically nil. So why does one work and the other crash your program?</p><p>The official explanation makes sense once you understand it: slices are descriptors (pointer, length, capacity), and append is designed to handle a nil pointer by allocating memory . Maps, however, are hash tables that need internal initialization before you can write to them. Reading from a nil map returns the zero value safely, writing requires an allocated structure.</p><p>But here’s the paradox: Go’s commitment to zero values being “<em>useful</em>” actually creates a cognitive burden. You have to remember which nil types are “<em>safe</em>” and which will panic. The language that prides itself on “<em>only one way to do things</em>” has two different behaviors for what looks like the same pattern.</p><p>The recent reimplementation of maps using Swiss Tables in Go 1.24 improves performance but doesn’t change this fundamental inconsistency. It’s a design decision baked deep into the language, one that trades implementation simplicity for user confusion.</p><h3>Trap #2: The “Simple” Concurrency That Isn’t</h3><p>Back to my QR generator: what if I wanted to generate multiple QR codes concurrently? Goroutines make this look easy:</p><pre>func processItems(items []Item) {<br>    for _, item := range items {<br>        go func(i Item) {<br>            result, err := process(i)<br>            // Wait, how do I return this result?<br>            // What if this panics?<br>            // How do I know when everything is done?<br>        }(item)<br>    }<br>    // Function returns immediately... but goroutines are still running<br>}</pre><p>The go keyword is simple. Coordinating goroutines is not. Channels help, but they introduce their own complexity (buffered vs. unbuffered, send/receive semantics, closing conventions). Meanwhile, the language that removed exceptions in favor of explicit error handling gives you goroutines that can panic silently in the background if you&#39;re not careful.</p><p>Compare this to async/await in other languages, where the syntax explicitly marks where concurrency happens and where synchronization is required. Go’s approach is cleaner on the surface but requires more discipline to use correctly.</p><h3>Trap #3: The Generics Timeline</h3><p>For almost a decade, Go existed without generics. The official stance was that they weren’t necessary, that interfaces and code generation covered most use cases.</p><p>In practice, this led to heavy use of interface{} across the ecosystem.</p><p>Libraries stored values as interface{}.<br> JSON decoding produced map[string]interface{}.<br> Frameworks passed context values through empty interfaces.</p><p>This wasn’t just ugly, it was <strong>type-unsafe by design</strong>.</p><p>Go 1.18 finally introduced generics in 2022, which dramatically improved the situation, but the long delay created technical debt that generics couldn’t instantly erase.</p><p>Many libraries were built around workarounds that still exist today.</p><p>The Go team continues expanding generics, but the ecosystem is still adjusting to a feature that arrived much later than many developers expected.</p><p>The community is celebrating this news, but one comment stuck with me: “<em>My internal utility library has a bunch of workarounds for missing generic methods and they all annoy the hell out of me</em>” . That’s a decade of accumulated frustration, finally being addressed piece by piece.</p><h3>Trap #4: Error Handling Verbosity</h3><p>You’ve seen this pattern in my QR code:</p><pre>err := qrcode.WriteFile(data, qrcode.Medium, 256, &quot;qrcode.png&quot;)<br>if err != nil {<br>    dialog.ShowInformation(&quot;Error&quot;, &quot;Failed to generate QR code&quot;, myWindow)<br>    log.Fatalf(&quot;Failed to generate QR code: %v&quot;, err)<br>}</pre><p>Repeat this three times in a function, and you’ve got more error-checking than business logic. Go’s explicit error handling is admirable, you can’t ignore errors, but in practice it often leads to <strong>error fatigue</strong>, with developers writing if err != nil { return err } on autopilot., without actually handling the error.</p><p>Looking back at my code, I used log.Fatalf twice. That&#39;s a blunt instrument, it prints the error and immediately terminates the program. For a command-line tool, fine. For a GUI application, it&#39;s user-hostile. The &quot;<em>simple</em>&quot; approach forced me to choose between verbose proper error propagation or quick and dirty exits.</p><p>The irony? Go’s standard library often wraps errors with context using fmt.Errorf(&quot;doing something: %w&quot;, err), but the language doesn&#39;t provide built-in syntax for this. The &quot;<em>simple</em>&quot; approach forces you to either write verbose boilerplate or lose valuable debugging information.</p><h3>Why We Still Use Go (Despite All This)</h3><p>If Go has all these rough edges, why is it still my go-to language? Because the paradox cuts both ways.</p><p>The simplicity that creates traps also creates clarity. When I read Go code, especially code I wrote six months ago, I understand it immediately. There’s no operator overloading to decode, no inheritance hierarchies to trace, no magic methods being called behind the scenes. What you see is what you get.</p><p>The garbage collector really does “<em>just work</em>” for most use cases. The build speed is still unmatched. The cross-compilation story is delightful. And the concurrency model, once you internalize it, is genuinely powerful.</p><p>But more importantly, Go’s limitations force good habits. The lack of function overloading makes you name things clearly. The flat package structure encourages thinking about public APIs carefully. The explicit error handling (despite the verbosity) makes failure modes visible.</p><p>My QR code generator was simple enough that these trade-offs didn’t matter. But as I built larger systems, I found that Go’s constraints kept me honest. I couldn’t hide complexity behind abstractions because the language doesn’t provide many abstraction mechanisms. I had to actually simplify my design.</p><h3>Making Peace with the Paradox</h3><p>If you’re learning Go, or considering it for a new project, here’s my advice: don’t mistake “<em>simple to learn</em>” for “<em>simple to use</em>.” Go has a gentle learning curve because it has few features, but mastering those features, understanding the goroutine lifecycle, internalizing the zero value behavior, designing with interfaces, takes time.</p><p>When you encounter something that feels awkward (like make() having different behaviors for slices vs. maps), remember that it&#39;s usually a trade-off. The make() ambiguity exists because the language avoided function overloading and generic functions for years . It&#39;s not an oversight, it&#39;s a design choice with consequences.</p><h3>The Bottom Line</h3><p>Go’s paradox is that it achieves simplicity for the machine (fast compilation, efficient execution, straightforward semantics) while pushing some complexity onto the developer (verbose error handling, nil behavior inconsistencies, limited abstraction tools).</p><p>This isn’t necessarily bad, it’s just a choice. And it’s a choice that works remarkably well for certain domains: network services, command-line tools, cloud infrastructure. But it works less well when you need rich domain models, complex data transformations, or functional programming patterns.</p><p>I still write Go almost every day. I’ve learned to love its quirks, or at least to work around them. But I’ve stopped telling people that Go is “<em>simple.</em>” Instead, I say it’s opinionated, and those opinions will either match your needs or fight against them.</p><p>The best thing you can do is understand those opinions upfront. Don’t just learn the syntax, learn the philosophy. Read Rob Pike’s talks . Understand why slices and maps behave differently. Accept that you’ll write if err != nil a thousand times.</p><p><strong>Go’s simplicity isn’t a lie, it’s just complicated.</strong></p><p>What’s your experience with Go’s learning curve? Did you hit any of these “<em>simple</em>” traps when you were starting out? I’d love to hear about it in the comments.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f835ba08156f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Writing a Simple Proof-of-Work Algorithm in Go]]></title>
            <link>https://medium.com/@stev3npy/writing-a-simple-proof-of-work-algorithm-in-go-7c89c7a6e38f?source=rss-4b256497da11------2</link>
            <guid isPermaLink="false">https://medium.com/p/7c89c7a6e38f</guid>
            <category><![CDATA[proof-of-work]]></category>
            <category><![CDATA[blockchain-basics]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[mining-algorithm]]></category>
            <dc:creator><![CDATA[Steven]]></dc:creator>
            <pubDate>Sun, 26 Jan 2025 15:07:02 GMT</pubDate>
            <atom:updated>2025-01-26T15:07:02.333Z</atom:updated>
            <content:encoded><![CDATA[<p>Ever wondered what goes on behind the scenes of blockchain mining? At its core is the <strong>Proof-of-Work (PoW)</strong> algorithm — a mechanism that ensures the security and consistency of blockchain networks by requiring computational effort to validate transactions. In this article, we’ll break down PoW concepts, build a basic PoW algorithm in Go, and dive into its implications for blockchain security.</p><p>If you’re looking for the full source code to follow along, it’s available on <a href="https://github.com/MuxN4/pow">GitHub</a>. Drop it a star if you find it helpful!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*078LmBlXideq9DB-hg0KRw.png" /></figure><h4>So, What Exactly Is Proof-of-Work?</h4><p>Proof-of-Work is like solving a cryptographic puzzle. Miners compete to find a solution, which is computationally expensive to find but easy to verify. This mechanism ensures that blocks are added to the blockchain in a manner that cannot be tampered with.</p><p>Here’s the TL;DR of PoW:</p><ul><li><strong>Nonce</strong>: A number miners adjust to find the correct solution.</li><li><strong>Hash</strong>: The unique digital fingerprint generated by a cryptographic function (SHA-256, in our case).</li><li><strong>Target</strong>: The puzzle difficulty, represented by the number of leading zeros a hash must have.</li><li><strong>Genesis Block</strong>: The first block in the blockchain, where it all begins.</li></ul><h4>Building the Algorithm in Go</h4><p>Go’s simplicity and performance make it an excellent choice for implementing PoW. We’ll structure our project into three parts:</p><ol><li><strong>Blocks</strong>: The fundamental unit of the blockchain.</li><li><strong>Proof-of-Work</strong>: The algorithm that governs mining.</li><li><strong>Main Function</strong>: Where everything comes together.</li></ol><p><strong>Step 1: Creating the Block</strong></p><p>Each block contains data (e.g., transactions), a reference to the previous block, and a hash. Here’s how we define a block in Go:</p><pre>type Block struct {<br>    Index        int<br>    Timestamp    int64<br>    Data         string<br>    PreviousHash string<br>    Hash         string<br>    Nonce        int<br>    Difficulty   int<br>}</pre><p>We calculate the block’s hash using its fields:</p><pre>func (b *Block) CalculateHash() string {<br>    record := strconv.Itoa(b.Index) +<br>              strconv.FormatInt(b.Timestamp, 10) +<br>              b.Data +<br>              b.PreviousHash +<br>              strconv.Itoa(b.Nonce)<br><br>    h := sha256.New()<br>    h.Write([]byte(record))<br>    return hex.EncodeToString(h.Sum(nil))<br>}</pre><p><strong>Step 2: Implementing Proof-of-Work</strong></p><p>The goal of mining is to find a hash that starts with a specific number of zeros (difficulty). Here’s how we create and execute the PoW algorithm:</p><pre>func (pow *ProofOfWork) Mine() (bool, int, time.Duration) {<br>    startTime := time.Now()<br><br>    for pow.block.Nonce &lt; pow.maxNonce {<br>        hash := pow.block.CalculateHash()<br><br>        if strings.HasPrefix(hash, pow.target) {<br>            pow.block.Hash = hash<br>            return true, pow.block.Nonce, time.Since(startTime)<br>        }<br><br>        pow.block.Nonce++<br>    }<br><br>    return false, -1, time.Since(startTime)<br>}</pre><p>We also validate mined blocks with a simple check:</p><pre>func (pow *ProofOfWork) Validate() bool {<br>    return strings.HasPrefix(pow.block.Hash, pow.target)<br>}</pre><p><strong>Step 3: Bringing It All Together</strong></p><p>Let’s simulate a blockchain in main.go. We start with a <strong>Genesis Block</strong> and mine additional blocks with increasing difficulty:</p><pre>func main() {<br>    blockchain := NewBlockchain()<br><br>    difficulties := []int{2, 4, 6}<br>    for _, diff := range difficulties {<br>        blockchain.AddBlock(fmt.Sprintf(&quot;Transaction at difficulty %d&quot;, diff), diff)<br>    }<br><br>    fmt.Println(&quot;🎉 Mining Complete!&quot;)<br>}</pre><p>Each mined block includes metadata like difficulty, nonce, hash, and the time taken to mine it.</p><h4>Running the Code</h4><p>Clone the repository, navigate to the project directory, and run it. You’ll see output like this:</p><pre>🚀 Starting Mining Process...<br>⛏️  Block mined!<br>    Difficulty:   2<br>    Nonce:        150<br>    Time:         0.35s<br>    Hash:         003f6e3c...<br>    Prev Hash:    [Genesis Block]<br><br>⛏️  Block mined!<br>    Difficulty:   4<br>    Nonce:        2738<br>    Time:         1.89s<br>    Hash:         0000c7ff...<br>    Prev Hash:    003f6e3c...<br><br>🎉 Mining Complete!</pre><h4>Why It Matters</h4><ul><li><strong>Security</strong>: PoW ensures only legitimate blocks are added, protecting the blockchain against tampering.</li><li><strong>Energy Consumption</strong>: Mining requires significant computational effort. While PoW secures the network, its energy usage has sparked debates, prompting exploration of alternatives like Proof-of-Stake (PoS).</li></ul><h4>Going Further</h4><p>Want to take it up a notch? Here are some ideas:</p><ul><li>Add dynamic difficulty adjustment based on mining time (and hey, you might spot it in the code already — but if not, why not give it a shot yourself?).</li><li>Implement a blockchain explorer to visualize blocks and transactions.</li><li>Experiment with different cryptographic hashing algorithms.</li></ul><p>For the complete source code and more inspiration, check out the <a href="https://github.com/MuxN4/pow">GitHub repository</a>.</p><h4>Conclusion</h4><p>Proof-of-Work might seem daunting at first, but with Go’s powerful standard library, it’s surprisingly simple to implement. By walking through the process of creating a PoW algorithm, you’ve not only learned the mechanics of mining but also gained insights into its role in blockchain technology.</p><p>Feel free to share your thoughts, improvements, or questions — and don’t forget to star the <a href="https://github.com/MuxN4/pow">repo</a> if this guide helped you!</p><p>Happy mining! 🎉</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7c89c7a6e38f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Benchmarking in Go: Writing Microbenchmarks That Matter]]></title>
            <link>https://medium.com/@stev3npy/benchmarking-in-go-writing-microbenchmarks-that-matter-e37cf0440868?source=rss-4b256497da11------2</link>
            <guid isPermaLink="false">https://medium.com/p/e37cf0440868</guid>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[go]]></category>
            <category><![CDATA[benchmarking]]></category>
            <category><![CDATA[benchmark]]></category>
            <dc:creator><![CDATA[Steven]]></dc:creator>
            <pubDate>Sat, 11 Jan 2025 14:33:42 GMT</pubDate>
            <atom:updated>2025-01-11T14:33:42.189Z</atom:updated>
            <content:encoded><![CDATA[<p>Benchmarking is more than just measuring how fast a piece of code runs. It’s about uncovering hidden inefficiencies, understanding trade-offs, and optimizing for real-world scenarios. In Go, benchmarking is baked right into the language through its testing tools. But here’s the kicker, if you benchmark the wrong way, your results are garbage. So, let’s dive into how to write meaningful benchmarks that tell the truth and help you write better, faster Go code.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/612/1*p2tGTH4zFZvBIxC9D275tQ.jpeg" /></figure><h3>Why Benchmarking?</h3><p>Imagine this; you’re in a car race, testing a new engine. If your stopwatch is broken or you’re testing on a treadmill or even better a simulator, instead of the actual racetrack, how the hell will you know if it’s any good? Benchmarking in Go is your racetrack. It lets you:</p><ol><li><strong>Measure performance accurately</strong> (no more guesswork).</li><li><strong>Spot bottlenecks</strong> in your code (like figuring out what’s slowing you down).</li><li><strong>Compare implementations</strong> to find the best approach.</li><li><strong>Justify trade-offs</strong> to your boss (or yourself and have solid proof when explaining them).</li></ol><p>But sloppy benchmarks that don’t account for noise, caching, or other quirks can lead you astray. Let’s make sure you don’t fall into those traps.</p><h3>Basics: Go’s Benchmarking Framework</h3><p>Go’s testing package makes benchmarking stupidly simple (on the surface at least). Here’s the skeleton of a benchmark:</p><pre>package main<br><br>import (<br> &quot;testing&quot;<br>)<br><br>func BenchmarkAdd(b *testing.B) {<br> for i := 0; i &lt; b.N; i++ {<br>  _ = 1 + 1 // Replace this with your actual code<br> }<br>}</pre><p>Run this benchmark with:</p><pre>go test -bench=.</pre><p>What’s happening here?</p><ul><li>b *testing.B is your benchmark control panel.</li><li>b.N is the number of iterations Go decides to run (it adjusts automatically for meaningful results).</li><li>The loop ensures the operation is executed multiple times.</li></ul><p>Simple, right? But there’s more than meets the eye.</p><h3>Writing Meaningful Benchmarks</h3><h3>1. Focus on Real Scenarios</h3><p>Benchmarking something nobody cares about is a waste of time. Let’s say you’re benchmarking a string concatenation function. Don’t test it on a single small string, test it on typical workloads for your app. Here’s an example:</p><pre>func BenchmarkConcat(b *testing.B) {<br> words := []string{&quot;Go&quot;, &quot;is&quot;, &quot;fast&quot;, &quot;and&quot;, &quot;awesome&quot;}<br> for i := 0; i &lt; b.N; i++ {<br>  _ = joinStrings(words)<br> }<br>}<br><br>func joinStrings(words []string) string {<br> return strings.Join(words, &quot; &quot;)<br>}</pre><p>This benchmark simulates joining an array of strings, something you might do often in real life.</p><h3>2. Avoid Common Pitfalls</h3><ul><li><strong>Global Variables and Caching</strong>: If your code uses global variables or caches results, your benchmark might measure cached results instead of real computation.</li></ul><p><strong>Bad Benchmark:</strong></p><pre>var result string<br><br>func BenchmarkBad(b *testing.B) {<br>    for i := 0; i &lt; b.N; i++ {<br>        result = &quot;cached value&quot;<br>    }<br>}</pre><p>This doesn’t test anything useful.</p><ul><li><strong>Memory Allocation Overhead</strong>: If your benchmark involves a lot of memory allocations, you might be measuring the garbage collector instead of your actual code. Simply use b.ReportAllocs() to track allocations.</li></ul><p><strong>Example:</strong></p><pre>func BenchmarkAlloc(b *testing.B) {<br>    b.ReportAllocs()<br>    for i := 0; i &lt; b.N; i++ {<br>        _ = make([]byte, 1024)<br>    }<br>}</pre><h3>3. Be Mindful of Compiler Optimizations</h3><p>Go’s compiler is smart, sometimes too smart. If it notices you’re not using the result of a computation, it might optimize it away. To prevent this, use a global variable to “consume” the result.</p><p><strong>Preventing Optimization:</strong></p><pre>var sink interface{}<br><br>func BenchmarkOptimized(b *testing.B) {<br> for i := 0; i &lt; b.N; i++ {<br>  sink = expensiveFunction()<br> }<br>}<br><br>func expensiveFunction() int {<br> return 42<br>}</pre><h3>4. Measure What Matters</h3><p>Sometimes raw speed isn’t the only metric.<strong> </strong>Depending on your use case, consider benchmarking:</p><ul><li><strong>Memory Usage</strong> (e.g., b.ReportAllocs())</li><li><strong>Throughput</strong> (e.g., bytes processed per second)</li><li><strong>Concurrency</strong> (e.g., performance with multiple goroutines)</li></ul><p><strong>Example: Throughput Benchmark:</strong></p><pre>func BenchmarkProcessBytes(b *testing.B) {<br> data := make([]byte, 1024*1024) // 1 MB<br> for i := 0; i &lt; b.N; i++ {<br>  processBytes(data)<br> }<br>}<br><br>func processBytes(data []byte) int {<br> return len(data)<br>}</pre><h3>5. Compare Alternatives</h3><p>Want to know if your fancy algorithm is faster than the simple one? Benchmark both, but don’t forget, meaningful comparisons require realistic inputs.</p><p><strong>Example:</strong></p><pre>func BenchmarkMapLookup(b *testing.B) {<br> m := map[string]int{&quot;a&quot;: 1, &quot;b&quot;: 2, &quot;c&quot;: 3}<br> for i := 0; i &lt; b.N; i++ {<br>  _ = m[&quot;a&quot;]<br> }<br>}<br><br>func BenchmarkSliceLookup(b *testing.B) {<br> s := []struct {<br>  key string<br>  value int<br> }{{&quot;a&quot;, 1}, {&quot;b&quot;, 2}, {&quot;c&quot;, 3}}<br> for i := 0; i &lt; b.N; i++ {<br>  for _, item := range s {<br>   if item.key == &quot;a&quot; {<br>    _ = item.value<br>    break<br>   }<br>  }<br> }<br>}</pre><h3>Interpreting Results</h3><p>When you run benchmarks, you’ll see something like this:</p><pre>BenchmarkAdd-8          2000000000               0.28 ns/op<br>BenchmarkConcat-8       50000000                30.5 ns/op</pre><p>Here’s what it means:</p><ul><li><strong>Benchmark Name</strong>: BenchmarkAdd-8 (the -8 means it was run on 8 threads).</li><li><strong>Iterations</strong>: 2000000000 (how many times the benchmark loop ran).</li><li><strong>Time per Iteration</strong>: 0.28 ns/op (nanoseconds per operation).</li></ul><h3>Key Questions to Ask:</h3><ol><li>Are the results consistent across multiple runs?</li><li>Is the time per operation realistic for your workload?</li><li>How does it compare to alternatives?</li></ol><h3>Best Practices</h3><ul><li><strong>Run Benchmarks in Isolation</strong>: Background processes, open apps, or system updates can mess with results. Close unnecessary apps get consistent results.</li><li><strong>Use Stable Inputs</strong>: Don’t benchmark with random or unrealistic data unless it’s representative of real-world scenarios.</li><li><strong>Repeat and Average</strong>: Run benchmarks multiple times to account for variability.</li><li><strong>Use Tools Like </strong><strong>benchstat</strong>: Go’s benchstat tool can help compare results statistically by analyzing multiple runs to identify performance changes</li></ul><p><strong>Example Command:</strong></p><pre>benchstat old.txt new.txt</pre><ul><li><strong>old.txt and </strong><strong>new.txt</strong> contain the benchmark results before and after optimization.</li><li><strong>benchstat</strong> compares the performance differences between the two.</li></ul><h3>Challenge: Benchmark Your Own Code</h3><p>Now it’s your turn. Take a function from your project and write a benchmark for it. Measure:</p><ol><li>Time per operation.</li><li>Allocations per operation.</li><li>Compare it with an alternative implementation.</li></ol><p>Prove that your function is as fast as you think. Or maybe find out it’s slow as shit and needs fixing — mine did. Either way, you’ll learn something.</p><h3>Conclusion</h3><p>Benchmarking in Go isn’t just about running go test -bench=. and calling it a day. It’s about crafting benchmarks that reflect reality, interpreting results thoughtfully, and making informed decisions based on data. Done right, it’s an art form, one that can turn your Go code from decent to damn fast. So go forth, benchmark wisely, and make your code scream. Godspeed.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e37cf0440868" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[GoCheerio: An Open Source Opportunity for Go Developers]]></title>
            <link>https://medium.com/@stev3npy/gocheerio-an-open-source-opportunity-for-go-developers-a98420eded70?source=rss-4b256497da11------2</link>
            <guid isPermaLink="false">https://medium.com/p/a98420eded70</guid>
            <category><![CDATA[open-source]]></category>
            <category><![CDATA[dom-manipulation]]></category>
            <category><![CDATA[web-scraping]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Steven]]></dc:creator>
            <pubDate>Wed, 20 Nov 2024 20:30:28 GMT</pubDate>
            <atom:updated>2024-11-20T20:30:28.010Z</atom:updated>
            <content:encoded><![CDATA[<p><a href="https://github.com/MuxN4/gocheerio">🌟 <strong>Star the Project on GitHub</strong></a> | <a href="https://github.com/MuxN4/gocheerio"><strong>Fork and Join the Journey</strong></a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*dczkNZu0-Cpc6ARv0zzzHw.png" /></figure><h3>Bridging the Gap: A Cheerio-Inspired Go Library</h3><p>Web scraping and HTML parsing are essential skills in modern software development, but Go developers have long lacked a comprehensive, user-friendly library similar to JavaScript’s popular Cheerio. Enter <strong>GoCheerio</strong> — an ambitious open-source project aiming to change that landscape.</p><h3>What Makes GoCheerio Unique?</h3><p>Born from the need for a robust, Go-native HTML parsing and manipulation library, GoCheerio isn’t just another project — it’s a collaborative mission to create a powerful tool for the Go community. Inspired by the JavaScript Cheerio library, it promises to bring intuitive CSS selector support, efficient DOM traversal, and memory-conscious design to Go developers.</p><h3>Why Contribute to GoCheerio?</h3><h3>1. Real-World Skill Development</h3><p>Contributing to GoCheerio isn’t just about writing code — it’s about mastering Go development in a practical, impactful context. You’ll gain hands-on experience in:</p><ul><li>Advanced Go programming techniques</li><li>DOM manipulation</li><li>Selector parsing and matching</li><li>Performance optimization</li><li>Streaming parser design</li></ul><h3>2. Open Collaboration, Meaningful Impact</h3><p>The project is currently in its early stages, with the first phase of core DOM implementation complete. This means your contributions can genuinely shape the library’s future. Whether you’re fixing a bug, enhancing performance, or expanding feature support, your work will be directly visible and valuable.</p><h3>Key Contribution Opportunities</h3><h3>CSS Selector Enhancements</h3><ul><li>Implement support for complex selectors</li><li>Add pseudo-class selector parsing</li><li>Improve attribute selector matching</li></ul><blockquote><strong>Interested in web standards? Dive into pseudo-class and advanced CSS selector support!</strong></blockquote><h3>Performance Optimization</h3><ul><li>Create comprehensive benchmarking tests</li><li>Optimize selector matching algorithms</li><li>Design intelligent caching mechanisms</li></ul><blockquote><strong>Are you a performance enthusiast? Help optimize selector matching and build intelligent caching systems!</strong></blockquote><h3>Streaming Parser Development</h3><ul><li>Build a memory-efficient streaming HTML parser</li><li>Develop callback-based processing systems</li><li>Enable handling of large HTML documents</li></ul><blockquote><strong>Love working with streams? Join to tackle large-scale HTML parsing with innovative streaming solutions!</strong></blockquote><h3>Test Coverage</h3><ul><li>Increase unit test coverage</li><li>Validate and strengthen existing implementations</li><li>Ensure robust, reliable library functionality</li></ul><blockquote><strong>Detail-oriented? Help improve test coverage and fortify the library’s reliability!</strong></blockquote><h3>Technical Highlights</h3><p>GoCheerio is built with modern Go practices, leveraging:</p><ul><li>golang.org/x/net/html for parsing</li><li>Custom DOM and selector implementations</li><li>Efficient memory management strategies</li></ul><p><strong>Current features include:</strong></p><ul><li>Basic CSS selector support</li><li>DOM traversal methods</li><li>Attribute handling</li><li>Text and HTML extraction</li></ul><h3>Getting Started</h3><pre># Clone the repository<br>git clone https://github.com/MuxN4/gocheerio.git<br>cd gocheerio<br><br># Install dependencies<br>go mod download<br><br># Run tests<br>go test ./...</pre><h3>Join the Journey</h3><p>GoCheerio isn’t just a library — it’s a community-driven project with the potential to become a standard tool for Go developers. Whether you’re looking to improve your skills, contribute to open source, or solve real-world parsing challenges, there’s a place for you.</p><p><a href="https://github.com/MuxN4/gocheerio">🌟 <strong>Star GoCheerio on GitHub</strong></a> | <a href="https://github.com/MuxN4/gocheerio">🔗 <strong>Fork and Contribute Now</strong></a></p><p>Let’s build something amazing together!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a98420eded70" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Go Concurrency, Why Not?]]></title>
            <link>https://medium.com/@stev3npy/go-concurrency-why-not-1b3b60a47634?source=rss-4b256497da11------2</link>
            <guid isPermaLink="false">https://medium.com/p/1b3b60a47634</guid>
            <category><![CDATA[goroutines]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[synchronization]]></category>
            <category><![CDATA[concurrency]]></category>
            <dc:creator><![CDATA[Steven]]></dc:creator>
            <pubDate>Fri, 25 Oct 2024 20:12:50 GMT</pubDate>
            <atom:updated>2024-10-25T20:12:50.580Z</atom:updated>
            <content:encoded><![CDATA[<p>Go concurrency is powerful yet surprisingly accessible, though it might look intimidating at first. Here’s your invitation to dive into the world of concurrent programming without the stress! This guide will take you through the basics — like <strong>Goroutines</strong> and <strong>WaitGroups</strong>— and guide you all the way to more advanced topics such as <strong>Channels</strong>, <strong>Mutexes</strong>, and <strong>Context</strong>. You’ll pick up best practices, learn to handle errors effectively, and get a solid handle on Go’s concurrency model. By the end, you’ll be ready to take on concurrent programming with confidence. So, why not give it a shot?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*esHJHyKepS_QdJ_CyIdn-A.png" /></figure><h3>1. Goroutines Fundamentals</h3><p><strong>Goroutines</strong> are Go’s lightweight threads. They’re much efficient than traditional threads, using as little as ~2KB of stack space, so you can create thousands of them without overloading your system. Go’s scheduler takes care of running and managing them efficiently, letting you focus on the tasks at hand.</p><h4><strong>Basic Goroutine Examples</strong></h4><pre>// Simple goroutine<br>go func() {<br>    fmt.Println(&quot;Hello from goroutine!&quot;)<br>}()</pre><blockquote><strong>What’s happening here:</strong></blockquote><ul><li>Using the go keyword launches a new goroutine, allowing the function to run concurrently with the main program.</li><li>Remember: Concurrency means the goroutine runs alongside other code, but the exact execution order can vary.</li></ul><p><strong>Note:</strong> If the main program ends before the goroutine finishes, the goroutine will be cut off. To avoid this, you can use <strong>WaitGroups</strong> or <strong>Channels</strong> (we’ll dive into those later) to make sure all goroutines finish before the main program exits.</p><pre>// Goroutine with parameters<br>go func(msg string, id int) {<br>    fmt.Printf(&quot;Message %d: %s\n&quot;, id, msg)<br>}(&quot;Hello&quot;, 1)</pre><blockquote><strong>Why pass parameters this way:</strong></blockquote><ul><li><strong>Creates a new value for each goroutine</strong>: Passing parameters directly ensures that each goroutine receives its own independent copy of the values, rather than referencing shared variables.</li><li><strong>Avoids closure-related issues</strong>: When using closures, variables captured by the goroutine may change before the goroutine runs, leading to unexpected results. By passing parameters explicitly, you prevent issues related to variable capture.</li><li><strong>Ensures safe concurrency</strong>: Each goroutine operates with its own copy of the parameters, reducing the risk of data races or unintended modifications in concurrent operations.</li></ul><h4><strong>Goroutine with Proper Cleanup</strong></h4><pre>func main() {<br>    ctx, cancel := context.WithCancel(context.Background())<br>    defer cancel() // Important: ensures cleanup<br><br>    go func(ctx context.Context) {<br>        for {<br>            select {<br>            case &lt;-ctx.Done():<br>                fmt.Println(&quot;Cleanup and exit&quot;)<br>                return<br>            default:<br>                time.Sleep(time.Second)<br>            }<br>        }<br>    }(ctx)<br>    <br>    // It run&#39;s for 5 seconds<br>    time.Sleep(5 * time.Second)<br>} // Context cancellation happens here due to defer</pre><blockquote><strong>Why this pattern is important:</strong></blockquote><ul><li><strong>Provides controlled shutdown mechanism</strong>: Using a context with cancellation allows for graceful shutdown of goroutines, ensuring they exit cleanly when needed.</li><li><strong>Prevents goroutine leaks</strong>: Without proper cancellation, goroutines might continue running in the background even after they are no longer needed, consuming resources. This pattern helps avoid such leaks.</li><li><strong>Ensures resource cleanup</strong>: By canceling the context and monitoring ctx.Done(), you can ensure that any resources allocated during the goroutine&#39;s execution are properly cleaned up when the goroutine finishes.</li><li><strong>Context propagates cancellation</strong>: The context allows cancellation to propagate through multiple goroutines, ensuring that all dependent goroutines are informed of the cancellation and can terminate properly.</li></ul><h3>2. WaitGroups</h3><p>A WaitGroup allows you to wait for a group of goroutines to complete their execution. You use Add() to increase the count when starting a goroutine and Done() to decrease it when one completes. When you call Wait(), it pauses until all the goroutines are done</p><p>Think of it as a conductor at an orchestra who ensures that all musicians (goroutines) complete their parts before the performance (the main function) can end.</p><h4>Basic WaitGroup Usage</h4><pre>func main() {<br>    var wg sync.WaitGroup<br>    <br>    // Launch multiple workers<br>    for i := 0; i &lt; 3; i++ {<br>        wg.Add(1) // Must be called before the goroutine starts<br>        go func(id int) {<br>            defer wg.Done() // Ensures Done is called even if a panic occurs<br>            fmt.Printf(&quot;Worker %d doing work\n&quot;, id)<br>        }(i)<br>    }<br>    <br>    wg.Wait() // Blocks until all workers are done<br>}</pre><blockquote><strong>Key points about WaitGroups:</strong></blockquote><ul><li><strong>Add() must be called before the goroutine starts</strong>: You need to increment the counter using Add() before launching the goroutine to ensure WaitGroup properly tracks the number of active goroutines.</li><li><strong>Done() should be deferred to handle panics</strong>: Deferring Done() ensures it’s called regardless of how the goroutine exits, including in cases of panic, preventing the program from getting stuck.</li><li><strong>Wait() blocks until the counter reaches zero</strong>: Wait() ensures the main function or parent goroutine pauses execution until all goroutines have finished their work and called Done().</li><li><strong>The counter must never go negative</strong>: If you accidentally call Done() more times than Add(), the counter will go negative, and the program will panic. Always ensure the number of Add() and Done() calls are balanced.</li></ul><h4>Advanced Worker Pool Pattern</h4><pre>type Job struct {<br>    ID   int<br>    Data string<br>}<br><br>type Result struct {<br>    JobID     int<br>    Processed string<br>    Error     error<br>}<br><br>func WorkerPool(jobs []Job, numWorkers int) []Result {<br>    var wg sync.WaitGroup<br>    jobsChan := make(chan Job, len(jobs))    // Buffered channel for jobs<br>    resultsChan := make(chan Result, len(jobs)) // Buffered channel for results<br>    <br>    // Start workers<br>    for i := 0; i &lt; numWorkers; i++ {<br>        wg.Add(1)<br>        go worker(&amp;wg, jobsChan, resultsChan)<br>    }<br>    <br>    // Send jobs<br>    go func() {<br>        for _, job := range jobs {<br>            jobsChan &lt;- job<br>        }<br>        close(jobsChan) // Close after all jobs are sent<br>    }()<br>    <br>    // Wait and collect results<br>    go func() {<br>        wg.Wait()<br>        close(resultsChan) // Close after all workers are done<br>    }()<br>    <br>    // Collect results<br>    var results []Result<br>    for result := range resultsChan {<br>        results = append(results, result)<br>    }<br>    return results<br>}<br><br>func worker(wg *sync.WaitGroup, jobs &lt;-chan Job, results chan&lt;- Result) {<br>    defer wg.Done()<br>    for job := range jobs {<br>        // Process job<br>        result := Result{<br>            JobID: job.ID,<br>            Processed: processJob(job), // processing logic<br>        }<br>        results &lt;- result<br>    }<br>}</pre><blockquote><strong>Why this pattern is effective:</strong></blockquote><ul><li><strong>Bounded concurrency</strong>: By fixing the number of workers (numWorkers), you control the level of concurrency, ensuring that you prevent overwhelming system resources with too many goroutines.</li><li><strong>Efficient resource utilization</strong>: Using a buffered channel for jobs and results allows workers to process jobs concurrently and prevents them from waiting on one another unnecessarily.</li><li><strong>Prevents system overload</strong>: By controlling the number of workers, you manage resource consumption efficiently, avoiding spikes in CPU or memory usage.</li><li><strong>Proper cleanup through channel closing</strong>: Closing channels after jobs and workers are done ensures that no goroutines are left hanging, preventing potential resource leaks.</li><li><strong>Clear separation of concerns</strong>: The worker function focuses solely on processing jobs and reporting results, while the pool manager handles job distribution and result collection, ensuring a clean and maintainable design.</li></ul><h3>3. Channels</h3><p>A <strong>channel</strong> in Go is a communication mechanism that allows goroutines to safely share data. They can either be unbuffered or buffered, more like a mailbox where one person drops off letters (data) and another picks them up, with options for single-use, one-way, or two-way access.</p><h4><strong>Understanding Channel Types</strong></h4><pre>// Unbuffered channel<br>ch := make(chan string)<br>// Blocks until receiver is ready<br>// Used for synchronization<br><br>// Buffered channel<br>bufferedCh := make(chan string, 5)<br>// Blocks only when buffer is full<br>// Used for async communication with known bounds<br><br>// Read-only channel<br>func readOnly(ch &lt;-chan string) {<br>    // Can only read from ch<br>}<br><br>// Write-only channel<br>func writeOnly(ch chan&lt;- string) {<br>    // Can only write to ch<br>}</pre><h4>Channel Direction Operators Explained:</h4><ul><li>chan&lt;-: Send-only channel; can only be used to send data.</li><li>&lt;-chan: Receive-only channel; can only be used to receive data.</li><li>chan: Bidirectional channel; can be used for both sending and receiving data.</li></ul><blockquote><strong>Why Direction Constraints Matter:</strong></blockquote><ul><li><strong>Compile-time safety</strong>: Direction constraints prevent unintended read or write operations on a channel, helping to catch potential bugs at compile time.</li><li><strong>Clear communication patterns</strong>: Defining channels with direction clarifies the channel’s purpose, making code easier to understand and maintain.</li></ul><h4>Select Pattern with Explanation</h4><pre>func handleMultipleChannels(<br>    ctx context.Context,<br>    ch1, ch2 &lt;-chan string,<br>    timeout time.Duration,<br>) (string, error) {<br>    timeoutCh := time.After(timeout)<br>    <br>    for {<br>        select {<br>        case &lt;-ctx.Done():<br>            return &quot;&quot;, ctx.Err() // Handles context cancellation<br>            <br>        case msg1, ok := &lt;-ch1:<br>            if !ok {<br>                // Channel closed<br>                ch1 = nil // // Disable this case to prevent repeated selects on a closed channel<br>                continue<br>            }<br>            return fmt.Sprintf(&quot;Ch1: %s&quot;, msg1), nil<br>            <br>        case msg2, ok := &lt;-ch2:<br>            if !ok {<br>                ch2 = nil<br>                continue<br>            }<br>            return fmt.Sprintf(&quot;Ch2: %s&quot;, msg2), nil<br>            <br>        case &lt;-timeoutCh:<br>            return &quot;&quot;, fmt.Errorf(&quot;timeout after %v&quot;, timeout)<br>        }<br>    }<br>}</pre><blockquote><strong>Why This Pattern is Important:</strong></blockquote><ul><li><strong>Non-blocking handling of multiple channels</strong>: The select statement enables the function to wait for multiple channels at once, ensuring non-blocking handling of incoming data.</li><li><strong>Graceful handling of closed channels</strong>: When a channel is closed, setting it to nil removes it from future select cases, preventing errors from repeated reads on a closed channel.</li><li><strong>Timeout mechanism</strong>: The time.After channel enforces a timeout, ensuring the function returns if no messages arrive within the specified duration.</li><li><strong>Context cancellation support</strong>: The ctx.Done() case respects external cancellation signals, providing controlled shutdown and resource cleanup.</li><li><strong>Avoids goroutine leaks</strong>: Proper handling of timeouts and context cancellation prevents goroutines from running indefinitely, avoiding potential memory and resource leaks.</li></ul><h4>Fan-Out Fan-In Pattern</h4><pre>// Fan-Out function<br>func fanOut[T any](<br>    ctx context.Context,<br>    input &lt;-chan T,<br>    numWorkers int,<br>    processor func(T) T,<br>) []&lt;-chan T {<br>    outputs := make([]&lt;-chan T, numWorkers)<br>    <br>    for i := 0; i &lt; numWorkers; i++ {<br>        outputs[i] = worker(ctx, input, processor)<br>    }<br>    <br>    return outputs<br>}<br><br>// Worker function<br>func worker[T any](<br>    ctx context.Context,<br>    input &lt;-chan T,<br>    processor func(T) T,<br>) &lt;-chan T {<br>    output := make(chan T)<br>    <br>    go func() {<br>        defer close(output)<br>        for {<br>            select {<br>            case &lt;-ctx.Done():<br>                return<br>            case val, ok := &lt;-input:<br>                if !ok {<br>                    return<br>                }<br>                select {<br>                case output &lt;- processor(val):<br>                case &lt;-ctx.Done():<br>                    return<br>                }<br>            }<br>        }<br>    }()<br>    <br>    return output<br>}<br><br>// Fan-In function<br>func fanIn[T any](<br>    ctx context.Context,<br>    channels ...&lt;-chan T,<br>) &lt;-chan T {<br>    merged := make(chan T)<br>    var wg sync.WaitGroup<br>    <br>    // Merge function for each channel<br>    merge := func(ch &lt;-chan T) {<br>        defer wg.Done()<br>        for {<br>            select {<br>            case &lt;-ctx.Done():<br>                return<br>            case val, ok := &lt;-ch:<br>                if !ok {<br>                    return<br>                }<br>                select {<br>                case merged &lt;- val:<br>                case &lt;-ctx.Done():<br>                    return<br>                }<br>            }<br>        }<br>    }<br>    <br>    wg.Add(len(channels))<br>    for _, ch := range channels {<br>        go merge(ch)<br>    }<br>    <br>    // Close merged channel after all inputs are done<br>    go func() {<br>        wg.Wait()<br>        close(merged)<br>    }()<br>    <br>    return merged<br>}</pre><p>Yeah, this seems overwhelming, but I promise it’s not.</p><blockquote><strong>Key Aspects of the Fan-Out Fan-In Pattern:</strong></blockquote><ul><li><strong>Fan-Out (Parallel Processing):</strong> The fanOut function distributes tasks across multiple worker goroutines, enabling concurrent processing. Each worker independently processes items from the input channel using the provided processor function.</li><li><strong>Fan-In (Result Merging):</strong> The fanIn function consolidates the output from multiple workers into a single merged channel, making it easier for downstream functions to handle the results.</li><li><strong>Contextual Cancellation:</strong> By passing a ctx into both fanOut and fanIn, the pattern respects cancellation signals, ensuring all workers and the fan-in process terminate gracefully when cancellation is requested.</li><li><strong>Generic Reusability:</strong> With generics (T any), the fanOut, fanIn, and worker functions are versatile and can handle different data types, making the implementation reusable across various use cases.</li><li><strong>Efficient Resource Cleanup:</strong> The pattern ensures that channels are closed after processing, preventing resource leaks and ensuring proper resource management.</li><li><strong>Non-blocking Channels:</strong> Each channel operation (input, output, and merged) uses select with a case for context cancellation, enabling non-blocking communication and preventing deadlocks.</li></ul><h3>4. Context Usage</h3><h4>Timeout and Cancellation Patterns</h4><p>When dealing with long-running or resource-intensive tasks, managing timeouts and cancellations is key to using resources efficiently and avoiding issues like goroutine leaks. Here’s a how to set up a timeout pattern with context and handle cancellation gracefully.</p><pre>func operationWithTimeout(<br>    parentCtx context.Context,<br>    duration time.Duration,<br>) (string, error) {<br>    // Create a context with a timeout<br>    ctx, cancel := context.WithTimeout(parentCtx, duration)<br>    defer cancel() // Always defer cancel to free up resources<br><br>    return doOperation(ctx)<br>}<br><br>func doOperation(ctx context.Context) (string, error) {<br>    resultCh := make(chan string, 1)<br>    errCh := make(chan error, 1)<br><br>    go func() {<br>        // Simulate a long-running or expensive operation<br>        result, err := expensiveOperation()<br><br>        // Send result or error based on context state<br>        select {<br>        case &lt;-ctx.Done():<br>            return // Stop work if context is canceled<br>        case resultCh &lt;- result:<br>            if err != nil {<br>                errCh &lt;- err<br>            }<br>        }<br>    }()<br><br>    // Await results or handle cancellation<br>    select {<br>    case result := &lt;-resultCh:<br>        return result, &lt;-errCh<br>    case &lt;-ctx.Done():<br>        return &quot;&quot;, ctx.Err() // Return the context error if canceled<br>    }<br>}</pre><blockquote><strong>Why This Pattern is Important:</strong></blockquote><ol><li><strong>Prevents Goroutine Leaks</strong>: The ctx.Done() case ensures goroutines exit cleanly if the context is canceled, so you don’t end up with orphaned goroutines consuming memory.</li><li><strong>Implements Proper Timeouts</strong>: By using a WithTimeout context, you control how long each operation can take, improving system responsiveness.</li><li><strong>Graceful Cancellation Handling</strong>: The ctx.Done() check ensures that operations stop if they’re no longer needed, especially when part of a larger, nested workflow.</li><li><strong>Error Propagation</strong>: This pattern uses buffered channels for error handling, allowing you to handle errors independently and preventing goroutines from blocking on send.</li></ol><h3>5. Mutex &amp; Synchronization</h3><h4>Safe Counter</h4><p>In concurrent programming, ensuring safe access to shared data is essential to avoid race conditions and unexpected results. Here’s a straightforward approach to a thread-safe counter using a mutex</p><pre>type Counter struct {<br>    mu    sync.RWMutex<br>    count map[string]int<br>}<br><br>func NewCounter() *Counter {<br>    return &amp;Counter{<br>        count: make(map[string]int),<br>    }<br>}<br><br>func (c *Counter) Increment(key string) {<br>    c.mu.Lock()<br>    defer c.mu.Unlock()<br>    c.count[key]++<br>}<br><br>func (c *Counter) Get(key string) int {<br>    c.mu.RLock()<br>    defer c.mu.RUnlock()<br>    return c.count[key]<br>}</pre><blockquote><strong>Why this is Important:</strong></blockquote><ul><li><strong>Safe Concurrent Access</strong>: The mutex (mu) ensures that only one goroutine can update count at a time. This prevents data corruption and guarantees thread safety when accessing shared data.</li><li><strong>Efficient Read-Write Locking</strong>: The use of sync.RWMutex allows; RLock for reads allows multiple concurrent readers, boosting performance when multiple goroutines only need to check the value. Lock for writes is exclusive, ensuring only one writer at a time, which is critical for maintaining correct counts.</li><li><strong>Automatic Cleanup with </strong><strong>defer</strong>: By using defer, we ensure that the lock is released when the function finishes, even if it exits early. This helps prevent deadlocks and keeps the code clean.</li><li><strong>Encapsulation of State</strong>: The Counter struct and its methods hide the synchronization details from the caller and reducing the chance of misuse.</li></ul><h3>6. Practical Patterns</h3><h4>Rate limiter</h4><p>This rate limiter pattern limits the frequency of operations to avoid overloading resources. It employs a token bucket model, where a set number of “tokens” allow requests within a given interval, refilling periodically.</p><pre>type RateLimiter struct {<br>    tokens   chan struct{}<br>    interval time.Duration<br>}<br><br>func NewRateLimiter(rate int, interval time.Duration) *RateLimiter {<br>    rl := &amp;RateLimiter{<br>        tokens:   make(chan struct{}, rate),<br>        interval: interval,<br>    }<br>    <br>    // Fill token bucket<br>    for i := 0; i &lt; rate; i++ {<br>        rl.tokens &lt;- struct{}{}<br>    }<br>    <br>    // Refill tokens periodically<br>    go func() {<br>        ticker := time.NewTicker(interval)<br>        defer ticker.Stop()<br>        <br>        for range ticker.C {<br>            select {<br>            case rl.tokens &lt;- struct{}{}:<br>            default: // Don&#39;t block if tokens channel is full<br>            }<br>        }<br>    }()<br>    <br>    return rl<br>}<br><br>func (rl *RateLimiter) Wait() {<br>    &lt;-rl.tokens<br>}</pre><blockquote><strong>Pattern Analysis:</strong></blockquote><ul><li><strong>Controlled Throughput</strong>: tokens is a buffered channel that limits operations to the number of tokens in it. Each request consumes one token, enforcing the limit.</li><li><strong>Periodic Refills</strong>: The go routine uses a ticker to refill the bucket at the defined interval.</li><li><strong>Efficiency</strong>: Non-blocking select (default case) prevents the go routine from waiting if the tokens bucket is already full, ensuring memory efficiency.</li></ul><h4>Circuit Breaker</h4><p>The circuit breaker prevents repeated calls to failing services, waiting until they are likely to succeed again. It maintains state to either allow or block operations based on recent failure patterns.</p><pre>type CircuitBreaker struct {<br>    mu             sync.RWMutex<br>    failureCount   int<br>    threshold      int<br>    resetTimeout   time.Duration<br>    lastFailureTime time.Time<br>    isOpen         bool<br>}<br><br>func NewCircuitBreaker(threshold int, resetTimeout time.Duration) *CircuitBreaker {<br>    return &amp;CircuitBreaker{<br>        threshold:    threshold,<br>        resetTimeout: resetTimeout,<br>    }<br>}<br><br>func (cb *CircuitBreaker) Execute(operation func() error) error {<br>    if !cb.canExecute() {<br>        return fmt.Errorf(&quot;circuit breaker is open&quot;)<br>    }<br>    <br>    err := operation()<br>    cb.recordResult(err)<br>    return err<br>}<br><br>func (cb *CircuitBreaker) canExecute() bool {<br>    cb.mu.RLock()<br>    defer cb.mu.RUnlock()<br>    <br>    if !cb.isOpen {<br>        return true<br>    }<br>    <br>    // Check reset timeout<br>    if time.Since(cb.lastFailureTime) &gt; cb.resetTimeout {<br>        cb.mu.RUnlock()<br>        cb.mu.Lock()<br>        cb.isOpen = false<br>        cb.failureCount = 0<br>        cb.mu.Unlock()<br>        cb.mu.RLock()<br>        return true<br>    }<br>    <br>    return false<br>}<br><br>func (cb *CircuitBreaker) recordResult(err error) {<br>    cb.mu.Lock()<br>    defer cb.mu.Unlock()<br>    <br>    if err != nil {<br>        cb.failureCount++<br>        cb.lastFailureTime = time.Now()<br>        if cb.failureCount &gt;= cb.threshold {<br>            cb.isOpen = true<br>        }<br>    } else {<br>        cb.failureCount = 0<br>        cb.isOpen = false<br>    }<br>}</pre><blockquote><strong>Pattern Analysis:</strong></blockquote><ul><li><strong>Controlled Failure Handling</strong>: If a service fails repeatedly, isOpen prevents further calls. This reduces load on the service and avoids predictable failures.</li><li><strong>Threshold and Reset Logic</strong>: The circuit “trips” if failureCount exceeds threshold. The breaker then rechecks the resetTimeout before allowing another call, minimizing downtime.</li><li><strong>Efficient Synchronization</strong>: The combination of RLock for reading states and Lock for writing states in the canExecute and recordResult methods prevents race conditions and improves performance.</li></ul><h3>7. Error Handling</h3><h4>Error Group Pattern</h4><p>The <strong>Error Group Pattern</strong> enables concurrent processing with error propagation, ensuring that if one goroutine fails, the entire operation can be canceled gracefully. This is especially useful when multiple items or tasks need parallel processing, and error handling must be centralized.</p><pre>func processItems(ctx context.Context, items []string) error {<br>    // Initialize an error group with context for managing goroutines and errors.<br>    g, ctx := errgroup.WithContext(ctx)<br>    results := make(chan string, len(items))<br><br>    for _, item := range items {<br>        item := item // Create new variable for closure to avoid data race<br>        g.Go(func() error {<br>            // Check if context was canceled<br>            select {<br>            case &lt;-ctx.Done():<br>                return ctx.Err() // Propagate cancellation error<br>            default:<br>                if err := processItem(item); err != nil {<br>                    return fmt.Errorf(&quot;processing %s: %w&quot;, item, err) // Capture specific item error<br>                }<br>                results &lt;- item<br>                return nil<br>            }<br>        })<br>    }<br><br>    // Closing results channel when all goroutines complete<br>    go func() {<br>        g.Wait()<br>        close(results)<br>    }()<br><br>    for result := range results {<br>        fmt.Printf(&quot;Processed: %s\n&quot;, result)<br>    }<br><br>    // Return any error encountered during processing<br>    return g.Wait()<br>}</pre><blockquote><strong>Pattern Analysis:</strong></blockquote><ul><li><strong>Centralized Error Handling</strong>: errgroup.WithContext(ctx) coordinates all goroutines, allowing any encountered error to cancel all tasks. If any goroutine fails, g.Wait() will return the error.</li><li><strong>Controlled Concurrency</strong>: g.Go launches each goroutine with errgroup, reducing boilerplate code for error handling.</li><li><strong>Channel-Based Results Processing</strong>: results channel stores successful items and is closed after all tasks finish, preventing deadlocks by gracefully shutting down.</li><li><strong>Ensured Closure Safety</strong>: Creating a new item variable inside the loop prevents closure data race issues, ensuring each goroutine has a unique item.</li></ul><h3>Best Practices &amp; Common Pitfalls</h3><h4>Best Practices</h4><ol><li><strong>Always Use Context for Cancellation</strong></li></ol><p>Use context.Context to control and cancel long-running tasks. This enables cleanup and prevents unnecessary resource usage.</p><pre>// ❌ Bad: No cancellation mechanism<br>func longRunningTask() error {<br>    for {<br>        // Do work<br>        time.Sleep(time.Second)<br>    }<br>}<br><br>// ✅ Good: Cancellable operation<br>func longRunningTask(ctx context.Context) error {<br>    for {<br>        select {<br>        case &lt;-ctx.Done():<br>            return ctx.Err()<br>        default:<br>            // Do work<br>            time.Sleep(time.Second)<br>        }<br>    }<br>}</pre><p><strong>2. Proper Channel Closing</strong></p><p>Channels should be closed only by the sender. Receivers should not attempt to close the channel.</p><pre>// ❌ Bad: Closing channel from receiver<br>func bad() {<br>    ch := make(chan int)<br>    go func() {<br>        val := &lt;-ch<br>        close(ch) // Wrong: receiver closing channel<br>    }()<br>    ch &lt;- 1<br>}<br><br>// ✅ Good: Sender owns channel closure<br>func good() {<br>    ch := make(chan int)<br>    go func() {<br>        defer close(ch) // Right: sender closes<br>        ch &lt;- 1<br>    }()<br>    &lt;-ch<br>}</pre><p><strong>3. Proper Error Handling</strong></p><p>Use a structured way to collect and report errors, especially when working with multiple goroutines.</p><pre>// ❌ Bad: Lost errors<br>func badErrorHandling(tasks []Task) {<br>    for _, task := range tasks {<br>        go func(t Task) {<br>            err := process(t)<br>            if err != nil {<br>                // Error lost!<br>                fmt.Println(err)<br>            }<br>        }(task)<br>    }<br>}<br><br>// ✅ Good: Error collection<br>func goodErrorHandling(tasks []Task) error {<br>    errCh := make(chan error, len(tasks))<br>    var wg sync.WaitGroup<br><br>    for _, task := range tasks {<br>        wg.Add(1)<br>        go func(t Task) {<br>            defer wg.Done()<br>            if err := process(t); err != nil {<br>                errCh &lt;- err<br>            }<br>        }(task)<br>    }<br><br>    // Wait in separate goroutine<br>    go func() {<br>        wg.Wait()<br>        close(errCh)<br>    }()<br><br>    // Collect errors<br>    var errs []error<br>    for err := range errCh {<br>        errs = append(errs, err)<br>    }<br><br>    if len(errs) &gt; 0 {<br>        return fmt.Errorf(&quot;multiple errors: %v&quot;, errs)<br>    }<br>    return nil<br>}</pre><h4>Common Pitfalls</h4><ol><li><strong>Goroutine Leaks</strong></li></ol><p>Avoid goroutine leaks by ensuring all launched goroutines have an exit path, especially when dealing with channels.</p><pre>// ❌ Bad: Leaking goroutine<br>func leakyGoroutine() {<br>    ch := make(chan int)<br>    go func() {<br>        val := &lt;-ch // Goroutine stuck forever<br>        fmt.Println(val)<br>    }()<br>    // Channel never receives value, goroutine leaks<br>}<br><br>// ✅ Good: Prevent leaks with context<br>func noLeak(ctx context.Context) {<br>    ch := make(chan int)<br>    go func() {<br>        select {<br>        case val := &lt;-ch:<br>            fmt.Println(val)<br>        case &lt;-ctx.Done():<br>            return // Clean exit<br>        }<br>    }()<br>}</pre><p><strong>2. Race Conditions</strong></p><p>Use atomic operations or mutexes to ensure safe concurrent access to shared data.</p><pre>// ❌ Bad: Race condition<br>type Counter struct {<br>    count int<br>}<br><br>func (c *Counter) Increment() {<br>    c.count++ // Race condition!<br>}<br><br>// ✅ Good: Use sync/atomic<br>type Counter struct {<br>    count atomic.Int64<br>}<br><br>func (c *Counter) Increment() {<br>    c.count.Add(1) // Atomic operation<br>}</pre><p><strong>3. Mutex Copying</strong></p><p>When embedding mutexes, always use pointer receivers to prevent accidental copying.</p><pre>// ❌ Bad: Copying mutex<br>type Config struct {<br>    sync.Mutex<br>    data map[string]string<br>}<br><br>func (c Config) Get(key string) string { // Mutex copied!<br>    c.Lock()<br>    defer c.Unlock()<br>    return c.data[key]<br>}<br><br>// ✅ Good: Pointer receiver<br>type Config struct {<br>    mu   sync.Mutex<br>    data map[string]string<br>}<br><br>func (c *Config) Get(key string) string { // Pointer receiver<br>    c.mu.Lock()<br>    defer c.mu.Unlock()<br>    return c.data[key]<br>}</pre><p><strong>4. Channel Sizing</strong></p><p>Choose buffer sizes based on specific use cases to avoid deadlocks or inefficiency.</p><pre>// ❌ Bad: Arbitrary buffer size<br>ch := make(chan int, 100) // Why 100?<br><br>// ✅ Good: Buffer size matches use case<br>// For known number of items:<br>ch := make(chan int, len(items))<br><br>// For rate limiting:<br>ch := make(chan struct{}, workerCount)<br><br>// For latest value only:<br>ch := make(chan int, 1)</pre><h3>Performance Tips</h3><ol><li><strong>Use </strong><strong>sync.Pool for Frequently Allocated Objects</strong></li></ol><p>sync.Pool is useful when we frequently allocate objects with a short lifecycle, like buffers or temporary structs. This reduces the frequency of allocations and reuses objects instead.</p><pre>var bufferPool = sync.Pool{<br>    New: func() interface{} {<br>        return new(bytes.Buffer)<br>    },<br>}<br><br>func processData(data []byte) error {<br>    buf := bufferPool.Get().(*bytes.Buffer)<br>    defer func() {<br>        buf.Reset()<br>        bufferPool.Put(buf)<br>    }()<br>    <br>    // Example of using buffer for processing<br>    buf.Write(data)<br>    // Do more work with buf...<br><br>    return nil<br>}</pre><p><strong>2. Consider Atomic Operations for Simple Counters</strong></p><p>Atomic operations are faster than using mutexes for simple counter updates and are safe in concurrent environments.</p><pre>var counter atomic.Int64<br><br>func incrementCounter() {<br>    counter.Add(1)<br>}<br><br>func getCounter() int64 {<br>    return counter.Load()<br>}</pre><p><strong>3. Profile Before Optimizing</strong></p><p>Use Go’s built-in pprof package to gather CPU and memory profiles before optimizing your code. Profiling identifies bottlenecks accurately so you can focus on areas that need optimization.</p><ul><li>Import net/http/pprof for an HTTP endpoint.</li><li>Run your program with the profiler active.</li><li>Analyze profiles to identify hotspots.</li></ul><pre>// Run with `go run -tags nethttp .` or enable in main.go for profiling<br>import _ &quot;net/http/pprof&quot;<br><br>// Run with profiler:<br>// go tool pprof cpu.prof (after profiling and generating .prof files)<br><br>// Example usage:<br>func main() {<br>    http.ListenAndServe(&quot;:6060&quot;, nil) // pprof endpoint at http://localhost:6060/debug/pprof/<br>}</pre><p><strong>4. Use Buffered Channels When Message Count Is Known</strong></p><p>Buffered channels are more efficient when the number of messages is predictable. This avoids goroutines being blocked and improves performance.</p><pre>func processItems(items []int) {<br>    ch := make(chan int, len(items)) // Buffered channel<br><br>    for _, item := range items {<br>        ch &lt;- item<br>    }<br>    close(ch)<br><br>    for item := range ch {<br>        fmt.Println(&quot;Processing:&quot;, item)<br>    }<br>}</pre><p><strong>5. Implement Proper Cleanup for Long-Running Goroutines</strong></p><p>Long-running goroutines need a clear exit strategy to avoid leaks. Using context.Context allows graceful termination when the context is canceled.</p><pre>func longRunningTask(ctx context.Context) {<br>    ticker := time.NewTicker(time.Second)<br>    defer ticker.Stop() // Ensure ticker is cleaned up<br><br>    for {<br>        select {<br>        case &lt;-ctx.Done():<br>            fmt.Println(&quot;Cleanup and exit&quot;)<br>            return // Exit goroutine on context cancellation<br>        case &lt;-ticker.C:<br>            // Simulate periodic work<br>            fmt.Println(&quot;Working...&quot;)<br>        }<br>    }<br>}<br><br>func main() {<br>    ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)<br>    defer cancel() // Clean up context after done<br><br>    go longRunningTask(ctx)<br><br>    time.Sleep(6 * time.Second) // Wait to observe cancellation<br>}</pre><p>Remember: Concurrency is about structure, parallelism is about execution. Design your concurrent programs around your problem’s natural concurrency patterns rather than trying to force parallelism.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1b3b60a47634" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Go Cheat Sheet: At a Glance]]></title>
            <link>https://medium.com/@stev3npy/go-cheat-sheet-at-a-glance-33ed05bf1ff7?source=rss-4b256497da11------2</link>
            <guid isPermaLink="false">https://medium.com/p/33ed05bf1ff7</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[beginner]]></category>
            <category><![CDATA[golang]]></category>
            <dc:creator><![CDATA[Steven]]></dc:creator>
            <pubDate>Mon, 30 Sep 2024 14:32:12 GMT</pubDate>
            <atom:updated>2024-10-15T05:16:43.253Z</atom:updated>
            <content:encoded><![CDATA[<p>Go (or Golang) is a fast, open-source, compiled language developed by Google, emphasizing simplicity, efficiency, and scalability. It compiles directly to native code, resulting in fast performance without virtual machines. Go utilizes structs and type embedding for composition instead of classes, promoting simplicity in design. Its standout features include goroutines and channels for concurrent programming, making it ideal for scalable, distributed systems. With rapid compilation, cross-platform support, and a minimalist syntax, Go is widely employed in cloud services, systems programming, and network applications.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BpcNvUI-C1fIffI8KRhzNg.jpeg" /></figure><h3>Let’s Dive In Shall we?!</h3><h3>1. Basic Syntax &amp; Declarations</h3><p><strong>Go Program Structure</strong>: A basic Go program starts with a package declaration, followed by imports and the main function.</p><pre>package main<br><br>import &quot;fmt&quot;<br><br>func main() {<br>    fmt.Println(&quot;Hello, Go!&quot;)<br>}</pre><ul><li><strong>Comments</strong>:</li></ul><blockquote>Single-line: //</blockquote><blockquote>Multi-line: /* ... */</blockquote><ul><li><strong>Variables</strong>: Variables can be declared using var or shorthand syntax.</li></ul><pre>var x int = 10  // Using var<br>x := 10         // Shorthand declaration (Go infers type)</pre><ul><li><strong>Constants</strong>: Values that never change, are declared with const.</li></ul><pre>const Pi = 3.14</pre><ul><li><strong>Multiple Variable Declaration</strong>:</li></ul><pre>var a, b, c int = 1, 2, 3  // Multiple variables in one line<br>x, y := 1, &quot;text&quot;          // Shorthand version</pre><h3>2. Data Types</h3><ul><li><strong>Integer Types</strong>:</li></ul><blockquote>int, int8, int16, int32, int64 for different ranges.</blockquote><ul><li><strong>Float Types</strong>:</li></ul><blockquote>float32, float64 for decimal values.</blockquote><ul><li><strong>Boolean</strong>:</li></ul><blockquote>bool for true or false.</blockquote><ul><li><strong>String</strong>:</li><li>Immutable sequence of characters. Concatenating with +.</li></ul><pre>var name string = &quot;Go Lang&quot;  // String declaration<br>fullName := name + &quot; Tutorial&quot;  // String concatenation</pre><ul><li><strong>Type Casting</strong>: Convert one type to another explicitly.</li></ul><pre>var i int = 42<br>var f float64 = float64(i)  // Convert int to float64</pre><h3>3. Control Structures</h3><ul><li><strong>If-Else</strong>: Conditional logic.</li></ul><pre>if x &gt; 0 {<br>    fmt.Println(&quot;Positive&quot;)<br>} else if x == 0 {<br>    fmt.Println(&quot;Zero&quot;)<br>} else {<br>    fmt.Println(&quot;Negative&quot;)<br>}</pre><ul><li><strong>Switch</strong>: A simpler way to handle multiple conditions.</li></ul><pre>go<br>Copy code<br>switch day {<br>case &quot;Monday&quot;:<br>    fmt.Println(&quot;Start of the week&quot;)<br>default:<br>    fmt.Println(&quot;Unknown day&quot;)<br>}</pre><ul><li><strong>For Loop</strong>: The only looping construct in Go, there’s no while or do-while</li></ul><pre>for i := 0; i &lt; 10; i++ {<br>    fmt.Println(i)<br>}</pre><ul><li><strong>Range</strong>: Special form of for loop for iterating over collections. Eg slices, arrays, maps</li></ul><pre>for index, value := range mySlice {<br>    fmt.Println(index, value)<br>}</pre><h3>4. Functions</h3><ul><li><strong>Basic Function</strong>: A simple function that takes arguments and returns a value.</li></ul><pre>func add(x int, y int) int {<br>    return x + y<br>}</pre><ul><li><strong>Multiple Return Values</strong>: A function that returns more than one value.</li></ul><pre>func addAndSubtract(a int, b int) (int, int) {<br>    return a + b, a - b<br>}</pre><ul><li><strong>Variadic Functions</strong>: Functions that take a variable number of arguments.</li></ul><pre>func sum(nums ...int) int {<br>    total := 0<br>    for _, num := range nums {<br>        total += num<br>    }<br>    return total<br>}</pre><h3>5. Structs &amp; Methods</h3><ul><li><strong>Structs</strong>: Group data together into a type.</li></ul><pre>type Person struct {<br>    Name string<br>    Age  int<br>}</pre><ul><li><strong>Methods</strong>: Functions that belong to a struct.</li></ul><pre>func (p Person) Greet() string {<br>    return &quot;Hello, &quot; + p.Name<br>}</pre><h3>6. Pointers</h3><ul><li><strong>Pointer Declaration</strong>: A pointer holds the memory address of a variable.</li></ul><pre>var ptr *int  // Declares a pointer to an int</pre><ul><li><strong>Dereferencing</strong>: Access the value stored at the pointer.</li></ul><pre>x := 10<br>p := &amp;x   // p stores the address of x<br>fmt.Println(*p)  // Prints the value of x (10)</pre><ul><li><strong>Modifying Value via Pointer</strong>: Changing the value stored in the address.</li></ul><pre>func changeValue(ptr *int) {<br>    *ptr = 20  // Changes the value at the pointer<br>}</pre><h3>7. Arrays &amp; Slices</h3><p><strong>Arrays</strong>: Fixed-size collection of elements of the same type.</p><pre>var arr = [3]int{1, 2, 3}  // Array with 3 integers</pre><p>Once declared, the size of an array cannot be changed. Arrays are rarely used for dynamic data because of this fixed size.</p><p><strong>Slices</strong>: Dynamic arrays that can grow and shrink.</p><pre>var s = []int{1, 2, 3}  // Slice with 3 integers</pre><p>Unlike arrays, slices can grow as needed.</p><ul><li><strong>Append to a Slice</strong>: Add elements to the end of a slice.</li></ul><pre>slice := []int{1, 2}<br>slice = append(slice, 3, 4)  // Now slice is [1, 2, 3, 4]</pre><ul><li><strong>Copy Slices</strong>: Copies elements from one slice to another.</li></ul><pre>srcSlice := []int{1, 2, 3}<br>destSlice := make([]int, len(srcSlice))  // Create aslice with the same size as srcSlice <br>copy(destSlice, srcSlice) // Now destSlice is [1, 2, 3]</pre><h3>8. Maps</h3><p>Maps are Go’s built-in data structure for key-value pairs. They provide fast lookups, updates, and deletions based on the key.</p><ul><li><strong>Map Declaration</strong>: Create a map with make, specifying the key and value types.</li></ul><pre>m := make(map[string]int)<br>m[&quot;apple&quot;] = 2</pre><p>This creates a map where the keys are of type string and the values are int. Here, &quot;apple&quot; is assigned the value 2.</p><ul><li><strong>Access &amp; Delete</strong>: Access the value by the key or delete a key-value pair.</li></ul><pre>value := m[&quot;apple&quot;]   // Access value for key &quot;apple&quot;<br>delete(m, &quot;apple&quot;)    // Delete key &quot;apple&quot; from map</pre><p>If a key doesn’t exist, accessing it returns the zero value of the value type (e.g., 0 for integers).</p><h3>9. Concurrency with Goroutines</h3><p>Go supports lightweight concurrency through <strong>goroutines</strong>, which are functions that run asynchronously.</p><ul><li><strong>Starting a Goroutine</strong>: To start a goroutine, simply prefix the function call with go.</li></ul><pre>go func() {<br>    fmt.Println(&quot;Inside Goroutine&quot;)<br>}()</pre><p>This launches a new goroutine that runs concurrently with other goroutines (including main()).</p><ul><li><strong>Channels</strong>: Channels are used for communication between goroutines, allowing safe data exchange.</li></ul><pre>ch := make(chan int)<br>ch &lt;- 1       // Send data to the channel<br>x := &lt;-ch     // Receive data from the channel</pre><p>Channels can be unbuffered (blocks until both send and receive are ready) or buffered.</p><h3>10. Error Handling</h3><p>Go treats errors as values, returned by functions to be handled explicitly.</p><ul><li><strong>Errors as Values</strong>: Check the error returned by a function and handle it accordingly.</li></ul><pre>if err != nil {<br>    fmt.Println(&quot;Error:&quot;, err)<br>}</pre><p>This pattern is common throughout Go code and encourages early exits on errors.</p><ul><li><strong>Custom Error</strong>: You can create custom error types by implementing the Error() method from the error interface.</li></ul><pre>type MyError struct {<br>    Message string<br>}<br><br>func (e *MyError) Error() string {<br>    return e.Message<br>}</pre><p>Custom errors allow you to convey more information about what went wrong.</p><h3>11. Interfaces</h3><p>Interfaces define a set of methods a type must have.</p><ul><li><strong>Interface Definition</strong>: Create an interface by declaring the required methods.</li></ul><pre>type Animal interface {<br>    Speak() string<br>}</pre><p>This interface requires any type that satisfies it to implement the Speak() method.</p><ul><li><strong>Implementing Interface</strong>: A type implements an interface by having all required methods.</li></ul><pre>type Dog struct{}<br><br>func (d Dog) Speak() string {<br>    return &quot;Woof!&quot;<br>}</pre><p>Here, Dog satisfies the Animal interface by implementing Speak()</p><blockquote><strong><em>Note</em></strong><em>: Interfaces allow Go to provide polymorphism without inheritance. Any type that implements all methods in an interface is said to “satisfy” the interface.</em></blockquote><h3>12. Packages &amp; Modules</h3><p>Go organizes code into <strong>packages</strong> and uses <strong>modules</strong> for dependency management.</p><ul><li><strong>Importing Packages</strong>: You can import standard library packages like fmt to use their functionality.</li></ul><pre>import &quot;fmt&quot;</pre><ul><li><strong>Create a Module</strong>: To create a new Go module, initialize it with go mod init.</li></ul><pre>go mod init mymodule</pre><ul><li><strong>Install Dependencies</strong>: Use go mod tidy to install and clean up module dependencies.</li></ul><pre>go mod tidy</pre><h3>13. Testing</h3><p>Go has built-in support for writing unit tests.</p><ul><li><strong>Unit Test</strong>: A basic unit test follows the below naming convention and uses t.Errorf() to report failures.</li></ul><pre>func TestAdd(t *testing.T) {<br>    result := add(2, 3)<br>    if result != 5 {<br>        t.Errorf(&quot;Expected 5, got %d&quot;, result)<br>    }<br>}</pre><ul><li><strong>Benchmark</strong>: Benchmark tests measure performance, using b.N to control iterations.</li></ul><pre>func BenchmarkAdd(b *testing.B) {<br>    for i := 0; i &lt; b.N; i++ {<br>        add(1, 2)<br>    }<br>}</pre><h3>14. Concurrency Tools (sync package)</h3><p>Go’s sync package provides tools for synchronizing goroutines.</p><ul><li><strong>Mutex for Safe Access</strong>: A Mutex ensures only one goroutine accesses a critical section at a time.</li></ul><pre>var mu sync.Mutex<br>mu.Lock()      // Lock the critical section<br>// critical section<br>mu.Unlock()    // Unlock after operation</pre><ul><li><strong>WaitGroup for Goroutines</strong>: A WaitGroup helps to wait for multiple goroutines to finish.</li></ul><pre>var wg sync.WaitGroup<br>wg.Add(1)<br>go func() {<br>    defer wg.Done()<br>    fmt.Println(&quot;Goroutine&quot;)<br>}()<br>wg.Wait()   // Wait for all goroutines to finish</pre><h3>15. Context for Concurrency</h3><p>The context package provides a way to manage the lifecycle of goroutines, particularly for timeouts and cancellations.</p><ul><li><strong>Context with Timeout</strong>: Use context.WithTimeout to automatically cancel a context after a timeout.</li></ul><pre>ctx, cancel := context.WithTimeout(context.Background(), time.Second)<br>defer cancel()<br><br>select {<br>case &lt;-ctx.Done():<br>    fmt.Println(&quot;Timeout!&quot;)<br>}</pre><p>ctx.Done() returns a channel that closes when the context times out or is canceled.</p><h3>16. File I/O</h3><p>Go provides functions in the os package for simple file I/O operations, replacing the now-deprecated ioutil functions</p><ul><li><strong>Reading a File</strong>: Read the contents of a file into memory.</li></ul><pre>data, err := os.ReadFile(&quot;file.txt&quot;)<br>if err != nil {<br>    log.Fatal(err)<br>}</pre><ul><li><strong>Writing to a File</strong>: Write data to a file with specific permissions (e.g., 0644 for read-write).</li></ul><pre>err := os.WriteFile(&quot;file.txt&quot;, []byte(&quot;Hello, Go!&quot;), 0644)</pre><h3>17. Networking</h3><p>Go’s net/http package makes it easy to build web servers and send HTTP requests.</p><ul><li><strong>Simple HTTP Server</strong>: Serve HTTP requests using a handler function.</li></ul><pre>http.HandleFunc(&quot;/&quot;, func(w http.ResponseWriter, r *http.Request) {<br>    fmt.Fprintln(w, &quot;Hello, world!&quot;)<br>})<br>http.ListenAndServe(&quot;:8080&quot;, nil)</pre><ul><li><strong>Making HTTP Requests</strong>: Use http.Get to make a GET request to a URL.</li></ul><pre>resp, err := http.Get(&quot;https://example.com&quot;)<br>if err != nil {<br>    log.Fatal(err)<br>}</pre><h3>18. JSON Handling</h3><p>Go makes it easy to encode and decode JSON with the encoding/json package.</p><ul><li><strong>JSON Encoding</strong>: Convert a Go struct to JSON.</li></ul><pre>data, _ := json.Marshal(person)</pre><ul><li><strong>JSON Decoding</strong>: Parse JSON data into a Go struct.</li></ul><pre>json.Unmarshal(data, &amp;person)</pre><h3>19. Reflection</h3><p>Reflection in Go allows you to inspect types and values at runtime.</p><ul><li><strong>Type and Value Inspection</strong>: Use reflect.TypeOf and reflect.ValueOf to get type and value information.</li></ul><pre>t := reflect.TypeOf(myVar)     // Retrieves the type of myVar<br>v := reflect.ValueOf(myVar)     // Retrieves the value of myVar</pre><h3>20. CGo</h3><p>CGo is a feature that allows Go packages to call C code directly. It enables you to leverage existing C libraries and functions within your Go applications.</p><pre>/*<br>#include &lt;stdlib.h&gt;<br>#include &lt;stdio.h&gt;<br>*/<br>import &quot;C&quot;<br>func main() {<br>    C.puts(C.CString(&quot;Hello from C!&quot;))<br>}</pre><p>Included is a C header and call a C function (puts) from Go. Make sure to manage memory and types carefully when using CGo, as it can introduce complexity.</p><h3>21. Go Plugins</h3><p>Go supports dynamically loading Go packages at runtime through plugins. This allows you to build modular applications that can load or unload functionality as needed without recompiling the entire program.</p><pre>import &quot;plugin&quot;<br><br>func main() {<br>    p, err := plugin.Open(&quot;myplugin.so&quot;)  // Load the plugin<br>    if err != nil {<br>        log.Fatal(err)<br>    }<br>    symbol, err := p.Lookup(&quot;MyFunction&quot;)   // Find a function in the plugin<br>    if err != nil {<br>        log.Fatal(err)<br>    }<br>    symbol.(func())()   // Call the function<br>}</pre><p>In the above a plugin is loaded and look up a function named MyFunction to execute. Using plugins can enhance flexibility but should be approached with care due to potential complexity in managing dependencies.</p><h3>23. Best Practices</h3><ul><li><strong>Error Handling</strong>: Always check and handle errors with if err != nil and return early.</li></ul><blockquote>I suggest revisiting step 10</blockquote><ul><li><strong>Defer for Cleanup</strong>: Always use defer for resource cleanup (closing files, unlocking mutexes, etc.)</li></ul><pre>file, err := os.Open(&quot;file.txt&quot;)<br>if err != nil {<br>    log.Fatal(err)<br>}<br>defer file.Close() // Ensures the file is closed when the function exits</pre><ul><li><strong>Avoid Panic</strong>: Use panics sparingly, as they can disrupt the normal flow of your application. Instead, return errors when possible and handle them gracefully.</li></ul><pre>func criticalFunction() error {<br>    // Handle potential issues without panicking<br>    if someCondition {<br>        return fmt.Errorf(&quot;something went wrong&quot;)<br>    }<br>    return nil<br>}</pre><ul><li><strong>Use Goroutines Wisely</strong>: Ensure safe access to shared resources using synchronization mechanisms like sync.Mutex.</li></ul><pre>var mu sync.Mutex // Mutex for safe access to shared data<br><br>mu.Lock() // Access shared resource<br>// Perform operations on shared resource here<br>mu.Unlock() // Release the lock</pre><ul><li><strong>Use io.Reader and io.Writer</strong>: These interfaces are widely used for I/O operations, mainly due to their flexibility.</li></ul><pre>func CopyData(w io.Writer, r io.Reader) error {<br>    _, err := io.Copy(w, r)<br>    return err<br>}</pre><ul><li><strong>Always prefer Composition</strong>: Use embedded structs for composition instead of inheritance.</li></ul><pre>type Logger struct {<br>    // logger fields (e.g., settings for logging)<br>}<br><br>type HttpServer struct {<br>    Logger  // Embedding Logger<br>    // server fields (e.g., configuration, handlers, etc.)<br>}</pre><p>Instead of saying “HttpServer is a type of Logger” (which would be inheritance), we say “HttpServer has a Logger”, which is composition. This is achieved by embedding one struct inside another.</p><ul><li><strong>Use Named Return Values</strong>: For clarity and documentation.</li></ul><pre>func divide(a, b float64) (quotient float64, err error) {<br>    if b == 0 {<br>        err = errors.New(&quot;division by zero&quot;)<br>        return<br>    }<br>    quotient = a / b<br>    return<br>}</pre><p>In Go, <strong>named return values</strong> are return values that are given explicit names in the function signature. In your divide function, the named return values are quotient and err.</p><h3>Additional Resources:</h3><ul><li><a href="https://golang.org/doc/">Official Go Documentation</a></li><li><a href="https://golang.org/doc/effective_go.html">Effective Go</a></li><li><a href="https://gobyexample.com/">Go by Example</a></li></ul><p>The above may not be perfect, but I tried my best to explain and clarify in the most effective way possible. If this cheatsheet helped you, feel free to leave a clap or share your thoughts and suggestions in the comments. Your feedback means a lot! 🚀</p><p><strong>🌟 Show Your Support!</strong> Check out my <a href="https://github.com/MuxN4"><em>GitHub</em></a><em> </em>to explore more of my projects. If you like what you see, consider following me and leaving a ⭐ to show your support!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=33ed05bf1ff7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Art of Web Traffic: A Python Proxy Server Adventure]]></title>
            <link>https://medium.com/@stev3npy/the-art-of-web-traffic-a-python-proxy-server-adventure-8b69355c9687?source=rss-4b256497da11------2</link>
            <guid isPermaLink="false">https://medium.com/p/8b69355c9687</guid>
            <category><![CDATA[https]]></category>
            <category><![CDATA[networking]]></category>
            <category><![CDATA[caching]]></category>
            <category><![CDATA[proxy-server]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Steven]]></dc:creator>
            <pubDate>Fri, 06 Sep 2024 20:40:28 GMT</pubDate>
            <atom:updated>2024-09-09T13:03:42.186Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>The Art of Web Traffic: A Python Proxy Server</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MvwKXAz-NPe_zdqw2xrgjA.png" /></figure><p>Hey there, I’m thrilled to share my creation with you — A Python-powered proxy server that handles HTTP, HTTPS, and caching like a pro. Trust me, this isn’t your average proxy; it’s packed with some neat features. This bad boy packs quite a punch! 🥊</p><p>Imagine a traffic controller for the web, handling incoming requests, managing secure HTTPS connections, and caching responses to speed things up. That’s exactly what this proxy server does — but with more pizzazz and a sprinkle of Python magic! ✨</p><h3>Cool Features</h3><ul><li><strong>Speaks HTTP and HTTPS</strong>: Handles both protocols with ease. It’s like being bilingual, but for web protocols!</li><li><strong>Concurrency Ninja</strong>: Juggles multiple client connections like a circus performer.</li><li><strong>Caching Genius</strong>: Comes with a basic cache that remembers previous responses, so you don’t have to wait for the same content twice.</li><li><strong>Logging Extraordinaire</strong>: Keeps track of every little detail (yes, even the first 100 bytes of data).</li><li><strong>Highly Configurable</strong>: Flexible Feng Shui as I like to call it, customize the host, port, and even logging settings as you wish! Because one size doesn’t fit all!</li></ul><h3>Why Care</h3><p>Whether you’re curious and looking to understand the intricacies of web traffic, a developer wanting to peek behind the curtains, or just someone who thinks proxies sound cool (they are!), this project has something for you. I think it’s a great tool to explore, tweak, and learn how the web moves data around. Plus, who doesn’t want to feel like a traffic controller for web requests? 🚦</p><h3>Under the Hood</h3><p>What makes this proxy special? Well, I could show you the code… but where’s the fun in that? Here’s a sneak peek of some of the key components that make this thing tick:</p><ul><li><strong>Cache Mechanism</strong>: It uses an LRU-like cache that keeps track of responses and only evicts the least recently used ones.</li><li><strong>Request Parsing</strong>: The server efficiently parses incoming HTTP requests, modifies headers, and forwards them to the destination server.</li><li><strong>Threaded Connections</strong>: Every incoming request is handled in its own thread, ensuring smooth traffic flow.</li></ul><p>But that’s just scratching the surface! If you want to know more about how the cache works, how HTTPS connections are tunneled, or how I implemented logging, you’ll need to dive into the source code.</p><h3>Check It Out!</h3><blockquote>The project is <a href="https://github.com/MuxN4/proxy-server"><strong>open source</strong></a><strong> </strong>and waiting for you to clone it, fork it, or just admire it from afar. Feel free to explore the code, make improvements, or use it as a learning tool for your own projects.</blockquote><h3>Final Thoughts</h3><p>Building this proxy server felt like constructing a miniature version of the internet’s plumbing system. It’s not perfect (what is?), but you get to learn how our online world works behind the scenes.</p><p>So, why not take it for a spin? Clone the repo, fire it up, and watch as it directs your web traffic like a seasoned conductor. Who knows, you might just find yourself becoming a proxy enthusiast too!</p><p>Remember, in the world of web traffic, we’re all just packets trying to find our way home. This proxy server is here to help light the way! 🚀</p><p>Happy proxying, guys!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8b69355c9687" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a Custom HTTP Server in Go]]></title>
            <link>https://medium.com/@stev3npy/building-a-custom-http-server-in-go-e2cc0da0ba3c?source=rss-4b256497da11------2</link>
            <guid isPermaLink="false">https://medium.com/p/e2cc0da0ba3c</guid>
            <category><![CDATA[http-server]]></category>
            <category><![CDATA[network]]></category>
            <category><![CDATA[go]]></category>
            <dc:creator><![CDATA[Steven]]></dc:creator>
            <pubDate>Sat, 03 Aug 2024 14:18:11 GMT</pubDate>
            <atom:updated>2024-09-23T07:22:30.728Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JtHjPw_v66o5Lh7dkZ2qlQ.png" /></figure><p>Hey there, fellow code enthusiasts! Today, I’m excited to share with you a project that’s been both challenging and incredibly rewarding: building a custom HTTP server in Go. Whether you’re a seasoned developer looking to deepen your understanding of web servers or a beginner eager to dive into the world of Go, this project has something for everyone. Let’s embark on this journey together!</p><p><strong>Want to dive right into the code? Check out the full source code on my GitHub repository: </strong><a href="https://github.com/MuxN4/lumenserver.git"><strong>https://github.com/MuxN4/lumenserver.git</strong></a><strong> and leave a star if possible.</strong></p><h3>The Vision: More Than Just “Hello, World!”</h3><p>When I started this project, I had a clear goal in mind: to create a HTTP server that goes beyond the basic “Hello, World!” example. I wanted to build something robust, modular, and feature-rich — a server that could serve as a solid foundation for real-world applications. Here’s what I set out to achieve:</p><ol><li>A modular and maintainable codebase</li><li>Custom routing capabilities</li><li>Middleware support for enhanced functionality</li><li>A structure that promotes clean code practices</li></ol><h3>Project Structure: Laying the Foundation</h3><p>Before diving into the code, let’s take a look at how I structured the project:</p><pre>lumensurver/<br>├── main.go<br>├── server/<br>│   ├── server.go<br>│   ├── router.go<br>│   └── middleware.go<br>└── handlers/<br>    └── handlers.go</pre><p>This structure separates concerns, making the project more maintainable and easier to understand. Each file has a specific purpose:</p><ul><li>main.go: The entry point of our application</li><li>server/server.go: Core server logic</li><li>server/router.go: Custom routing implementation</li><li>server/middleware.go: Middleware functionality</li><li>handlers/handlers.go: Request handlers</li></ul><h3>The Journey: Building Block by Block</h3><h3>Step 1: Setting Up the Project</h3><p>First things first, I set up the project structure and initialized a Go module:</p><pre>mkdir lumenserver<br>cd lumenserver<br>go mod init lumenserver</pre><h3>Step 2: The Heart of the Server</h3><p>In server/server.go, I created the core Server struct and its methods:</p><pre>package server<br><br>import (<br> &quot;context&quot;<br> &quot;fmt&quot;<br> &quot;net/http&quot;<br>)<br><br>type Server struct {<br> port         int<br> Router       *Router<br> middlewares  []Middleware<br> errorHandler ErrorHandler<br> server       *http.Server<br>}<br><br>type ServerOption func(*Server)<br><br>func NewServer(port int) *Server {<br> s := &amp;Server{<br>  port:        port,<br>  middlewares: []Middleware{},<br> }<br> s.Router = NewRouter(s)<br> return s<br>}<br><br>func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {<br> s.Router.ServeHTTP(w, r)<br>}<br><br>func (s *Server) Run() error {<br> addr := fmt.Sprintf(&quot;:%d&quot;, s.port)<br> s.server = &amp;http.Server{<br>  Addr:    addr,<br>  Handler: s,<br> }<br><br> fmt.Printf(&quot;Server starting on port %d\n&quot;, s.port)<br> return s.server.ListenAndServe()<br>}<br><br>func (s *Server) Shutdown(ctx context.Context) error {<br> return s.server.Shutdown(ctx)<br>}<br><br>func (s *Server) GetRouter() *Router {<br> return s.Router<br>}<br><br>type ErrorHandler func(w http.ResponseWriter, r *http.Request, err error)<br><br>func WithErrorHandler(handler ErrorHandler) ServerOption {<br> return func(s *Server) {<br>  s.errorHandler = handler<br> }<br>}<br><br>func DefaultErrorHandler(w http.ResponseWriter, r *http.Request, err error) {<br> http.Error(w, err.Error(), http.StatusInternalServerError)<br>}</pre><p>This forms the backbone of our custom server, handling initialization and the main run loop.</p><h3>Step 3: Custom Routing</h3><p>The server/router.go file contains our custom routing logic:</p><pre>package server<br><br>import (<br> &quot;fmt&quot;<br> &quot;net/http&quot;<br> &quot;strings&quot;<br>)<br><br>type Handler func(w http.ResponseWriter, r *http.Request)<br><br>type Router struct {<br> routes          map[string]map[string]Handler<br> server          *Server<br> notFoundHandler Handler<br>}<br><br>func NewRouter(server *Server) *Router {<br> return &amp;Router{<br>  routes:          make(map[string]map[string]Handler),<br>  notFoundHandler: defaultNotFoundHandler,<br> }<br>}<br><br>func (r *Router) NotFound(handler Handler) {<br> r.notFoundHandler = handler<br>}<br><br>func (r *Router) addRoute(method, path string, handler Handler) {<br> if r.routes[method] == nil {<br>  r.routes[method] = make(map[string]Handler)<br> }<br> r.routes[method][path] = handler<br>}<br><br>func (r *Router) GET(path string, handler Handler) {<br> r.addRoute(http.MethodGet, path, handler)<br>}<br><br>func (r *Router) POST(path string, handler Handler) {<br> r.addRoute(http.MethodPost, path, handler)<br>}<br><br>func (r *Router) PUT(path string, handler Handler) {<br> r.addRoute(http.MethodPut, path, handler)<br>}<br><br>func (r *Router) DELETE(path string, handler Handler) {<br> r.addRoute(http.MethodDelete, path, handler)<br>}<br><br>func (r *Router) ServeHTTP(w http.ResponseWriter, req *http.Request) {<br> handler, err := r.findHandler(req.Method, req.URL.Path)<br> if err != nil {<br>  r.notFoundHandler(w, req)<br>  return<br> }<br> if r.server != nil {<br>  handler = r.server.ApplyMiddleware(handler)<br> }<br> handler(w, req)<br>}<br><br>func (r *Router) findHandler(method, path string) (Handler, error) {<br> if methodRoutes, ok := r.routes[method]; ok {<br>  if handler, ok := methodRoutes[path]; ok {<br>   return handler, nil<br>  }<br><br>  for routePath, handler := range methodRoutes {<br>   if isWildcardMatch(routePath, path) {<br>    return handler, nil<br>   }<br>  }<br> }<br> return nil, fmt.Errorf(&quot;no handler found for %s %s&quot;, method, path)<br>}<br><br>func isWildcardMatch(routePath, requestPath string) bool {<br> routeParts := strings.Split(routePath, &quot;/&quot;)<br> requestParts := strings.Split(requestPath, &quot;/&quot;)<br><br> if len(routeParts) != len(requestParts) {<br>  return false<br> }<br><br> for i, part := range routeParts {<br>  if part == &quot;*&quot; {<br>   continue<br>  }<br>  if part != requestParts[i] {<br>   return false<br>  }<br> }<br><br> return true<br>}<br><br>func defaultNotFoundHandler(w http.ResponseWriter, r *http.Request) {<br> http.Error(w, &quot;404 page not found&quot;, http.StatusNotFound)<br>}</pre><p>This custom router allows us to define routes and match incoming requests to the correct handlers.</p><h3>Step 4: Middleware Magic</h3><p>In server/middleware.go, I implemented middleware support:</p><pre>package server<br><br>import (<br> &quot;net/http&quot;<br>)<br><br>type Middleware func(Handler) Handler<br><br>func Chain(h Handler, middleware ...Middleware) Handler {<br> for i := len(middleware) - 1; i &gt;= 0; i-- {<br>  h = middleware[i](h)<br> }<br> return h<br>}<br><br>func (s *Server) ApplyMiddleware(h Handler) Handler {<br> if len(s.middlewares) == 0 {<br>  return h<br> }<br> return Chain(h, s.middlewares...)<br>}<br><br>func (s *Server) Use(middleware ...Middleware) {<br> s.middlewares = append(s.middlewares, middleware...)<br>}<br><br>// Some example middleware functions<br><br>func LoggingMiddleware(next Handler) Handler {<br> return func(w http.ResponseWriter, r *http.Request) {<br>  println(&quot;Request:&quot;, r.Method, r.URL.Path)<br>  next(w, r)<br>  println(&quot;Response sent&quot;)<br> }<br>}<br><br>func AuthMiddleware(next Handler) Handler {<br> return func(w http.ResponseWriter, r *http.Request) {<br>  // Check for auth token (this is a very simplistic example)<br>  if r.Header.Get(&quot;Authorization&quot;) == &quot;&quot; {<br>   http.Error(w, &quot;Unauthorized&quot;, http.StatusUnauthorized)<br>   return<br>  }<br>  next(w, r)<br> }<br>}<br><br>func RecoveryMiddleware(next Handler) Handler {<br> return func(w http.ResponseWriter, r *http.Request) {<br>  defer func() {<br>   if err := recover(); err != nil {<br>    http.Error(w, &quot;Internal Server Error&quot;, http.StatusInternalServerError)<br>   }<br>  }()<br>  next(w, r)<br> }<br>}</pre><p>This allows us to create a chain of middleware functions, enabling features like logging, authentication, and more.</p><h3>Step 5: Handling Requests</h3><p>The handlers/handlers.go file contains our request handlers:</p><pre>package handlers<br><br>import (<br> &quot;encoding/json&quot;<br> &quot;fmt&quot;<br> &quot;net/http&quot;<br> &quot;time&quot;<br>)<br><br>func HomeHandler(w http.ResponseWriter, r *http.Request) {<br> w.Header().Set(&quot;Content-Type&quot;, &quot;text/plain&quot;)<br> fmt.Fprintln(w, &quot;Welcome to our custom HTTP server!&quot;)<br>}<br>func TimeHandler(w http.ResponseWriter, r *http.Request) {<br> w.Header().Set(&quot;Content-Type&quot;, &quot;application/json&quot;)<br> currentTime := time.Now().Format(time.RFC3339)<br> json.NewEncoder(w).Encode(map[string]string{&quot;time&quot;: currentTime})<br>}<br><br>type User struct {<br> ID   string `json:&quot;id&quot;`<br> Name string `json:&quot;name&quot;`<br>}<br><br>func UsersHandler(w http.ResponseWriter, r *http.Request) {<br> w.Header().Set(&quot;Content-Type&quot;, &quot;application/json&quot;)<br> users := []map[string]string{<br>  {&quot;id&quot;: &quot;1&quot;, &quot;name&quot;: &quot;Alice&quot;},<br>  {&quot;id&quot;: &quot;2&quot;, &quot;name&quot;: &quot;Bob&quot;},<br>  {&quot;id&quot;: &quot;3&quot;, &quot;name&quot;: &quot;Charlie&quot;},<br> }<br> json.NewEncoder(w).Encode(users)<br>}<br><br>func CreateUserHandler(w http.ResponseWriter, r *http.Request) {<br> w.Header().Set(&quot;Content-Type&quot;, &quot;application/json&quot;)<br> var user map[string]string<br> if err := json.NewDecoder(r.Body).Decode(&amp;user); err != nil {<br>  http.Error(w, err.Error(), http.StatusBadRequest)<br>  return<br> }<br><br> // In a real application, you would save the user to a database here<br> user[&quot;id&quot;] = &quot;4&quot; <br> json.NewEncoder(w).Encode(user)<br>}<br><br>func NotFoundHandler(w http.ResponseWriter, r *http.Request) {<br> w.Header().Set(&quot;Content-Type&quot;, &quot;text/plain&quot;)<br> w.WriteHeader(http.StatusNotFound)<br> fmt.Fprintln(w, &quot;404 - Page not found&quot;)<br>}</pre><p>These handlers process incoming requests and generate appropriate responses.</p><h3>Step 6: Putting It All Together in main.go</h3><p>Now, let’s tie everything together in our main.go file:</p><pre>package main<br><br>import (<br> &quot;context&quot;<br> &quot;fmt&quot;<br> &quot;log&quot;<br> &quot;os&quot;<br> &quot;os/signal&quot;<br> &quot;syscall&quot;<br> &quot;time&quot;<br><br> &quot;lumenserver/handlers&quot;<br> &quot;lumenserver/server&quot;<br>)<br><br>func main() {<br> s := server.NewServer(8080)<br><br> s.Use(server.LoggingMiddleware)<br> s.Use(server.RecoveryMiddleware)<br><br> // Register routes<br> s.Router.GET(&quot;/&quot;, handlers.HomeHandler)<br> s.Router.GET(&quot;/time&quot;, handlers.TimeHandler)<br> s.Router.GET(&quot;/users&quot;, handlers.UsersHandler)<br> s.Router.POST(&quot;/users&quot;, handlers.CreateUserHandler)<br> s.Router.NotFound(handlers.NotFoundHandler)<br><br> // Set up graceful shutdown<br> stop := make(chan os.Signal, 1)<br> signal.Notify(stop, os.Interrupt, syscall.SIGTERM)<br><br> go func() {<br>  if err := s.Run(); err != nil {<br>   log.Fatalf(&quot;Error starting server: %v&quot;, err)<br>  }<br> }()<br><br> fmt.Println(&quot;Server is running on http://localhost:8080&quot;)<br><br> //Interrupt signal<br> &lt;-stop<br><br> fmt.Println(&quot;Shutting down server...&quot;)<br><br> ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)<br> defer cancel()<br><br> if err := s.Shutdown(ctx); err != nil {<br>  log.Fatalf(&quot;Server forced to shutdown: %v&quot;, err)<br> }<br><br> fmt.Println(&quot;Server gracefully stopped&quot;)<br>}</pre><p>This main.go file creates a new server instance, adds middleware, registers routes, and starts the server on port 8080.</p><h3>Challenges and Learning</h3><p>Building this server wasn’t without its challenges. One particular hurdle I faced was ensuring proper access to the middleware chain from the router. I initially defined the router field in the Server struct with a lowercase ‘r’, making it unexported (private). This led to some head-scratching moments!</p><p>The solution was to update the Server struct and provide a method to access the router:</p><pre>type Server struct {<br>    Router *Router // Note the capital &#39;R&#39;<br>    // Other fields...<br>}<br><br>func (s *Server) GetRouter() *Router {<br>    return s.Router<br>}</pre><p>This experience taught me the importance of careful struct design and the nuances of Go’s visibility rules.</p><h3>The Result: A Functional and Extensible Server</h3><p>After putting all the pieces together, we end up with a custom HTTP server that:</p><ol><li>Handles basic routing for different HTTP methods</li><li>Supports middleware for request processing</li><li>Provides a clean, modular structure for adding new features</li><li>Serves as a great learning tool for understanding web servers</li></ol><h3>Real-World Use Cases</h3><p>While building a custom HTTP server is an excellent learning experience, you might be wondering about its practical applications. Here are some scenarios where our custom server could shine:</p><ol><li>Microservices Architecture: In a microservices setup, our lightweight, customizable server could be perfect for creating small, focused services. Its modularity allows easy adaptation to specific service requirements.</li><li>API Gateways: With its routing and middleware capabilities, our server could serve as a foundation for building API gateways, handling tasks like request routing, authentication, and rate limiting.</li><li>IoT Applications: For IoT devices with limited resources, a stripped-down version of our server could provide just the necessary functionality without the overhead of a full-featured web framework.</li><li>Custom Web Frameworks: This server could be the starting point for building a custom web framework tailored to specific organizational needs or performance requirements.</li><li>Learning and Teaching Tool: As demonstrated in this blog post, this server is an excellent tool for understanding the inner workings of HTTP servers, making it valuable in educational settings.</li></ol><h3>Server Architecture and Request Flow</h3><p>To better understand how our custom server works, let’s visualize its architecture and request flow:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DYzgDqEeshS3a39P07JzKA.png" /></figure><p>This diagram illustrates the key components of our custom HTTP server and the flow of a request through the system:</p><ol><li>The incoming request first hits the Router.</li><li>The Router determines which handler should process the request.</li><li>Before reaching the handler, the request passes through the Middleware Chain.</li><li>The appropriate handler processes the request and generates a response.</li><li>The response travels back through the system to the client.</li></ol><p>This architecture allows for a clear separation of concerns and makes it easy to add or modify functionality at each stage of request processing.</p><h3>Comparison with Go’s Standard Library</h3><p>While Go’s standard net/http package is powerful and flexible, building a custom server offers several advantages:</p><ol><li>Greater Control: Our custom server allows fine-grained control over every aspect of request handling, from routing to middleware execution.</li><li>Learning Opportunity: Building from scratch provides deep insights into server internals, which can be invaluable for debugging and optimization.</li><li>Customization: We can tailor the server exactly to our needs, potentially improving performance by eliminating unnecessary features.</li><li>Middleware Implementation: While middleware can be implemented with the standard library, our custom solution makes it more straightforward and explicit.</li><li>Extensibility: It’s easier to add custom features or experiment with different architectural patterns in our bespoke solution.</li></ol><p>However, it’s important to note that the standard library is battle-tested, extensively documented, and continuously improved. For many applications, it remains the best choice. Our custom server shines in scenarios requiring specific optimizations or unique features not easily implemented with the standard library.</p><h3>Learning Resources</h3><p>If this project has piqued your interest in Go, HTTP servers, or web development in general, here are some excellent resources to continue your learning journey:</p><ol><li>“The Go Programming Language” by Alan A. A. Donovan and Brian W. Kernighan — A comprehensive guide to Go, suitable for beginners and experienced programmers alike.</li><li>Go by Example (<a href="https://gobyexample.com/">https://gobyexample.com/</a>) — A hands-on introduction to Go using annotated example programs.</li><li>Effective Go (<a href="https://golang.org/doc/effective_go">https://golang.org/doc/effective_go</a>) — Tips for writing clear, idiomatic Go code.</li><li>“Building Web Applications with Go” by Nathan Youngman and Roger Peppe — Focuses on web development with Go.</li><li>“Network Programming with Go” by Jan Newmarch — Dives deep into network programming, including HTTP servers.</li><li>The net/http package documentation (<a href="https://golang.org/pkg/net/http/">https://golang.org/pkg/net/http/</a>) — Essential reading for understanding Go’s standard HTTP toolkit.</li><li>Awesome Go (<a href="https://awesome-go.com/">https://awesome-go.com/</a>) — A curated list of awesome Go frameworks, libraries, and software.</li></ol><p>Remember, the best way to learn is by doing. Don’t hesitate to experiment with the code, break things, and rebuild them. Each error and successful implementation will deepen your understanding.</p><h3>Conclusion: The Journey Continues</h3><p>Building this custom HTTP server in Go has been an incredible learning experience. It’s given me a deeper understanding of how web servers work under the hood and has improved my Go programming skills.</p><p>We’ve created a robust, flexible solution that not only serves as a learning tool but also has practical applications in various scenarios. The modular structure, custom routing, and middleware support provide a solid foundation for building more complex web applications.</p><p>But the journey doesn’t end here! There’s always room for improvement and expansion. Some ideas for future enhancements include:</p><ul><li>Implementing more advanced routing with URL parameters</li><li>Adding support for WebSockets</li><li>Implementing graceful shutdown</li><li>Adding configuration options for SSL/TLS</li></ul><p>I hope this project inspires you to dive deeper into Go and web server development. As you continue to explore and expand upon this project, remember that the world of web development and Go programming is vast and ever-evolving. Stay curious, keep learning, and most importantly, enjoy the process of creation!</p><p>Happy coding, and may your custom servers always respond with lightning speed and 200 OK! 🚀</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e2cc0da0ba3c" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>