Blame
| ee697a | Melisha Dsouza | 2026-01-16 07:25:14 | 1 | # **Golang** |
| 2 | ||||
| 3 | | Field | Value | |
|||
| 4 | | ------- | -------------------------------- | |
|||
| 5 | | Version | 1.0.0 | |
|||
| 6 | | Status | Draft | |
|||
| 7 | | Author | Datta Bhise | |
|||
| 8 | | Target | All Go Backend Engineering Teams | |
|||
| 9 | ||||
| 10 | ### **1. Introduction & Philosophy** |
|||
| 11 | The primary goal of this document is to ensure code **consistency**, **maintainability**, and **simplicity**. Go is an opinionated language; we embrace its idioms rather than fighting them. |
|||
| 12 | ||||
| 13 | **Core Tenets:** |
|||
| 14 | 1. Clear is better than clever. |
|||
| 15 | 2. Errors are values and must be handled explicitly. |
|||
| 16 | 3. Concurrency is a tool, not a default state. |
|||
| 17 | 4. Documentation is part of the code, not an afterthought. |
|||
| 18 | ||||
| 19 | ### **2. Project Layout & Structure** |
|||
| 20 | We adhere to the community-standard **Go Project Layout**. |
|||
| c07c44 | Melisha Dsouza | 2026-01-16 09:45:03 | 21 | ```Golang |
| ee697a | Melisha Dsouza | 2026-01-16 07:25:14 | 22 | | Directory | Purpose | |
| 23 | | /cmd | Main applications. Directory names match the binary (e.g., cmd/api-server). | |
|||
| 24 | | /internal | Private application and library code. Compiler-enforced privacy. | |
|||
| 25 | | /pkg | Library code safe for external applications to import. | |
|||
| 26 | | /api | API protocols (Swagger/OpenAPI, Protocol Buffers, gRPC definitions). | |
|||
| 27 | | /configs | Configuration file templates or default configs. | |
|||
| 28 | | /scripts | Scripts to build, install, analyze, etc. | |
|||
| 29 | ``` |
|||
| 30 | **Rule**: Do not place application logic in the root directory. Keep the root for meta-files (go.mod, Dockerfile, README.md). |
|||
| 31 | ||||
| 32 | ### **3. Formatting & Style** |
|||
| 33 | ||||
| 34 | #### **3.1 Automated Formatting** |
|||
| 35 | - All code must be formatted using gofmt (or goimports). |
|||
| 36 | - This should be enforced via a pre-commit hook or CI pipeline. |
|||
| 37 | ||||
| 38 | #### **3.2 Imports** |
|||
| 39 | Imports are grouped into three blocks, separated by newlines: |
|||
| 40 | 1. Standard Library |
|||
| 41 | 2. Third-party packages |
|||
| 42 | 3. Internal/Company packages |
|||
| 43 | ||||
| c07c44 | Melisha Dsouza | 2026-01-16 09:45:03 | 44 | ```Golang |
| ee697a | Melisha Dsouza | 2026-01-16 07:25:14 | 45 | import ( |
| 46 | "fmt" |
|||
| 47 | "os" |
|||
| 48 | ||||
| 49 | "[github.com/gin-gonic/gin](https://github.com/gin-gonic/gin)" |
|||
| 50 | ||||
| 51 | "[github.com/myorg/project/internal/user](https://github.com/myorg/project/internal/user)" |
|||
| 52 | ) |
|||
| 53 | ``` |
|||
| 54 | ||||
| 55 | #### **3.3 Line Length** |
|||
| 56 | - Avoid lines longer than 120 characters. |
|||
| 57 | - Break long function signatures or boolean conditions into multiple lines for readability. |
|||
| 58 | ||||
| 59 | ### **4. Naming Conventions** |
|||
| 60 | #### **4.1 Packages** |
|||
| 61 | - **Single word**, **lowercase**. (e.g., user, account, not user_service or User). |
|||
| 62 | - Package names should describe what is provided, not what it contains (avoid util, common, helper). |
|||
| 63 | #### **4.2 Variables** |
|||
| 64 | - **Short Scope** = **Short Name**: Use i for loop indices, r for readers. |
|||
| 65 | - **Long Scope** = **Descriptive Name**: Exported variables or those used across large functions need explicit names (e.g., RequestTimeoutDuration). |
|||
| 66 | - **MixedCaps**: Use CamelCase. No snake_case. |
|||
| 67 | #### **4.3 Interfaces** |
|||
| 68 | - One-method interfaces end in -er (e.g., Reader, Writer, Formatter). |
|||
| 69 | - Keep interfaces small (1-3 methods). |
|||
| 70 | #### **4.4 Getters** |
|||
| 71 | - Go does not use get in getter names. |
|||
| 72 | - **Bad**: func (u *User) GetName() string |
|||
| 73 | - **Good**: func (u *User) Name() string |
|||
| 74 | ||||
| 75 | ### **5. Architecture & Design patterns** |
|||
| 76 | #### **5.1 Dependency Injection** |
|||
| 77 | Avoid global state. Dependencies should be injected explicitly, typically via the constructor. |
|||
| 78 | ||||
| 79 | **Bad (Global State):** |
|||
| c07c44 | Melisha Dsouza | 2026-01-16 09:45:03 | 80 | ```Golang |
| ee697a | Melisha Dsouza | 2026-01-16 07:25:14 | 81 | func CreateUser() { |
| 82 | db.Execute(...) // "db" is a global variable |
|||
| 83 | } |
|||
| 84 | ||||
| 85 | ||||
| 86 | Good (Dependency Injection): |
|||
| 87 | type Service struct { |
|||
| 88 | repo UserRepository |
|||
| 89 | } |
|||
| 90 | ||||
| 91 | func NewService(r UserRepository) *Service { |
|||
| 92 | return &Service{repo: r} |
|||
| 93 | } |
|||
| 94 | ``` |
|||
| 95 | ||||
| 96 | #### **5.2 Interfaces: Consumer Defined** |
|||
| 97 | Define interfaces where they are used, not where they are implemented. This reduces coupling. |
|||
| 98 | - **Accept Interfaces, Return Structs:** Functions should accept the broadest possible interface (behavior) and return concrete types (data). |
|||
| 99 | #### **5.3 Configuration** |
|||
| 100 | - Use a struct-based configuration. |
|||
| 101 | - Read from Environment Variables (12-Factor App methodology). |
|||
| 102 | - Use libraries like viper or kelseyhightower/envconfig. |
|||
| 103 | ||||
| 104 | ### **6. Error Handling** |
|||
| 105 | #### **6.1 Inspectable Errors** |
|||
| 106 | - Never use panic for standard error flow. |
|||
| 107 | - Use %w to wrap errors to add context while preserving type. |
|||
| c07c44 | Melisha Dsouza | 2026-01-16 09:45:03 | 108 | ```Golang |
| ee697a | Melisha Dsouza | 2026-01-16 07:25:14 | 109 | if err := db.Query(); err != nil { |
| 110 | return fmt.Errorf("querying user failed: %w", err) |
|||
| 111 | } |
|||
| 112 | ``` |
|||
| 113 | ||||
| 114 | #### **6.2 Checking Errors** |
|||
| 115 | - Use errors.Is() for value comparisons. |
|||
| 116 | - Use errors.As() for type assertions. |
|||
| 117 | - Never use _ to ignore an error. If an error is truly ignorable, document why. |
|||
| 118 | ||||
| 119 | #### **6.3 Indentation (Line of Sight)** |
|||
| 120 | Handle errors early and return. Avoid else blocks after error checks. |
|||
| c07c44 | Melisha Dsouza | 2026-01-16 09:45:03 | 121 | ```Golang |
| ee697a | Melisha Dsouza | 2026-01-16 07:25:14 | 122 | // Bad |
| 123 | if err == nil { |
|||
| 124 | // heavy logic |
|||
| 125 | } else { |
|||
| 126 | return err |
|||
| 127 | } |
|||
| 128 | ||||
| 129 | // Good |
|||
| 130 | if err != nil { |
|||
| 131 | return err |
|||
| 132 | } |
|||
| 133 | // heavy logic |
|||
| 134 | ``` |
|||
| 135 | ||||
| 136 | ### **7. Concurrency** |
|||
| 137 | #### **7.1 Lifecycle Management** |
|||
| 138 | - Never start a goroutine without knowing how it will stop. |
|||
| 139 | - Use context.Context for cancellation and timeout propagation. |
|||
| 140 | #### **7.2 Communication** |
|||
| 141 | - "Share memory by communicating, don't communicate by sharing memory." |
|||
| 142 | - Use Channels for passing data ownership. |
|||
| 143 | - Use Mutexes (sync.Mutex) for protecting state integrity within a struct. |
|||
| 144 | #### **7.3 Context Usage** |
|||
| 145 | - ctx should always be the first parameter of a function. |
|||
| 146 | - Never store Context inside a struct definition; pass it through the call stack. |
|||
| 147 | ||||
| 148 | ### **8. Performance & Memory** |
|||
| 149 | #### **8.1 Pointers vs Values** |
|||
| 150 | - **Use Pointers (T):** |
|||
| 151 | - If you need to modify the receiver. |
|||
| 152 | - If the struct is large (> 64 bytes) to avoid copying. |
|||
| 153 | - If the struct contains a Mutex (mutexes must strictly not be copied). |
|||
| 154 | - **Use Values (T)**: |
|||
| 155 | - For small structs, basic types, maps, and funcs. |
|||
| 156 | - To ensure immutability. |
|||
| 157 | - **Note**: Passing by value is often faster due to stack allocation logic. |
|||
| 158 | #### **8.2 Slice Allocation** |
|||
| 159 | If the length is known, pre-allocate slices to avoid resizing overhead. |
|||
| c07c44 | Melisha Dsouza | 2026-01-16 09:45:03 | 160 | ```Golang |
| ee697a | Melisha Dsouza | 2026-01-16 07:25:14 | 161 | // Good |
| 162 | users := make([]User, 0, len(ids)) |
|||
| 163 | ``` |
|||
| 164 | ||||
| 165 | ### **9. Testing** |
|||
| 166 | #### **9.1 Table-Driven Tests** |
|||
| 167 | Use table-driven tests for all logic-heavy functions. |
|||
| c07c44 | Melisha Dsouza | 2026-01-16 09:45:03 | 168 | ```Golang |
| ee697a | Melisha Dsouza | 2026-01-16 07:25:14 | 169 | func TestAdd(t *testing.T) { |
| 170 | tests := []struct { |
|||
| 171 | name string |
|||
| 172 | a, b int |
|||
| 173 | want int |
|||
| 174 | }{ |
|||
| 175 | {"positive", 1, 2, 3}, |
|||
| 176 | {"negative", -1, -1, -2}, |
|||
| 177 | } |
|||
| 178 | for _, tt := range tests { |
|||
| 179 | t.Run(tt.name, func(t *testing.T) { |
|||
| 180 | if got := Add(tt.a, tt.b); got != tt.want { |
|||
| 181 | t.Errorf("Add() = %v, want %v", got, tt.want) |
|||
| 182 | } |
|||
| 183 | }) |
|||
| 184 | } |
|||
| 185 | } |
|||
| 186 | ``` |
|||
| 187 | ||||
| 188 | #### **9.2 Test Packages** |
|||
| 189 | Use package foo_test (external testing) to ensure you are testing the public API of your package, preventing tight coupling to internal implementation details. |
|||
| 190 | #### **9.3 Race Detection** |
|||
| 191 | - **Mandatory in CI**: All test pipelines must run with the -race flag enabled (go test -race ./...). |
|||
| 192 | - **Local Development**: Developers should run race detection locally when working on concurrent code. |
|||
| 193 | - **Zero Tolerance**: Any race condition reported by the tool is considered a critical bug and blocks merging. |
|||
| 194 | #### **9.4 Code Coverage** |
|||
| 195 | - **Target**: We aim for **80% code coverage** on core business logic (services, domain logic). |
|||
| 196 | - **Enforcement**: Use go test -coverprofile to generate reports. |
|||
| 197 | - **Philosophy**: High coverage does not guarantee bug-free code, but low coverage guarantees untested paths. Do not write assertions just to satisfy the counter; test behavior, not lines. |
|||
| 198 | ||||
| 199 | ### **10. Observability (Logging & Metrics)** |
|||
| 200 | - **Structured Logging**: Use log/slog (Go 1.21+) or zap. |
|||
| 201 | - **Levels**: Use strictly defined levels (DEBUG, INFO, WARN, ERROR). |
|||
| 202 | - **No Printf**: Do not use fmt.Println in production code. |
|||
| 203 | ||||
| 204 | ### **11. Linting Configuration** |
|||
| 205 | We use golangci-lint. The following linters are mandatory: |
|||
| 206 | ``` |
|||
| 207 | # .golangci.yml snippet |
|||
| 208 | linters: |
|||
| 209 | enable: |
|||
| 210 | - errcheck # checking for unchecked errors |
|||
| 211 | - gosimple # simplifies code |
|||
| 212 | - govet # reports suspicious constructs |
|||
| 213 | - staticcheck # massive set of static analysis checks |
|||
| 214 | - unused # checks for unused constants, variables, functions |
|||
| 215 | - bodyclose # checks whether HTTP response body is closed |
|||
| 216 | - noctx # finds sending http request without context.Context |
|||
| 217 | - revive # fast, configurable, extensible, flexible, and beautiful linter |
|||
| 218 | ``` |
|||
| c07c44 | Melisha Dsouza | 2026-01-16 09:45:03 | 219 | |
| 220 | **Document** - [Go Lang](https://docs.google.com/document/d/1EaOaSk-hbuje0igvIxl1DXcHQROc3KP-S49eD1IUGqg/edit?usp=sharing) |