<?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 Peeyush Mishra on Medium]]></title>
        <description><![CDATA[Stories by Peeyush Mishra on Medium]]></description>
        <link>https://medium.com/@mishrapeeyush212?source=rss-52068ee050d9------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*8JalSbWZKkAEbRfy0cHscA.jpeg</url>
            <title>Stories by Peeyush Mishra on Medium</title>
            <link>https://medium.com/@mishrapeeyush212?source=rss-52068ee050d9------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 21 Nov 2026 08:25:26 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@mishrapeeyush212/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[12 Go Coding Practices I Learned the Hard Way (So You Don’t Have To )]]></title>
            <link>https://medium.com/@mishrapeeyush212/12-go-coding-practices-i-learned-the-hard-way-so-you-dont-have-to-7cb7c1c726a6?source=rss-52068ee050d9------2</link>
            <guid isPermaLink="false">https://medium.com/p/7cb7c1c726a6</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[best-practices]]></category>
            <category><![CDATA[go]]></category>
            <category><![CDATA[backend-development]]></category>
            <dc:creator><![CDATA[Peeyush Mishra]]></dc:creator>
            <pubDate>Thu, 10 Apr 2025 19:56:44 GMT</pubDate>
            <atom:updated>2025-04-10T20:00:05.627Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*YI4JeUeGJdLNNTw7.jpeg" /></figure><p>Hey, fellow gophers! 🐹</p><p>When I first started building APIs and backend services with Go at a startup, I stumbled a lot. Over time (and after quite a few “oh crap” moments 😅), I learned some hard lessons — the kind of lessons that docs don’t always cover.</p><p>This post is my no-fluff, straight-from-the-trenches guide to writing better Go code. If you’re a beginner or intermediate developer, especially in the backend/API world, I hope these tips help you skip the potholes I fell into.</p><p>Let’s go! 💡</p><h3>1. 🔁 DRY: Don’t Repeat Yourself</h3><p>If you’re copy-pasting, you’re doing it wrong.</p><p>Create reusable helpers, interfaces, and modules. DRY not only saves time but avoids bugs from inconsistent updates.</p><blockquote>Code duplication is easy. But debugging the same bug in 3 places isn’t.</blockquote><p>😵‍💫 Repetitive Code:</p><pre>// ❌ Bad<br>if user.Type == &quot;admin&quot; {<br>    if user.IsActive {<br>        // do something<br>    }<br>}</pre><p>✅ DRY Version:</p><pre>// ✅ Good<br>func isActiveAdmin(user User) bool {<br>    return user.Type == &quot;admin&quot; &amp;&amp; user.IsActive<br>}</pre><blockquote>A few helper methods will save you hours of pain later.</blockquote><h3>2. 😌 KISS: Keep It Super Simple</h3><p>Yes, I added an extra ‘S’.</p><blockquote>Go shines when it’s simple. Clever hacks are fun… until you’re debugging them at 2 AM.</blockquote><blockquote>Assume your code is being read by a sleepy intern — or even sleepier future-you.</blockquote><p>😵‍💫 Bad:</p><pre>func DoIt(x string) {}</pre><p>😌 Good:</p><pre>func SaveUserToDB(userName string) {}</pre><h3>3. 📏 Short Functions FTW</h3><p>Aim for functions under 7<strong>0 lines</strong>. More than that, it’s probably doing too much.</p><p>Let each function do <em>one</em> thing. Split if needed.</p><pre>func (i impl) PublishToMarketplace(ctx context.Context, workflowID string) error {<br> log := logger.FromContext(ctx)<br><br> workflow, err := i.getWorkflowByID(ctx, workflowID)<br> if err != nil {<br>  log.Error(&quot;failed to retrieve workflow&quot;, err, logger.Field(&quot;id&quot;, workflowID))<br>  return err<br> }<br><br> now := time.Now().UTC().UnixMilli()<br> workflow.UpdatedAt = now<br> workflow.IsPublished = true<br><br> _, err = i.workflowRepo.Save(ctx, workflow, &amp;workflowID)<br> if err != nil {<br>  log.Error(&quot;failed to publish workflow&quot;, err, logger.Field(&quot;workflowID&quot;, workflowID))<br>  return err<br> }<br><br> return nil<br>}</pre><pre>func (i impl) getWorkflowByID(ctx context.Context, workflowID string) (*model.Workflow, error) {<br> query, _ := querybuilder.New().<br>  EqualsIDHex(workflow.KeyObjectID, workflowID).<br>  Build()<br><br> workflowDoc, err := i.workflowRepo.FindOne(ctx, query)<br><br> return workflowDoc, err<br>}</pre><h3>4. ❌ Don’t Over-Abstract… Yet</h3><blockquote>A good abstraction hides the complexity, not the intent.</blockquote><p>Over-abstraction too early often leads to code that’s hard to trace and reason about. A good abstraction hides complexity without hiding meaning.</p><p>A helpful way to think about abstraction is to ask: <em>“Is this logic repeated in more than one place or likely to be reused soon?”</em> If yes, consider abstracting. If not, keep it inline until the pattern emerges naturally.</p><h4>Real-World Analogy 🧠</h4><p>Think of abstraction like setting up a coffee machine in your office. If you’re the only one making coffee once a month, it’s overkill. But if the whole team needs coffee every day, a well-labeled machine saves everyone time.<br>👎 Over-Abstracted:</p><pre>func updateCacheAndDB(value string) {}</pre><p>This hides too much logic. You lose track of what it’s actually doing — caching, persisting, both?</p><p>✅ Better:</p><pre>func setFieldsInCache(val string) {}<br>func updateFields(val string) {}</pre><p>Each function has a single responsibility and is reusable in isolation.</p><p>Yes, abstractions are great. But <em>not</em> when you club everything into a single all-purpose function.</p><h3>5. 🧹 Modular Packaging</h3><p>To keep your service modular and maintainable, it’s good practice to split it into separate packages based on use cases or domains. This improves code organization, makes onboarding easier, and keeps each component focused and reusable.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/568/1*goZc66GYnSlI2rs3xLasjA.png" /></figure><p>Organizing execution, file, and marketplace packages within the handler layer keeps the code modular and uncluttered, clearly separating APIs by domain.</p><h3>6. 📦 Folder Structure</h3><p>Follow <strong>layered architecture</strong> — handler, logic, repo — with clear boundaries:</p><ul><li>handlers: Handles HTTP requests/responses. Deals only with DTOs.</li><li>logic: Contains business logic. This layer should only interact with <strong>external services</strong> (e.g., third-party APIs) and <strong>internal contracts</strong> — not DTOs or database-specific logic.</li><li>repo: Responsible for <strong>all DB-level interactions</strong> — insertions, queries, and data models with tags like BSON or SQL.</li></ul><p><em>🧠 </em>Rule of thumb:</p><ul><li><strong>logic</strong> = brains (pure Go + third-party APIs)</li><li><strong>repo</strong> = database I/O (Mongo, SQL, etc.)</li><li><strong>handlers</strong> = API boundary (Gin, Fiber, Echo)</li></ul><p>This structure helps avoid cross-contamination of responsibilities and keeps things easier to mock, test, and scale.</p><h3>7. 📥 Imports: Be Clear</h3><p>Use alias imports that make your code readable.</p><pre>import (<br> marketplaceContract &quot;test-service/logic/marketplace/contract&quot;<br> utilContext &quot;test-service/utils/context&quot;<br> &quot;github.com/gin-gonic/gin&quot;<br>)</pre><h3>8. 📦 DTOs vs Contracts</h3><p>When designing your codebase, it’s important to clearly distinguish between <strong>DTOs (Data Transfer Objects)</strong> and <strong>Contracts</strong> to maintain separation of concerns.</p><ul><li><strong>DTOs</strong> are used at the API/handler layer for transporting data in and out of your service — they often include JSON tags and validation annotations.</li><li><strong>Contracts</strong> are used internally, often between your service logic and repository layers, and should use native types without external-facing tags.</li></ul><p>Keeping them separate reduces coupling between your internal logic and the shape of external requests/responses. This makes your service more robust to change and easier to maintain or refactor.</p><p>Think of it like the difference between a UI form (DTO) and the internal struct you use to store or manipulate data (Contract). They may look similar but serve different purposes and evolve at different paces.</p><p>Example DTO:</p><pre>type UpdateWorkflowRequest struct {<br> LogoURL      string `json:&quot;logoURL&quot; binding:&quot;required&quot;`<br> WorkflowID   string `json:&quot;workflowID&quot; binding:&quot;required&quot;`<br> WorkflowName string `json:&quot;workflowName&quot; binding:&quot;required&quot;`<br> Category     string `json:&quot;category&quot; binding:&quot;required&quot;`<br> Description  string `json:&quot;description&quot; binding:&quot;required&quot;`<br>}</pre><p>Example Contract:</p><pre>type UpdateWorkflowFieldsRequest struct {<br> WorkflowID string<br> Data       UpdateWorkflowMetaFieldsRequest<br>}<br><br>type UpdateWorkflowMetaFieldsRequest struct {<br> CompanyID           string<br> WorkflowLogoURL     string<br> WorkflowName        string<br> WorkflowCategory    string<br> WorkflowDescription string<br> WorkflowPublisher   string<br>}</pre><p>Example Repo Struct with BSON tags:</p><pre>type TemplateHistory struct { // serves as history<br> ID                 *primitive.ObjectID `bson:&quot;_id,omitempty&quot;`<br> FromWorkflowID     string              `bson:&quot;fromWorkflowID&quot;`<br> Workflow           TemplateWorkflow    `bson:&quot;workflow&quot;`<br> CreatedAt          int64               `bson:&quot;createdAt&quot;`<br> CreatedByUser      string              `bson:&quot;createdByUser&quot;`<br> PublisherUserID    string              `bson:&quot;publisherUserID&quot;`<br> PublisherCompanyID string              `bson:&quot;publisherCompanyID&quot;`<br>}</pre><h3>9. 📃 Interface Definition</h3><p>Define clear, strongly typed interfaces. Avoid ambiguous or overly generic types like map[string]interface{}, interface{}, or any unless absolutely required (e.g., when dealing with third-party packages or dynamic data).</p><p>Interfaces should be small, descriptive, and use well-defined types to maintain readability, predictability, and compile-time safety.</p><pre>type Marketplace interface {<br> CopyTemplate(ctx context.Context, req *contract.CopyTemplateRequest) (*contract.CopyTemplateResponse, error)<br> PublishToMarketplace(ctx context.Context, workflowID string) error<br>}</pre><h3>10. 🧪 Dependency Injection (DI): Plug, Don’t Hardcode</h3><p>Dependency Injection is a design pattern where you pass (or “inject”) dependencies like database clients, services, or repositories <em>into</em> your struct or function, rather than creating them <em>inside</em> it.</p><p>Think of it like plugging in your charger instead of soldering it to the wall. It keeps things flexible, testable, and modular.</p><p>🔧 What It Looks Like:</p><pre>package marketplace<br><br>import (<br> &quot;context&quot;<br><br> &quot;test-service/external/user&quot;<br> &quot;test-service/logic/marketplace/contract&quot;<br> &quot;test-service/repository/mongodb/node&quot;<br> &quot;test-service/repository/mongodb/templatehistory&quot;<br> &quot;test-service/repository/mongodb/workflow&quot;<br>)<br><br>type impl struct {<br> workflowRepo        workflow.Workflow<br> nodeRepo            node.Node<br> templateHistoryRepo templatehistory.TemplateHistory<br> user                user.User<br>}<br><br>func New() Marketplace {<br> return &amp;impl{<br>  workflowRepo:        workflow.New(),<br>  nodeRepo:            node.New(),<br>  templateHistoryRepo: templatehistory.New(),<br>  user:                user.New(),<br> }<br>}</pre><p>Now when calling:</p><pre>_, err := i.workflowRepo.Save(ctx, workflow, &amp;workflowID)<br>if err != nil {<br> log.Error(&quot;failed to publish workflow&quot;, err, logger.Field(&quot;workflowID&quot;, workflowID))<br> return err<br>}</pre><p>You’re not hardcoding logic inside the impl — you&#39;re using its dependencies through interfaces. This is clean, testable, and decoupled.</p><p>✅ Advantages of DI:</p><ul><li>Makes <strong>unit testing easier</strong> (you can inject mocks)</li><li>Promotes <strong>loose coupling</strong></li><li>Improves <strong>readability</strong> and <strong>reusability</strong></li><li>Encourages writing <strong>interface-driven</strong> code</li></ul><p>Inject, don’t construct — and your code will stay testable, composable, and future-proof. 🔄</p><h3>11. 🧠 Use context.Context Effectively</h3><blockquote>Context isn’t just a Go feature — it’s your best friend in a distributed world. Use it well.</blockquote><p>In Go, context.Context isn’t just a formality — it&#39;s how you pass deadlines, cancellations, and request-scoped data across your service.</p><p>Use it consistently across all layers: handler → logic → repo. This gives you full control over request flow, timeouts, and logging.</p><p>😵‍💫 <strong>Bad: No Context</strong></p><pre>func GetUser(id string) (*User, error) {<br>  return db.FindUserByID(id) // No cancellation or timeout handling<br>}</pre><p>✅ <strong>Good: Context All the Way Down</strong></p><pre>func (i impl) GetUser(ctx context.Context, id string) (*User, error) {<br>  user, err := i.userRepo.FindByID(ctx, id)<br>  if err != nil {<br>    logger.FromContext(ctx).Error(&quot;failed to get user&quot;, err)<br>    return nil, err<br>  }<br><br>  return user, nil<br>}</pre><p>🎯 <strong>Pro Tips:</strong></p><ul><li>Never create a context.Background() inside your business logic. Always pass it down from upstream (typically from the HTTP handler).</li><li>Use context-aware loggers (logger.FromContext(ctx)) to add request IDs and tracing.</li><li>Add deadlines where applicable (context.WithTimeout) — especially around external calls like DB or API.</li></ul><h3>12. 🛠️ Error Handling Patterns: Be Explicit, Not Cryptic</h3><blockquote>Errors are part of the flow — not an afterthought. Own them.</blockquote><p>Go makes you handle errors explicitly — embrace it. A clean error strategy keeps debugging painless and error flows predictable.</p><p>Start by defining <strong>typed errors</strong> or <strong>custom error structs</strong> so you’re not just comparing raw strings.</p><p>😵‍💫 <strong>Bad: Error String Matching</strong></p><pre>if err.Error() == &quot;user not found&quot; {<br>  return nil<br>}</pre><p>✅ <strong>Good: Define Meaningful Errors</strong></p><pre>var ErrUserNotFound = errors.New(&quot;user not found&quot;)<br><br>func (r repo) FindByID(ctx context.Context, id string) (*User, error) {<br>  user, err := r.db.Find(id)<br>  if err == sql.ErrNoRows {<br>    return nil, ErrUserNotFound<br>  }<br>  return user, err<br>}</pre><p>Then in logic layer:</p><pre>func (i impl) GetUser(ctx context.Context, id string) (*User, error) {<br>  user, err := i.userRepo.FindByID(ctx, id)<br>  if errors.Is(err, ErrUserNotFound) {<br>    return nil, nil // or return a 404 response from handler<br>  }<br><br>  if err != nil {<br>    logger.FromContext(ctx).Error(&quot;db failed&quot;, err)<br>    return nil, err<br>  }<br><br>  return user, nil<br>}</pre><p>🎯 <strong>Pro Tips:</strong></p><ul><li>Use errors.Is() or errors.As() when working with wrapped errors.</li><li>Consider wrapping errors with context using fmt.Errorf(&quot;failed to find user: %w&quot;, err) for better stack traces.</li><li>Your <strong>handler</strong> should map internal errors to appropriate HTTP responses.</li></ul><h3>✨ Wrapping Up</h3><p>This <em>isn’t</em> an exhaustive list — just the tip of the iceberg when it comes to writing clean, scalable Go code. But if you’re a self-taught dev, a junior engineer, or someone navigating the beautiful chaos of startup life, these practices can be the difference between merely surviving and actually thriving in production.</p><p>They’ve definitely helped me.</p><p>I’m a <strong>founding engineer</strong> at a <strong>Dubai-based Generative AI startup</strong>, and I’ve been building full-time in Go for the past two years. Like many others, I didn’t learn this stuff in a classroom — I learned it by breaking things… and slowly figuring out how not to. 😅</p><p>This was also my <strong>first article on Medium</strong>, so if you enjoyed it — found it useful, relatable, or even just nodded along at that “who wrote this?” moment — I’d truly appreciate it if you hit the ❤️, dropped a comment, or shared it with a fellow dev. It helps more than you know.</p><p>There’s still so much more to cover, but mastering even these fundamentals will already set you apart.</p><p>Thanks for reading — and here’s to writing Go code your future self won’t hate. 🧑‍💻🙌</p><h3>Let’s Connect</h3><p>🐦 Twitter (X): <a href="https://x.com/mipeeyush">@mipeeyush</a><br> 💼 LinkedIn: <a href="https://www.linkedin.com/in/peeyush-m/">Peeyush M</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7cb7c1c726a6" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>