🐹 Go (Golang) Backend Engineering Masterclass
1️⃣ The Go Philosophy, Type System & Memory Layout
Definition: Go (Golang) Google dwara design ki gayi ek statically-typed, compiled programming language hai jo simple syntax, ultra-fast compilation, native multicore concurrency aur direct OS machine binary generation deliver karti hai.
| Criteria | Go (Golang) | Java / Node.js |
|---|---|---|
| Execution Model | Direct machine code binary compilation. Zero runtime VM overhead. | JVM Bytecode JIT execution (Java) / V8 dynamic JIT runtime (Node). |
| Concurrency Cost | ~2 KB initial stack size per Goroutine. Millions spawn ho sakte hain. | ~1 MB stack size per OS Thread (Java). Single-threaded event loop (Node). |
| Type Inheritance | Zero class inheritance. Composition via embedded structs & interfaces. | Classical class-based deep inheritance hierarchies. |
2️⃣ Pointers, Structs & Implicit Interfaces
Go me interfaces implicitly satisfy hote hain. Kisi class ko implements keyword likhne ki zaroorat nahi hoti:
package main
import "fmt"
// 1. Interface Declaration
type Notifier interface {
Send(message string) error
}
// 2. Concrete Struct
type EmailSender struct {
EmailAddress string
}
// 3. Method Implementation (Implicitly satisfies Notifier!)
func (e EmailSender) Send(message string) error {
fmt.Printf("Dispatching email to %s: %s\n", e.EmailAddress, message)
return nil
}
func NotifyUser(n Notifier, msg string) {
n.Send(msg)
}
3️⃣ Idiomatic Error Handling vs Exceptions
Go me try-catch blocks exist nahi karte. Errors standard values hote hain jo multiple return values ke sath propagate kiye jaate hain:
import (
"errors"
"fmt"
)
var ErrInvalidSalary = errors.New("salary must be greater than zero")
func CalculateAnnualPackage(monthlySalary float64) (float64, error) {
if monthlySalary <= 0 {
return 0, ErrInvalidSalary
}
return monthlySalary * 12, nil
}
// Standard Invocation Idiom:
pkg, err := CalculateAnnualPackage(85000)
if err != nil {
// Handle error explicitly
fmt.Printf("Failed: %v\n", err)
return
}
fmt.Printf("Total CTC: ₹%.2f\n", pkg)
4️⃣ Concurrency: Goroutines, WaitGroups & Mutexes
Goroutine ko spawn karne ke liye sirf go keyword lagana hota hai. Shared state race conditions ko prevent karne ke liye sync.Mutex ya sync.WaitGroup use kiya jata hai:
package main
import (
"sync"
)
type SafeCounter struct {
mu sync.Mutex
count int
}
func (c *SafeCounter) Increment(wg *sync.WaitGroup) {
defer wg.Done()
c.mu.Lock() // Acquire Lock
c.count++
c.mu.Unlock() // Release Lock
}
5️⃣ CSP Pattern: Channels & Non-Blocking Select
"Do not communicate by sharing memory; instead, share memory by communicating."
| Channel Type | Declaration | Blocking Behavior |
|---|---|---|
| Unbuffered | ch := make(chan int) |
Sender tab tak block rehta hai jab tak receiver data accept na kare (Synchronous handshake). |
| Buffered | ch := make(chan int, 5) |
Sender tab tak non-blocking rehta hai jab tak buffer capacity (5) full na ho jaye. |
// Multiplexing Channels with select
select {
case msg := <-jobQueue:
fmt.Println("Processed job:", msg)
case <-time.After(2 * time.Second):
fmt.Println("Worker timeout reached! Moving on.")
}
6️⃣ Production REST API with net/http
package main
import (
"encoding/json"
"net/http"
)
type JobResponse struct {
ID string `json:"id"`
Title string `json:"title"`
}
func jobsHandler(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
response := JobResponse{ID: "JOB-401", Title: "Senior Golang Backend Lead"}
json.NewEncoder(w).Encode(response)
}
func main() {
mux := http.NewServeMux()
mux.HandleFunc("GET /api/v1/jobs", jobsHandler)
http.ListenAndServe(":8080", mux)
}
7️⃣ Context Package & Database Connection Pooling
database/sql):•
db.SetMaxOpenConns(25): Database server par CPU saturation rokne ke liye hard limit.•
db.SetMaxIdleConns(25): Reusable idle connections pool me maintain rakhna.•
db.SetConnMaxLifetime(5 * time.Minute): AWS/Cloud firewalls dwara stale TCP connections terminate hone se rokna.•
context.WithTimeout(ctx, 2*time.Second): Slow queries ko background me safely kill karna.