Skip to main content
CodeSpeedTest
Languages
Start TypingJump into a test — pick any languageAdaptive TrainingUnlock chars as you master themPractice DrillsFocused sessions targeting weak spotsDaily ChallengesNew coding challenges every dayRace ModeCompete against others in real timeAI OpponentRace against an AI at your WPM levelTournamentsLive coding speed tournamentsArcade GamesZType, Overkill Survival, Glyphica & moreGamificationXP, coins, badges & quests
LeaderboardGlobal rankings for every languageCertificatesEarn verifiable Bronze / Silver / Gold certsActivityDaily streaks & historical analyticsProfileYour stats, badges & achievements
Browse Languages500+ languages with real code examplesBlogTips, guides & deep divesFree ToolsWPM calculator, typing speed report & moreFAQCommon questions answeredGetting StartedNew to CodeSpeedTest?AboutOur story & missionSupportGet help — Pro users get priorityContactGet in touch with the team
Pricing
  1. Home
  2. /
  3. Learn
  4. /
  5. Go

Learn Go - 119 Code Examples & CST Typing Practice Test

Go (Golang) is a statically typed, compiled programming language designed at Google. It emphasizes simplicity, concurrency, and high-performance networking and system programming, making it ideal for cloud services, web backends, and distributed systems.

View all 119 Go code examples →
Basic Go Program StructureVariables, Constants, and TypesFunctions in GoStructs in GoMethods on StructsInterfaces in GoControl Flow in GoError Handling in GoArrays, Slices, and MapsString Handling in GoPointers in GoGoroutines in GoChannels in GoSelect Statement in GoPackages and ModulesHTTP Server in GoREST API (CRUD)Middleware PatternJSON HandlingDatabase Connectivity (SQL)CRUD with DatabaseORM (GORM)Authentication (JWT)Authorization (RBAC)Logging SystemConfiguration ManagementTesting in GoMocking and Interfaces in TestingFile HandlingConcurrency Patterns (Advanced)+89 more examples

Learn GO with Real Code Examples

Updated Nov 21, 2025

Explain

Go has a simple syntax, garbage collection, and built-in support for concurrent programming via goroutines and channels.

It produces fast, statically linked binaries and supports cross-compilation across platforms.

The Go standard library is extensive, especially for networking, HTTP, and system-level tasks.

Core Features

Simple, clear syntax for easy readability

Goroutines for lightweight concurrent execution

Channels for communication and synchronization

Interfaces for polymorphism

Package-based modular system

Basic Concepts Overview

Variables with `var` or short declaration `:=`

Functions and methods

Structs and interfaces

Control flow: `if`, `for`, `switch`

Concurrency with `go` and channels

Project Structure

cmd/ - main applications

pkg/ - libraries or reusable packages

internal/ - private modules

api/ - API definitions or proto files

test/ - additional test cases

Building Workflow

Write `.go` files in any editor

Organize code using packages

Compile with `go build` or run directly with `go run`

Use `go test` for unit testing

Manage dependencies with `go mod`

Difficulty Use Cases

Beginner: simple CLI tools

Intermediate: HTTP servers or API clients

Advanced: concurrent network applications

Expert: cloud-native microservices

Community: contribute to open-source Go projects

Comparisons

Simpler syntax than C++ or Java

Faster than interpreted languages like Python

Built-in concurrency unlike many languages

Statically compiled like Rust or C

Ideal for networked services and cloud applications

Versioning Timeline

2007 - Go designed at Google

2009 - Go 1 released publicly

2012-2015 - Go standard library and tooling mature

2016-2020 - Go adoption grows in cloud-native ecosystems

2025 - Go 1.21+ with generics and improved performance

Glossary

Goroutine: lightweight concurrent function

Channel: concurrency communication primitive

Interface: defines behavior without implementation

Struct: user-defined type grouping fields

Package: modular code unit

Installation Setup

Download Go from golang.org or via OS package manager

Install and configure GOPATH and GOROOT if necessary

Verify installation with `go version`

Check workspace setup with `go env`

Test with `go run hello.go`

Environment Setup

Install Go from golang.org

Set PATH to Go binary directory

Initialize workspace with `go mod init`

Install dependencies with `go get`

Test with `go run hello.go`

Config Files

Go source files `.go`

Module files `go.mod` and `go.sum`

Environment variables for GOPATH

Optional JSON/YAML config files

Build tags for platform-specific code

Cli Commands

go run main.go - run Go program

go build - compile binary

go test ./... - run tests

go fmt ./... - format code

go mod tidy - clean dependencies

Internationalization

UTF-8 strings natively supported

Standard library handles locale-sensitive operations

Community packages available for i18n

Cross-platform character support

Web frameworks integrate with translation libraries

Accessibility

Cross-platform compiled binaries

Readable syntax and tooling

Extensive documentation and examples

Gopher community and forums

Beginner to expert skill levels supported

Ui Styling

Primarily CLI or API output

Optional HTML generation for web

GUI via third-party libraries (Fyne, Gio)

Text formatting with fmt package

JSON/YAML for structured output

State Management

Variables and structs hold runtime state

Channels coordinate concurrent state

Mutexes or atomic operations for shared data

Functions encapsulate logic

Global variables minimized for safety

Data Management

Primitives: int, float, bool, string

Collections: slices, arrays, maps

Structs for complex types

JSON/XML/DB for persistent data

Memory safe via garbage collection

Architecture

Compiled binaries with static linking

Goroutine scheduler within runtime

Garbage-collected memory management

Package/module system for code organization

Cross-platform and architecture support via build tags

Rendering Model

N/A - Go is system/backend language, not GUI-focused

Can output text, JSON, HTML, or network streams

Integrates with frontend via APIs

CLI and network I/O as primary interface

Optional GUI via third-party libraries

Architectural Patterns

Procedural and modular package structure

Concurrency via goroutines and channels

Interface-based polymorphism

Event-driven network servers

Pipeline-style data processing

Real World Architectures

RESTful APIs

Microservices with gRPC

Concurrent data processing pipelines

Cloud-native infrastructure tools

Distributed systems and message brokers

Design Principles

Simplicity and readability first

Built-in concurrency primitives

Fast compilation and execution

Garbage collection for memory safety

Strong standard library for networking and system tasks

Scalability Guide

Use goroutines and channels for concurrent workloads

Optimize memory and I/O usage

Split applications into microservices

Use interfaces and modular design

Benchmark and profile with pprof

Migration Guide

Port scripts from Python/Perl to Go for performance

Use goroutines to parallelize tasks

Replace dynamic typing with explicit types

Modularize code into packages

Test cross-platform builds

Performance Notes

Compiled binaries are fast and memory-efficient

Goroutines are lightweight compared to threads

Garbage collection may add minor latency

Channels provide safe concurrent communication

Avoid blocking operations in critical goroutines

Security Notes

Validate all input in web servers

Avoid exposing secrets in source code

Use HTTPS and secure networking libraries

Limit concurrency to avoid DoS vulnerabilities

Keep Go runtime and modules updated

Monitoring Analytics

Use pprof for CPU/memory profiling

Log application metrics

Monitor goroutine and channel usage

Benchmark critical paths

Trace API and network requests

Code Quality

Use `go fmt` and `golint` for consistent style

Write unit and integration tests

Avoid global mutable state

Document packages and functions

Follow idiomatic Go patterns

Practical Examples

HTTP REST API server using `net/http`

Concurrent file processing with goroutines

Network socket communication

CLI tool for system monitoring

JSON parsing and data transformation

Troubleshooting

Check for compilation errors with `go build`

Validate module dependencies with `go mod tidy`

Debug runtime issues using `fmt.Println` or debugger

Monitor goroutine leaks or channel deadlocks

Check cross-platform builds for portability

Testing Guide

Write unit tests with `testing` package

Use table-driven tests

Run tests with `go test ./...`

Profile code with `pprof`

Use mocks for external dependencies

Deployment Options

Distribute as a single binary

Dockerize Go applications

Deploy on cloud platforms (GCP, AWS, Azure)

Cross-compile for multiple OS/architectures

Use CI/CD pipelines for automated builds

Tools Ecosystem

Go compiler and runtime

Go modules (`go mod`) for dependency management

Testing framework with `testing` package

Profiling and benchmarking (`pprof`, `bench`) tools

Linters and static analysis (`golint`, `staticcheck`)

Integrations

Databases via `database/sql` and drivers

Web frameworks: Gin, Echo, Fiber

Cloud services: AWS SDK, GCP SDK

Message brokers: Kafka, NATS, RabbitMQ

JSON, YAML, XML data parsing

Productivity Tips

Use `go fmt` and `go vet` regularly

Leverage standard library extensively

Use goroutines and channels for concurrency

Keep code modular and reusable

Automate testing and deployment with CI/CD

Challenges

Build a concurrent file processor

Implement a REST API server

Create a CLI tool with subcommands

Write unit and integration tests

Deploy binary to multiple platforms

Learning Path

Learn Go syntax and variables

Understand structs, interfaces, and methods

Practice goroutines and channels

Build CLI or HTTP applications

Contribute to Go open-source projects

Skill Improvement Plan

Week 1: Go basics, variables, control flow

Week 2: Functions, structs, and methods

Week 3: Concurrency and channels

Week 4: Networking and HTTP servers

Week 5: Testing, profiling, and deployment

Interview Questions

Explain goroutines and how they differ from threads

How do channels work in Go?

What is the purpose of `defer`?

Explain Go modules and package management

What are interfaces and how are they used?

Cheat Sheet

var x int - declare variable

x := 42 - short variable declaration

func add(a, b int) int { return a+b } - define function

go f() - start goroutine

ch := make(chan int) - create channel

Books

The Go Programming Language by Alan Donovan & Brian Kernighan

Go in Action by William Kennedy

Concurrency in Go by Katherine Cox-Buday

Introducing Go by Caleb Doxsey

Go Programming Blueprints by Mat Ryer

Tutorials

A Tour of Go

Learn Go with Tests

Building Web Apps with Go

Concurrency in Go

Go Modules and Dependency Management

Official Docs

https://golang.org/doc/

Go standard library documentation

Go blog and tutorials

Community Links

Gophers Slack

Gopher Reddit

GitHub Go projects

GopherCon Conference

Go Forum

Community Support

Gophers Slack and Discord channels

Go Forum and Reddit

GitHub open-source Go projects

Go conferences (GopherCon, GoLab)

Official Go blog and tutorials

Monetization

Develop cloud infrastructure tools

SaaS backend services

CLI utilities for enterprises

Open-source consulting and support

Educational courses for Go developers

Future Roadmap

Improved generics and type inference

Enhanced runtime performance

Better support for mobile and GUI

Expanded standard library for cloud tasks

Stronger community and ecosystem growth

When Not To Use

Desktop GUI-heavy applications

Mobile app frontend (though supported via gomobile)

Real-time high-performance graphics/games

Heavy metaprogramming or DSLs

Scripts for text processing with minimal compilation overhead

Final Summary

Go is a compiled, statically typed language designed for simplicity, performance, and concurrency.

It excels at backend services, cloud applications, and distributed systems.

Goroutines and channels provide easy concurrency.

Go produces fast, portable binaries with minimal dependencies.

Strong standard library and tooling make it highly productive for system programming.

Faq

Is Go suitable for web development?

Yes, Go is widely used for web servers and APIs.

Can Go handle concurrent tasks?

Yes, goroutines and channels make concurrency simple.

Which platforms support Go?

Windows, Linux, macOS, BSD, ARM, and others.

Is Go statically or dynamically typed?

Go is statically typed.

Does Go support object-oriented programming?

Yes, via structs and interfaces, though without classes.

Code Sample Descriptions

1

Basic Go Program Structure

package main

import "fmt"

func main() {
    fmt.Println("Hello, Go!")
}

Write and run a simple Go program demonstrating the basic program structure.

Let’s Try →
2

Variables, Constants, and Types

package main

import "fmt"

func main() {
    var age int = 25
    height := 5.9
    const language = "Go"
    isBackend := true

    fmt.Println("Age:", age)
    fmt.Println("Height:", height)
    fmt.Println("Language:", language)
    fmt.Println("Backend:", isBackend)
}

Demonstrates variable declarations, constants, basic data types, and type inference in Go.

Let’s Try →
3

Functions in Go

package main

import "fmt"

func add(a, b int) int {
    return a + b
}

func divide(a, b int) (int, int) {
    return a / b, a % b
}

func rectangle(width, height int) (area int) {
    area = width * height
    return
}

func main() {
    sum := add(10, 5)
    quotient, remainder := divide(17, 5)
    area := rectangle(6, 4)

    fmt.Println("Sum:", sum)
    fmt.Println("Quotient:", quotient)
    fmt.Println("Remainder:", remainder)
    fmt.Println("Area:", area)
}

Demonstrates Go functions with parameters, return values, multiple returns, and named returns.

Let’s Try →
4

Structs in Go

package main

import "fmt"

type Address struct {
    City string
    Country string
}

type User struct {
    Name string
    Age int
    Address Address
}

func main() {
    user := User{
        Name: "Alice",
        Age: 28,
        Address: Address{
            City: "New York",
            Country: "USA",
        },
    }

    fmt.Println("Name:", user.Name)
    fmt.Println("Age:", user.Age)
    fmt.Println("City:", user.Address.City)
    fmt.Println("Country:", user.Address.Country)
}

Demonstrates defining structs, nested structs, and composition to model real-world data.

Let’s Try →
5

Methods on Structs

package main

import "fmt"

type BankAccount struct {
    Owner string
    Balance float64
}

func (b BankAccount) Display() {
    fmt.Println("Owner:", b.Owner)
    fmt.Println("Balance:", b.Balance)
}

func (b *BankAccount) Deposit(amount float64) {
    b.Balance += amount
}

func main() {
    account := BankAccount{Owner: "Alice", Balance: 1000}

    account.Display()
    account.Deposit(250)

    fmt.Println("After Deposit:")
    account.Display()
}

Demonstrates value receivers and pointer receivers by attaching behavior to structs.

Let’s Try →
6

Interfaces in Go

package main

import "fmt"

type Speaker interface {
    Speak() string
}

type Dog struct{}

func (Dog) Speak() string {
    return "Woof!"
}

type Cat struct{}

func (Cat) Speak() string {
    return "Meow!"
}

func announce(s Speaker) {
    fmt.Println(s.Speak())
}

func main() {
    announce(Dog{})
    announce(Cat{})
}

Demonstrates interfaces, implicit implementation, and polymorphism in Go.

Let’s Try →
7

Control Flow in Go

package main

import "fmt"

func main() {
    score := 85

    if score >= 90 {
        fmt.Println("Grade: A")
    } else if score >= 75 {
        fmt.Println("Grade: B")
    } else {
        fmt.Println("Grade: C")
    }

    switch {
    case score >= 90:
        fmt.Println("Excellent")
    case score >= 75:
        fmt.Println("Good")
    default:
        fmt.Println("Keep Practicing")
    }

    fmt.Print("Numbers: ")
    for i := 1; i <= 5; i++ {
        fmt.Print(i, " ")
    }
}

Demonstrates conditional statements, switch cases, and the for loop in Go.

Let’s Try →
8

Error Handling in Go

package main

import (
    "errors"
    "fmt"
)

func divide(a, b float64) (float64, error) {
    if b == 0 {
        return 0, errors.New("division by zero")
    }
    return a / b, nil
}

func main() {
    result, err := divide(10, 0)
    if err != nil {
        fmt.Println("Error:", err)
        return
    }

    fmt.Println("Result:", result)
}

Demonstrates explicit error handling using the error type, errors.New, and wrapped errors.

Let’s Try →
9

Arrays, Slices, and Maps

package main

import "fmt"

func main() {
    // Array
    numbers := [3]int{10, 20, 30}

    // Slice
    fruits := []string{"Apple", "Banana"}
    fruits = append(fruits, "Orange")

    // Map
    ages := map[string]int{
        "Alice": 25,
        "Bob": 30,
    }

    fmt.Println("Array:", numbers)
    fmt.Println("Slice:", fruits)
    fmt.Println("Map:", ages)
    fmt.Println("Slice Length:", len(fruits))
    fmt.Println("Slice Capacity:", cap(fruits))
}

Demonstrates arrays, slices, maps, append, and the len/cap built-in functions.

Let’s Try →
10

String Handling in Go

package main

import (
    "fmt"
    "strings"
)

func main() {
    text := "Go,is,fast"

    parts := strings.Split(text, ",")
    joined := strings.Join(parts, " ")
    contains := strings.Contains(joined, "fast")

    fmt.Println("Original:", text)
    fmt.Println("Split:", parts)
    fmt.Println("Joined:", joined)
    fmt.Println("Contains 'fast':", contains)
}

Demonstrates common string operations using the strings package.

Let’s Try →
11

Pointers in Go

package main

import "fmt"

func increment(value *int) {
    *value++
}

func main() {
    number := 10
    pointer := &number

    fmt.Println("Value:", number)
    fmt.Println("Address:", pointer)

    increment(pointer)

    fmt.Println("Updated Value:", number)
}

Demonstrates pointers, the address operator (&), dereferencing (*), and passing pointers to functions.

Let’s Try →
12

Goroutines in Go

package main

import (
    "fmt"
    "time"
)

func worker(name string) {
    fmt.Println(name, "started")
    time.Sleep(time.Second)
    fmt.Println(name, "finished")
}

func main() {
    go worker("Worker 1")
    go worker("Worker 2")

    time.Sleep(2 * time.Second)
    fmt.Println("Main finished")
}

Demonstrates launching lightweight goroutines to execute functions concurrently.

Let’s Try →
13

Channels in Go

package main

import "fmt"

func main() {
    messages := make(chan string)

    go func() {
        messages <- "Hello from goroutine!"
    }()

    msg := <-messages
    fmt.Println("Received:", msg)
}

Demonstrates sending and receiving data between goroutines using channels.

Let’s Try →
14

Select Statement in Go

package main

import (
    "fmt"
    "time"
)

func main() {
    ch1 := make(chan string)
    ch2 := make(chan string)

    go func() {
        time.Sleep(500 * time.Millisecond)
        ch1 <- "Message from channel 1"
    }()

    go func() {
        time.Sleep(time.Second)
        ch2 <- "Message from channel 2"
    }()

    select {
    case msg := <-ch1:
        fmt.Println(msg)
    case msg := <-ch2:
        fmt.Println(msg)
    }
}

Demonstrates using the select statement to handle multiple channel operations.

Let’s Try →
15

Packages and Modules

// greetings/greetings.go
package greetings

func Hello(name string) string {
    return "Hello, " + name + "!"
}

// main.go
package main

import (
    "fmt"
    "example.com/myapp/greetings"
)

func main() {
    fmt.Println(greetings.Hello("Go"))
}

Demonstrates organizing Go code into packages and modules using imports.

Let’s Try →
16

HTTP Server in Go

package main

import (
    "fmt"
    "net/http"
)

func homeHandler(w http.ResponseWriter, r *http.Request) {
    fmt.Fprintln(w, "Welcome to Go HTTP Server!")
}

func main() {
    http.HandleFunc("/", homeHandler)

    fmt.Println("Server running at http://localhost:8080")
    http.ListenAndServe(":8080", nil)
}

Demonstrates creating a basic HTTP server using the net/http package.

Let’s Try →
17

REST API (CRUD)

package main

import (
    "encoding/json"
    "net/http"
)

type User struct {
    ID   int    `json:"id"`
    Name string `json:"name"`
}

var users = []User{{ID: 1, Name: "Alice"}}

func usersHandler(w http.ResponseWriter, r *http.Request) {
    w.Header().Set("Content-Type", "application/json")

    switch r.Method {
    case http.MethodGet:
        json.NewEncoder(w).Encode(users)
    case http.MethodPost:
        var user User
        json.NewDecoder(r.Body).Decode(&user)
        users = append(users, user)
        json.NewEncoder(w).Encode(user)
    case http.MethodPut:
        json.NewEncoder(w).Encode(map[string]string{"message": "User updated"})
    case http.MethodDelete:
        json.NewEncoder(w).Encode(map[string]string{"message": "User deleted"})
    default:
        http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
    }
}

func main() {
    http.HandleFunc("/users", usersHandler)
    http.ListenAndServe(":8080", nil)
}

Demonstrates building a simple REST API with CRUD operations using JSON request and response handling.

Let’s Try →
18

Middleware Pattern

package main

import (
    "fmt"
    "log"
    "net/http"
)

func loggingMiddleware(next http.Handler) http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        log.Println("Request:", r.Method, r.URL.Path)
        next.ServeHTTP(w, r)
    })
}

func homeHandler(w http.ResponseWriter, r *http.Request) {
    fmt.Fprintln(w, "Welcome!")
}

func main() {
    mux := http.NewServeMux()
    mux.HandleFunc("/", homeHandler)

    fmt.Println("Server running at http://localhost:8080")
    http.ListenAndServe(":8080", loggingMiddleware(mux))
}

Demonstrates middleware for logging requests before passing control to the next handler.

Let’s Try →
19

JSON Handling

package main

import (
    "encoding/json"
    "fmt"
)

type User struct {
    ID   int    `json:"id"`
    Name string `json:"name"`
}

func main() {
    user := User{ID: 1, Name: "Alice"}

    data, _ := json.Marshal(user)
    fmt.Println("JSON:", string(data))

    var decoded User
    json.Unmarshal(data, &decoded)
    fmt.Println("Decoded:", decoded)
}

Demonstrates encoding and decoding JSON using struct tags, json.Marshal, and json.Unmarshal.

Let’s Try →
20

Database Connectivity (SQL)

package main

import (
    "database/sql"
    "fmt"

    _ "github.com/lib/pq"
)

func main() {
    db, err := sql.Open("postgres", "host=localhost user=postgres password=secret dbname=testdb sslmode=disable")
    if err != nil {
        panic(err)
    }
    defer db.Close()

    var version string
    err = db.QueryRow("SELECT version()") .Scan(&version)
    if err != nil {
        panic(err)
    }

    fmt.Println("Connected to:", version)
}

Demonstrates connecting to a SQL database, executing a query, and reading results using the database/sql package.

Let’s Try →
21

CRUD with Database

package main

import (
    "database/sql"
    "fmt"

    _ "github.com/lib/pq"
)

type User struct {
    ID   int
    Name string
}

func main() {
    db, err := sql.Open("postgres", "host=localhost user=postgres password=secret dbname=testdb sslmode=disable")
    if err != nil {
        panic(err)
    }
    defer db.Close()

    // INSERT
    _, _ = db.Exec("INSERT INTO users(name) VALUES($1)", "Alice")

    // SELECT
    var user User
    db.QueryRow("SELECT id, name FROM users WHERE id = $1", 1).Scan(&user.ID, &user.Name)
    fmt.Println("User:", user)

    // UPDATE
    _, _ = db.Exec("UPDATE users SET name = $1 WHERE id = $2", "Bob", 1)

    // DELETE
    _, _ = db.Exec("DELETE FROM users WHERE id = $1", 1)

    fmt.Println("CRUD operations completed")
}

Demonstrates basic CRUD operations (SELECT, INSERT, UPDATE, DELETE) using the database/sql package.

Let’s Try →
22

ORM (GORM)

package main

import (
    "fmt"

    "gorm.io/driver/sqlite"
    "gorm.io/gorm"
)

type User struct {
    ID   uint
    Name string
    Email string
}

func main() {
    db, err := gorm.Open(sqlite.Open("app.db"), &gorm.Config{})
    if err != nil {
        panic(err)
    }

    db.AutoMigrate(&User{})

    user := User{Name: "Alice", Email: "alice@example.com"}
    db.Create(&user)

    var result User
    db.First(&result, user.ID)

    fmt.Println(result.Name, result.Email)
}

Demonstrates using GORM to define models, perform auto migration, and query records.

Let’s Try →
23

Authentication (JWT)

package main

import (
    "fmt"
    "time"

    "github.com/golang-jwt/jwt/v5"
)

var secretKey = []byte("my-secret-key")

func main() {
    claims := jwt.MapClaims{
        "username": "alice",
        "exp": time.Now().Add(time.Hour).Unix(),
    }

    token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
    tokenString, _ := token.SignedString(secretKey)

    fmt.Println("JWT Token Generated")
    fmt.Println("Token:", tokenString)

    parsedToken, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {
        return secretKey, nil
    })

    fmt.Println("Valid:", err == nil && parsedToken.Valid)
}

Demonstrates creating and validating JWT tokens to secure API endpoints using authentication middleware.

Let’s Try →
24

Authorization (RBAC)

package main

import (
    "fmt"
    "net/http"
)

func authorize(requiredRole string, next http.HandlerFunc) http.HandlerFunc {
    return func(w http.ResponseWriter, r *http.Request) {
        userRole := r.Header.Get("Role")
        if userRole != requiredRole {
            http.Error(w, "Forbidden", http.StatusForbidden)
            return
        }
        next(w, r)
    }
}

func adminHandler(w http.ResponseWriter, r *http.Request) {
    fmt.Fprintln(w, "Welcome, Admin!")
}

func main() {
    http.HandleFunc("/admin", authorize("admin", adminHandler))
    fmt.Println("Server running at http://localhost:8080")
    http.ListenAndServe(":8080", nil)
}

Demonstrates Role-Based Access Control (RBAC) using middleware to authorize users based on roles and permissions.

Let’s Try →
25

Logging System

package main

import (
    "log"
    "os"
)

func main() {
    log.SetPrefix("INFO: ")
    log.SetFlags(log.Ldate | log.Ltime)

    log.Println("Application started")

    user := "Alice"
    log.Printf("User %s logged in\n", user)

    log.Println("Application finished")

    os.Exit(0)
}

Demonstrates logging application events using Go's log package for observability.

Let’s Try →
26

Configuration Management

package main

import (
    "fmt"
    "os"
)

func main() {
    os.Setenv("APP_PORT", "8080")
    os.Setenv("APP_ENV", "development")

    port := os.Getenv("APP_PORT")
    env := os.Getenv("APP_ENV")

    fmt.Println("Environment:", env)
    fmt.Println("Port:", port)
}

Demonstrates reading configuration from environment variables for application setup.

Let’s Try →
27

Testing in Go

// math.go
package main

func Add(a, b int) int {
    return a + b
}

// math_test.go
package main

import "testing"

func TestAdd(t *testing.T) {
    tests := []struct {
        a, b int
        want int
    }{
        {2, 3, 5},
        {10, 5, 15},
        {-1, 1, 0},
    }

    for _, tt := range tests {
        got := Add(tt.a, tt.b)
        if got != tt.want {
            t.Errorf("Add(%d, %d) = %d; want %d", tt.a, tt.b, got, tt.want)
        }
    }
}

Demonstrates writing unit tests using the testing package with table-driven tests.

Let’s Try →
28

Mocking and Interfaces in Testing

package main

import "fmt"

type UserRepository interface {
    GetUser(id int) string
}

type MockRepository struct{}

func (m MockRepository) GetUser(id int) string {
    return "Alice"
}

type UserService struct {
    repo UserRepository
}

func (s UserService) GetUserName(id int) string {
    return s.repo.GetUser(id)
}

func main() {
    service := UserService{repo: MockRepository{}}
    fmt.Println(service.GetUserName(1))
}

Demonstrates interface mocking and dependency injection for isolated unit testing.

Let’s Try →
29

File Handling

package main

import (
    "fmt"
    "os"
)

func main() {
    content := []byte("Hello, Go File!")

    err := os.WriteFile("sample.txt", content, 0644)
    if err != nil {
        panic(err)
    }

    data, err := os.ReadFile("sample.txt")
    if err != nil {
        panic(err)
    }

    fmt.Println(string(data))
}

Demonstrates creating, writing, and reading a file using the os package.

Let’s Try →
30

Concurrency Patterns (Advanced)

package main

import (
    "fmt"
    "sync"
)

func worker(id int, jobs <-chan int, results chan<- int, wg *sync.WaitGroup) {
    defer wg.Done()
    for job := range jobs {
        fmt.Println("Worker", id, "processing", job)
        results <- job * job
    }
}

func main() {
    jobs := make(chan int, 3)
    results := make(chan int, 3)
    var wg sync.WaitGroup

    for w := 1; w <= 2; w++ {
        wg.Add(1)
        go worker(w, jobs, results, &wg)
    }

    for j := 1; j <= 3; j++ {
        jobs <- j
    }
    close(jobs)

    wg.Wait()
    close(results)

    fmt.Println("Results:")
    for result := range results {
        fmt.Println(result)
    }
}

Demonstrates a worker pool pattern using goroutines and channels for concurrent task processing.

Let’s Try →
31

Context Package

package main

import (
    "context"
    "fmt"
    "time"
)

func main() {
    ctx, cancel := context.WithTimeout(context.Background(), time.Second)
    defer cancel()

    select {
    case <-time.After(2 * time.Second):
        fmt.Println("Task completed")
    case <-ctx.Done():
        fmt.Println("Task cancelled:", ctx.Err())
    }
}

Demonstrates using context.Context to manage request timeouts and cancellation.

Let’s Try →
32

Graceful Shutdown

package main

import (
    "context"
    "fmt"
    "net/http"
    "os"
    "os/signal"
    "syscall"
    "time"
)

func main() {
    server := &http.Server{Addr: ":8080"}

    go func() {
        fmt.Println("Server running on :8080")
        server.ListenAndServe()
    }()

    quit := make(chan os.Signal, 1)
    signal.Notify(quit, os.Interrupt, syscall.SIGTERM)
    <-quit

    fmt.Println("Shutting down server...")

    ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
    defer cancel()

    server.Shutdown(ctx)

    fmt.Println("Server stopped gracefully")
}

Demonstrates gracefully shutting down an HTTP server by handling operating system signals.

Let’s Try →
33

Microservices Basics

package main

import (
    "fmt"
    "net/http"
)

func userHandler(w http.ResponseWriter, r *http.Request) {
    fmt.Fprintln(w, "User Service Response")
}

func main() {
    http.HandleFunc("/users", userHandler)

    fmt.Println("User Service running on :8080")
    http.ListenAndServe(":8080", nil)
}

Demonstrates a simple microservice exposing a REST endpoint that can communicate with other services over HTTP.

Let’s Try →
34

gRPC Services

// hello.proto
syntax = "proto3";

package hello;

service Greeter {
    rpc SayHello (HelloRequest) returns (HelloReply);
}

message HelloRequest {
    string name = 1;
}

message HelloReply {
    string message = 1;
}

// server.go
package main

import (
    "context"
    "fmt"
)

type server struct{}

func (s *server) SayHello(ctx context.Context, req *HelloRequest) (*HelloReply, error) {
    return &HelloReply{Message: "Hello, " + req.Name + "!"}, nil
}

func main() {
    fmt.Println("gRPC server running on :50051")
}

Demonstrates defining and implementing a simple gRPC service using Protocol Buffers.

Let’s Try →
35

Docker for Go Apps

// main.go
package main

import "fmt"

func main() {
    fmt.Println("Hello from Dockerized Go App!")
}

// Dockerfile
FROM golang:1.22-alpine AS builder

WORKDIR /app
COPY . .
RUN go build -o app .

FROM alpine:latest
WORKDIR /root/
COPY --from=builder /app/app .
CMD ["./app"]

Demonstrates containerizing a Go application using a Dockerfile and running it in a Docker container.

Let’s Try →
36

Deployment Basics

// Build the application
$ go build -o app main.go

// Copy binary to Linux server
$ scp app user@server:/home/user/

// Run the application
$ ssh user@server
$ ./app

Demonstrates the basic steps for building and deploying a Go application to a Linux server with CI/CD integration.

Let’s Try →
37

Clean Architecture

package main

import "fmt"

// Domain

type User struct {
    Name string
}

// Repository Interface

type UserRepository interface {
    FindByID(id int) User
}

// Infrastructure

type MemoryRepository struct{}

func (r MemoryRepository) FindByID(id int) User {
    return User{Name: "Alice"}
}

// Use Case

type UserService struct {
    repo UserRepository
}

func (s UserService) GetUser(id int) User {
    return s.repo.FindByID(id)
}

func main() {
    service := UserService{repo: MemoryRepository{}}
    user := service.GetUser(1)
    fmt.Println(user.Name)
}

Demonstrates organizing a Go backend into clean, testable layers using dependency injection and the repository pattern.

Let’s Try →
38

Repository Pattern

package main

import "fmt"

// Entity

type User struct {
    ID   int
    Name string
}

// Repository Interface

type UserRepository interface {
    GetByID(id int) User
}

// Database Implementation

type SQLRepository struct{}

func (r SQLRepository) GetByID(id int) User {
    return User{ID: id, Name: "Alice"}
}

// Mock Implementation

type MockRepository struct{}

func (r MockRepository) GetByID(id int) User {
    return User{ID: id, Name: "Test User"}
}

// Business Logic

type UserService struct {
    repo UserRepository
}

func (s UserService) GetUser(id int) User {
    return s.repo.GetByID(id)
}

func main() {
    service := UserService{repo: SQLRepository{}}
    fmt.Println(service.GetUser(1))
}

Demonstrates separating business logic from data access using the Repository Pattern and dependency injection.

Let’s Try →
39

Service Layer Pattern

package main

import (
    "errors"
    "fmt"
)

type User struct {
    Name string
}

type UserService struct{}

func (s UserService) CreateUser(name string) (User, error) {
    if name == "" {
        return User{}, errors.New("name is required")
    }

    // Business logic
    user := User{Name: name}

    // Transaction or repository call would go here
    return user, nil
}

func main() {
    service := UserService{}

    user, err := service.CreateUser("Alice")
    if err != nil {
        fmt.Println(err)
        return
    }

    fmt.Println("User created:", user)
}

Demonstrates using a service layer to encapsulate validation and business logic, keeping controllers thin and independent.

Let’s Try →
40

Configuration Management

package main

import (
    "fmt"
    "os"
)

type Config struct {
    Port   string
    Env    string
    DBHost string
}

func loadConfig() Config {
    return Config{
        Port:   os.Getenv("APP_PORT"),
        Env:    os.Getenv("APP_ENV"),
        DBHost: os.Getenv("DB_HOST"),
    }
}

func main() {
    os.Setenv("APP_PORT", "8080")
    os.Setenv("APP_ENV", "production")
    os.Setenv("DB_HOST", "localhost")

    config := loadConfig()

    fmt.Println("Environment:", config.Env)
    fmt.Println("Port:", config.Port)
    fmt.Println("Database:", config.DBHost)
}

Demonstrates loading application configuration from environment variables while supporting external configuration files.

Let’s Try →
41

Structured Logging

package main

import (
    "encoding/json"
    "fmt"
    "time"
)

type LogEntry struct {
    Time          string `json:"time"`
    Level         string `json:"level"`
    RequestID     string `json:"request_id"`
    CorrelationID string `json:"correlation_id"`
    Message       string `json:"message"`
}

func main() {
    entry := LogEntry{
        Time:          time.Now().Format(time.RFC3339),
        Level:         "INFO",
        RequestID:     "req-12345",
        CorrelationID: "corr-67890",
        Message:       "User login successful",
    }

    log, _ := json.Marshal(entry)
    fmt.Println(string(log))
}

Demonstrates generating structured JSON logs with log levels and request correlation IDs.

Let’s Try →
42

Error Handling Strategy

package main

import (
    "errors"
    "fmt"
)

var ErrUserNotFound = errors.New("user not found")

type ValidationError struct {
    Field string
}

func (e ValidationError) Error() string {
    return "invalid field: " + e.Field
}

func findUser(id int) error {
    if id == 0 {
        return ValidationError{Field: "id"}
    }
    return fmt.Errorf("database lookup failed: %w", ErrUserNotFound)
}

func main() {
    err := findUser(1)
    if err != nil {
        fmt.Println(err)

        if errors.Is(err, ErrUserNotFound) {
            fmt.Println("Handle missing user")
        }

        var ve ValidationError
        if errors.As(err, &ve) {
            fmt.Println("Validation Error:", ve.Field)
        }
    }
}

Demonstrates production-grade error handling using custom errors, sentinel errors, error wrapping, and error inspection.

Let’s Try →
43

Validation Layer

package main

import (
    "fmt"

    "github.com/go-playground/validator/v10"
)

type UserRequest struct {
    Name  string `validate:"required,min=2"`
    Email string `validate:"required,email"`
    Age   int    `validate:"gte=18"`
}

func main() {
    validate := validator.New()

    request := UserRequest{
        Name:  "A",
        Email: "invalid-email",
        Age:   16,
    }

    if err := validate.Struct(request); err != nil {
        fmt.Println("Validation failed:")
        for _, e := range err.(validator.ValidationErrors) {
            fmt.Printf("- %s failed on '%s'\n", e.Field(), e.Tag())
        }
        return
    }

    fmt.Println("Validation successful")
}

Demonstrates validating incoming request data using struct validation and returning meaningful error responses.

Let’s Try →
44

Middleware Architecture

package main

import (
    "fmt"
    "log"
    "net/http"
)

func Logging(next http.Handler) http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        log.Println(r.Method, r.URL.Path)
        next.ServeHTTP(w, r)
    })
}

func Authentication(next http.Handler) http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        fmt.Println("Authentication successful")
        next.ServeHTTP(w, r)
    })
}

func handler(w http.ResponseWriter, r *http.Request) {
    fmt.Fprintln(w, "Hello, Go!")
}

func main() {
    h := Logging(Authentication(http.HandlerFunc(handler)))
    http.Handle("/", h)

    fmt.Println("Server running on :8080")
    http.ListenAndServe(":8080", nil)
}

Demonstrates chaining reusable HTTP middleware for logging, authentication, rate limiting, and panic recovery.

Let’s Try →
45

Authentication

package main

import (
    "fmt"

    "golang.org/x/crypto/bcrypt"
)

func main() {
    password := "secret123"

    hashedPassword, _ := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)

    fmt.Println("Password hashed:", string(hashedPassword))

    err := bcrypt.CompareHashAndPassword(hashedPassword, []byte(password))
    if err == nil {
        fmt.Println("Password verified")
    }

    fmt.Println("Generate JWT access token")
    fmt.Println("Generate refresh token")
}

Demonstrates a basic authentication flow using password hashing, JWT tokens, and refresh token concepts.

Let’s Try →
46

Authorization

package main

import "fmt"

type User struct {
    Name string
    Role string
    Department string
}

func checkAccess(user User, resource string) bool {
    // RBAC: Role based rule
    if user.Role == "admin" {
        return true
    }

    // ABAC: Attribute based rule
    if user.Department == "finance" && resource == "reports" {
        return true
    }

    // Policy based authorization
    return false
}

func main() {
    user := User{
        Name: "Alice",
        Role: "manager",
        Department: "finance",
    }

    allowed := checkAccess(user, "reports")

    fmt.Println("Access granted:", allowed)
}

Demonstrates authorization concepts using RBAC, ABAC, and policy-based access control.

Let’s Try →
47

API Versioning

package main

import (
    "fmt"
    "net/http"
)

func userV1(w http.ResponseWriter, r *http.Request) {
    fmt.Fprintln(w, "User API Version 1")
}

func userV2(w http.ResponseWriter, r *http.Request) {
    fmt.Fprintln(w, "User API Version 2 - Enhanced Response")
}

func main() {
    http.HandleFunc("/api/v1/users", userV1)
    http.HandleFunc("/api/v2/users", userV2)

    fmt.Println("API Server running on :8080")
    http.ListenAndServe(":8080", nil)
}

Demonstrates API versioning strategies using URI versioning, header versioning, and semantic versioning concepts.

Let’s Try →
48

Pagination

package main

import (
    "fmt"
    "net/http"
    "strconv"
)

var users = []string{"Alice", "Bob", "Charlie", "David", "Eve"}

func usersHandler(w http.ResponseWriter, r *http.Request) {
    offset, _ := strconv.Atoi(r.URL.Query().Get("offset"))
    limit, _ := strconv.Atoi(r.URL.Query().Get("limit"))

    if limit == 0 {
        limit = 2
    }

    end := offset + limit
    if end > len(users) {
        end = len(users)
    }

    fmt.Fprintln(w, users[offset:end])
}

func main() {
    http.HandleFunc("/users", usersHandler)

    fmt.Println("API running on :8080")
    http.ListenAndServe(":8080", nil)
}

Demonstrates API pagination techniques using offset pagination and cursor-based pagination patterns.

Let’s Try →
49

Filtering & Searching

package main

import (
    "fmt"
    "net/http"
    "strings"
)

var products = []string{"Laptop", "Phone", "Keyboard", "Monitor"}

func searchHandler(w http.ResponseWriter, r *http.Request) {
    query := r.URL.Query().Get("search")

    fmt.Println("Search Query:", query)

    for _, product := range products {
        if strings.Contains(strings.ToLower(product), strings.ToLower(query)) {
            fmt.Fprintln(w, product)
        }
    }
}

func main() {
    http.HandleFunc("/products", searchHandler)

    fmt.Println("Search API running on :8080")
    http.ListenAndServe(":8080", nil)
}

Demonstrates building search APIs using query parameters and dynamic filtering logic.

Let’s Try →
50

Sorting APIs

package main

import (
    "fmt"
    "net/http"
    "sort"
)

type Product struct {
    Name  string
    Price int
}

var products = []Product{
    {Name: "Laptop", Price: 1200},
    {Name: "Phone", Price: 800},
    {Name: "Tablet", Price: 500},
}

func productsHandler(w http.ResponseWriter, r *http.Request) {
    order := r.URL.Query().Get("sort")

    sort.Slice(products, func(i, j int) bool {
        if order == "price" {
            return products[i].Price < products[j].Price
        }
        return products[i].Name < products[j].Name
    })

    fmt.Fprintln(w, products)
}

func main() {
    http.HandleFunc("/products", productsHandler)

    fmt.Println("Sorting API running on :8080")
    http.ListenAndServe(":8080", nil)
}

Demonstrates API sorting using query parameters with dynamic ordering and multi-column sorting concepts.

Let’s Try →
51

File Upload APIs

package main

import (
    "fmt"
    "net/http"
)

func uploadHandler(w http.ResponseWriter, r *http.Request) {
    err := r.ParseMultipartForm(10 << 20)
    if err != nil {
        fmt.Fprintln(w, "Invalid file upload")
        return
    }

    file, header, err := r.FormFile("file")
    if err != nil {
        fmt.Fprintln(w, "File not found")
        return
    }
    defer file.Close()

    fmt.Fprintln(w, "Uploaded:", header.Filename)
}

func main() {
    http.HandleFunc("/upload", uploadHandler)

    fmt.Println("Upload API running on :8080")
    http.ListenAndServe(":8080", nil)
}

Demonstrates handling file uploads using multipart forms, streaming, and file validation.

Let’s Try →
52

Background Jobs

package main

import (
    "fmt"
    "time"
)

func worker(id int, jobs <-chan string) {
    for job := range jobs {
        fmt.Println("Worker", id, "processing", job)

        for attempt := 1; attempt <= 3; attempt++ {
            fmt.Println("Attempt", attempt, "for", job)
            if attempt == 3 {
                fmt.Println(job, "completed")
            }
            time.Sleep(time.Millisecond * 100)
        }
    }
}

func main() {
    jobs := make(chan string, 3)

    for i := 1; i <= 2; i++ {
        go worker(i, jobs)
    }

    jobs <- "Send Email"
    jobs <- "Generate Report"
    jobs <- "Process Payment"

    close(jobs)
    time.Sleep(time.Second)
}

Demonstrates processing background tasks using worker pools, job queues, and retry logic.

Let’s Try →
53

Scheduler (Cron Jobs)

package main

import (
    "fmt"
    "time"
)

func cleanupJob() {
    fmt.Println("Running cleanup job...")
    fmt.Println("Expired sessions removed")
}

func main() {
    // Example cron schedule: Every minute
    cronExpression := "*/1 * * * *"

    fmt.Println("Scheduler started")
    fmt.Println("Cron:", cronExpression)

    for i := 0; i < 2; i++ {
        cleanupJob()
        time.Sleep(time.Second)
    }
}

Demonstrates running scheduled tasks using cron expressions for automated backend jobs.

Let’s Try →
54

Redis

package main

import (
    "fmt"
    "time"
)

type Cache struct {
    value string
    expiry time.Time
}

func main() {
    cache := Cache{
        value: "user_data",
        expiry: time.Now().Add(time.Minute),
    }

    fmt.Println("Cached Value:", cache.value)
    fmt.Println("TTL:", time.Until(cache.expiry))

    fmt.Println("Publishing message: user.updated")
    fmt.Println("Distributed lock acquired")
}

Demonstrates using Redis concepts including caching, TTL expiration, Pub/Sub messaging, and distributed locking.

Let’s Try →
55

Caching Strategies

package main

import "fmt"

var database = map[int]string{
    1: "Alice",
}

var cache = map[int]string{}

func getUser(id int) string {
    // Cache Aside Pattern
    if value, ok := cache[id]; ok {
        return value
    }

    value := database[id]
    cache[id] = value
    return value
}

func updateUser(id int, name string) {
    // Write Through Pattern
    database[id] = name
    cache[id] = name
}

func invalidateCache(id int) {
    delete(cache, id)
}

func main() {
    fmt.Println("First Request:", getUser(1))
    fmt.Println("Second Request:", getUser(1))

    updateUser(1, "Bob")
    fmt.Println("Updated:", getUser(1))

    invalidateCache(1)
    fmt.Println("Cache invalidated")
}

Demonstrates common caching strategies including cache-aside, read-through, write-through, and cache invalidation patterns.

Let’s Try →
56

Message Queues

package main

import "fmt"

type MessageQueue struct {
    messages chan string
}

func NewQueue() MessageQueue {
    return MessageQueue{
        messages: make(chan string, 3),
    }
}

func producer(queue MessageQueue) {
    queue.messages <- "Order Created"
    queue.messages <- "Payment Processed"
    queue.messages <- "Email Sent"
}

func consumer(queue MessageQueue) {
    for i := 0; i < 3; i++ {
        message := <-queue.messages
        fmt.Println("Consumed:", message)
    }
}

func main() {
    queue := NewQueue()

    producer(queue)
    consumer(queue)
}

Demonstrates asynchronous communication using message queue concepts with producers, consumers, and distributed messaging systems.

Let’s Try →
57

Event Driven Architecture

package main

import "fmt"

type Event struct {
    Name string
    Data string
}

type EventBus struct {
    subscribers []func(Event)
}

func (b *EventBus) Subscribe(handler func(Event)) {
    b.subscribers = append(b.subscribers, handler)
}

func (b *EventBus) Publish(event Event) {
    for _, subscriber := range b.subscribers {
        subscriber(event)
    }
}

func main() {
    bus := EventBus{}

    bus.Subscribe(func(e Event) {
        fmt.Println("Consumer received:", e.Name)
    })

    event := Event{
        Name: "UserCreated",
        Data: "user_id=123",
    }

    fmt.Println("Producer published:", event.Name)
    bus.Publish(event)
}

Demonstrates event-driven architecture using producers, consumers, events, and an event bus for decoupled communication.

Let’s Try →
58

Distributed Transactions

package main

import "fmt"

type OrderService struct{}

type PaymentService struct{}

func createOrder() bool {
    fmt.Println("Order created")
    return true
}

func processPayment() bool {
    fmt.Println("Payment processed")
    return true
}

func compensateOrder() {
    fmt.Println("Order cancelled - compensation action")
}

func main() {
    transactionID := "txn-123"

    fmt.Println("Transaction:", transactionID)

    if createOrder() {
        if !processPayment() {
            compensateOrder()
        }
    }

    fmt.Println("Outbox event stored")
    fmt.Println("Operation completed safely")
}

Demonstrates distributed transaction patterns using Saga, Outbox Pattern, and idempotent operations for reliable microservices.

Let’s Try →
59

gRPC Advanced

package main

import "fmt"

type Metadata struct {
    RequestID string
    Token     string
}

func interceptor(next func(Metadata)) func(Metadata) {
    return func(md Metadata) {
        fmt.Println("Interceptor: validating request")
        next(md)
    }
}

func streamingHandler(md Metadata) {
    messages := []string{
        "Message 1",
        "Message 2",
        "Message 3",
    }

    fmt.Println("Request ID:", md.RequestID)

    for _, msg := range messages {
        fmt.Println("Stream:", msg)
    }
}

func main() {
    handler := interceptor(streamingHandler)

    handler(Metadata{
        RequestID: "req-123",
        Token: "jwt-token",
    })
}

Demonstrates advanced gRPC concepts including streaming, interceptors, and metadata handling for high-performance services.

Let’s Try →
60

WebSockets

package main

import (
    "fmt"
)

type Client struct {
    Name string
    Room string
}

type WebSocketServer struct {
    clients []Client
}

func (s *WebSocketServer) Broadcast(room string, message string) {
    for _, client := range s.clients {
        if client.Room == room {
            fmt.Println("Send to", client.Name, ":", message)
        }
    }
}

func main() {
    server := WebSocketServer{
        clients: []Client{
            {Name: "Alice", Room: "chat"},
            {Name: "Bob", Room: "chat"},
            {Name: "John", Room: "gaming"},
        },
    }

    fmt.Println("WebSocket server started")
    server.Broadcast("chat", "Hello everyone!")
}

Demonstrates real-time communication using WebSockets with connected clients, broadcasting messages, and room-based communication.

Let’s Try →
61

GraphQL

package main

import "fmt"

type User struct {
    ID   int
    Name string
}

var users = []User{
    {ID: 1, Name: "Alice"},
}

// Resolver for Query
func getUsers() []User {
    return users
}

// Resolver for Mutation
func createUser(name string) User {
    user := User{
        ID: len(users) + 1,
        Name: name,
    }

    users = append(users, user)
    return user
}

func main() {
    fmt.Println("Query Result:", getUsers())

    newUser := createUser("Bob")
    fmt.Println("Mutation Result:", newUser)
}

Demonstrates GraphQL concepts using queries, mutations, and resolvers for flexible API communication.

Let’s Try →
62

Elasticsearch

package main

import "fmt"

type Document struct {
    ID    int
    Title string
}

var index []Document

func indexDocument(doc Document) {
    index = append(index, doc)
}

func search(query string) []Document {
    results := []Document{}

    for _, doc := range index {
        if doc.Title == query {
            results = append(results, doc)
        }
    }

    return results
}

func main() {
    indexDocument(Document{ID: 1, Title: "Go Backend"})
    indexDocument(Document{ID: 2, Title: "Distributed Systems"})

    fmt.Println("Search Result:", search("Go Backend"))
    fmt.Println("Aggregation: Total Documents", len(index))
}

Demonstrates Elasticsearch concepts including indexing documents, full-text search, and aggregations for analytics.

Let’s Try →
63

Monitoring

package main

import (
    "fmt"
    "net/http"
)

var requests = 0

func metricsHandler(w http.ResponseWriter, r *http.Request) {
    fmt.Fprintf(w, "http_requests_total %d", requests)
}

func apiHandler(w http.ResponseWriter, r *http.Request) {
    requests++
    fmt.Fprintln(w, "API Response")
}

func main() {
    http.HandleFunc("/api", apiHandler)
    http.HandleFunc("/metrics", metricsHandler)

    fmt.Println("Monitoring server running on :8080")
    http.ListenAndServe(":8080", nil)
}

Demonstrates application monitoring concepts using metrics, Prometheus scraping, and exporters.

Let’s Try →
64

Visualization

package main

import "fmt"

type Metric struct {
    Name  string
    Value int
}

func main() {
    metrics := []Metric{
        {Name: "Requests", Value: 1200},
        {Name: "Errors", Value: 5},
        {Name: "Latency(ms)", Value: 80},
    }

    fmt.Println("Dashboard Metrics")

    for _, metric := range metrics {
        fmt.Println(metric.Name, ":", metric.Value)
    }

    if metrics[1].Value > 10 {
        fmt.Println("Alert: High error rate")
    } else {
        fmt.Println("System Healthy")
    }
}

Demonstrates backend visualization concepts using metrics dashboards, Grafana, and alerting systems.

Let’s Try →
65

Distributed Tracing

package main

import "fmt"

type Span struct {
    Service string
    Action  string
}

func createSpan(service string, action string) Span {
    return Span{
        Service: service,
        Action:  action,
    }
}

func main() {
    trace := []Span{
        createSpan("API Gateway", "Receive Request"),
        createSpan("User Service", "Fetch User"),
        createSpan("Database", "Query User"),
    }

    fmt.Println("Distributed Trace")

    for _, span := range trace {
        fmt.Println(span.Service, "-", span.Action)
    }

    fmt.Println("Trace exported to Jaeger")
}

Demonstrates distributed tracing concepts using OpenTelemetry, Jaeger, and Zipkin for tracking requests across services.

Let’s Try →
66

Health Checks

package main

import (
    "fmt"
    "net/http"
)

var started = true
var healthy = true

func readinessProbe(w http.ResponseWriter, r *http.Request) {
    if healthy {
        fmt.Fprintln(w, "READY")
        return
    }

    w.WriteHeader(http.StatusServiceUnavailable)
    fmt.Fprintln(w, "NOT READY")
}

func livenessProbe(w http.ResponseWriter, r *http.Request) {
    if healthy {
        fmt.Fprintln(w, "ALIVE")
        return
    }

    w.WriteHeader(http.StatusInternalServerError)
    fmt.Fprintln(w, "FAILED")
}

func startupProbe(w http.ResponseWriter, r *http.Request) {
    if started {
        fmt.Fprintln(w, "STARTED")
        return
    }

    w.WriteHeader(http.StatusServiceUnavailable)
    fmt.Fprintln(w, "STARTING")
}

func main() {
    http.HandleFunc("/health/readiness", readinessProbe)
    http.HandleFunc("/health/liveness", livenessProbe)
    http.HandleFunc("/health/startup", startupProbe)

    fmt.Println("Health check server running on :8080")
    http.ListenAndServe(":8080", nil)
}

Demonstrates Kubernetes-style health checks using readiness, liveness, and startup probes for reliable backend services.

Let’s Try →
67

API Documentation

package main

import "fmt"

type APIEndpoint struct {
    Method string
    Path   string
}

func generateDocs(api APIEndpoint) {
    fmt.Println("Generating API Documentation")
    fmt.Println(api.Method, api.Path)
}

func main() {
    endpoint := APIEndpoint{
        Method: "GET",
        Path:   "/users",
    }

    generateDocs(endpoint)

    fmt.Println("Swagger UI available")
    fmt.Println("Client SDK generated")
}

Demonstrates API documentation concepts using OpenAPI specifications, Swagger UI, and automated code generation.

Let’s Try →
68

Rate Limiting

package main

import (
    "fmt"
    "net/http"
    "time"
)

type RateLimiter struct {
    requests int
    limit    int
    reset    time.Time
}

func (r *RateLimiter) Allow() bool {
    if time.Now().After(r.reset) {
        r.requests = 0
        r.reset = time.Now().Add(time.Minute)
    }

    if r.requests >= r.limit {
        return false
    }

    r.requests++
    return true
}

var limiter = RateLimiter{
    limit: 3,
    reset: time.Now().Add(time.Minute),
}

func apiHandler(w http.ResponseWriter, req *http.Request) {
    if limiter.Allow() {
        fmt.Fprintln(w, "Request allowed")
        return
    }

    w.WriteHeader(http.StatusTooManyRequests)
    fmt.Fprintln(w, "Rate limit exceeded")
}

func main() {
    http.HandleFunc("/api", apiHandler)

    fmt.Println("Rate limiter running on :8080")
    http.ListenAndServe(":8080", nil)
}

Demonstrates API rate limiting concepts using token bucket, sliding window, and fixed window algorithms to control request traffic.

Let’s Try →
69

Security Hardening

package main

import (
    "fmt"
    "net/http"
)

func securityMiddleware(next http.Handler) http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        // Security Headers
        w.Header().Set("X-Content-Type-Options", "nosniff")
        w.Header().Set("X-Frame-Options", "DENY")
        w.Header().Set("Content-Security-Policy", "default-src 'self'")

        // CORS Example
        w.Header().Set("Access-Control-Allow-Origin", "https://example.com")

        next.ServeHTTP(w, r)
    })
}

func userHandler(w http.ResponseWriter, r *http.Request) {
    // SQL Injection Prevention:
    // Use prepared statements instead of string concatenation
    query := "SELECT * FROM users WHERE id = ?"

    fmt.Fprintln(w, "Safe Query:", query)
    fmt.Fprintln(w, "XSS protection enabled")
    fmt.Fprintln(w, "CSRF validation enabled")
}

func main() {
    handler := securityMiddleware(http.HandlerFunc(userHandler))

    http.Handle("/users", handler)

    fmt.Println("Secure API running on :8080")
    http.ListenAndServe(":8080", nil)
}

Demonstrates backend security hardening techniques including SQL injection prevention, XSS protection, CSRF handling, CORS configuration, and security headers.

Let’s Try →
70

Production API Project

package main

import (
    "fmt"
    "net/http"
)

func authMiddleware(next http.Handler) http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        fmt.Println("Auth: validating JWT token")
        next.ServeHTTP(w, r)
    })
}

func loggingMiddleware(next http.Handler) http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        fmt.Println("Log: request received", r.URL.Path)
        next.ServeHTTP(w, r)
    })
}

func healthHandler(w http.ResponseWriter, r *http.Request) {
    fmt.Fprintln(w, "API Healthy")
}

func userHandler(w http.ResponseWriter, r *http.Request) {
    fmt.Fprintln(w, "User API Response")
}

func main() {
    api := http.NewServeMux()

    api.HandleFunc("/health", healthHandler)
    api.HandleFunc("/users", userHandler)

    handler := loggingMiddleware(authMiddleware(api))

    fmt.Println("Production API running on :8080")
    http.ListenAndServe(":8080", handler)
}

Demonstrates a complete production-ready Go backend architecture combining authentication, logging, monitoring, testing, and deployment practices.

Let’s Try →
71

Docker Advanced

package main

import "fmt"

func main() {
    fmt.Println("Go application running inside optimized Docker image")
    fmt.Println("Build: Multi-stage Docker build")
    fmt.Println("Image: Minimal production container")
    fmt.Println("Security: Vulnerability scan completed")
}

Demonstrates advanced Docker concepts for Go applications including multi-stage builds, image optimization, and security scanning.

Let’s Try →
72

Docker Compose

package main

import "fmt"

type Service struct {
    Name string
}

func main() {
    services := []Service{
        {Name: "Go API"},
        {Name: "PostgreSQL Database"},
        {Name: "Redis Cache"},
    }

    fmt.Println("Docker Compose Environment")

    for _, service := range services {
        fmt.Println("Running:", service.Name)
    }

    fmt.Println("Network: app-network")
    fmt.Println("Volume: database-storage")
}

Demonstrates Docker Compose concepts for running multi-container applications with networking and persistent storage volumes.

Let’s Try →
73

Kubernetes Basics

package main

import "fmt"

type KubernetesResource struct {
    Kind string
    Name string
}

func main() {
    resources := []KubernetesResource{
        {Kind: "Pod", Name: "api-pod"},
        {Kind: "Deployment", Name: "api-deployment"},
        {Kind: "Service", Name: "api-service"},
        {Kind: "ConfigMap", Name: "app-config"},
        {Kind: "Secret", Name: "db-secret"},
    }

    fmt.Println("Kubernetes Cluster Resources")

    for _, resource := range resources {
        fmt.Println(resource.Kind, ":", resource.Name)
    }
}

Demonstrates Kubernetes core concepts including Pods, Deployments, Services, ConfigMaps, and Secrets for managing containerized applications.

Let’s Try →
74

Helm

package main

import "fmt"

type HelmChart struct {
    Name    string
    Version string
    Values  map[string]string
}

func installRelease(chart HelmChart) {
    fmt.Println("Installing Release:", chart.Name)
    fmt.Println("Chart Version:", chart.Version)

    for key, value := range chart.Values {
        fmt.Println(key, "=", value)
    }
}

func main() {
    chart := HelmChart{
        Name:    "backend-api",
        Version: "1.0.0",
        Values: map[string]string{
            "replicas": "3",
            "environment": "production",
        },
    }

    installRelease(chart)
}

Demonstrates Helm concepts including charts, releases, and values for managing Kubernetes application deployments.

Let’s Try →
75

AWS IAM

package main

import "fmt"

type IAMPolicy struct {
    Resource string
    Action   string
}

type User struct {
    Name   string
    Role   string
    Policy IAMPolicy
}

func checkAccess(user User, action string) bool {
    return user.Policy.Action == action
}

func main() {
    user := User{
        Name: "api-service-user",
        Role: "BackendRole",
        Policy: IAMPolicy{
            Resource: "Database",
            Action:   "Read",
        },
    }

    fmt.Println("IAM User:", user.Name)
    fmt.Println("IAM Role:", user.Role)

    if checkAccess(user, "Read") {
        fmt.Println("Access Granted")
    } else {
        fmt.Println("Access Denied")
    }
}

Demonstrates AWS IAM concepts including users, roles, policies, and least privilege access control for secure cloud applications.

Let’s Try →
76

AWS EC2

package main

import "fmt"

type EC2Instance struct {
    ID             string
    AMI            string
    SecurityGroup  string
    Status         string
}

func startInstance(instance EC2Instance) {
    fmt.Println("Starting EC2 Instance:", instance.ID)
    fmt.Println("AMI:", instance.AMI)
    fmt.Println("Security Group:", instance.SecurityGroup)
    fmt.Println("Status:", instance.Status)
}

func main() {
    instance := EC2Instance{
        ID:            "i-123456",
        AMI:           "ubuntu-server-image",
        SecurityGroup: "web-api-security-group",
        Status:        "Running",
    }

    startInstance(instance)
}

Demonstrates AWS EC2 concepts including virtual machines, security groups, and AMIs for deploying backend applications.

Let’s Try →
77

AWS S3

package main

import "fmt"

type S3Object struct {
    Name string
    Size string
    StorageClass string
}

type BucketPolicy struct {
    Action string
    Access string
}

func uploadObject(object S3Object) {
    fmt.Println("Uploaded Object:", object.Name)
    fmt.Println("Size:", object.Size)
    fmt.Println("Storage Class:", object.StorageClass)
}

func main() {
    object := S3Object{
        Name: "profile-image.png",
        Size: "2MB",
        StorageClass: "STANDARD",
    }

    policy := BucketPolicy{
        Action: "Read",
        Access: "Private",
    }

    uploadObject(object)

    fmt.Println("Bucket Policy:", policy.Access)
    fmt.Println("Lifecycle Rule: Move old files to Glacier")
}

Demonstrates AWS S3 concepts including object storage, bucket policies, and lifecycle rules for managing application files.

Let’s Try →
78

AWS RDS

package main

import "fmt"

type Database struct {
    Engine       string
    Instance     string
    ReadReplica  bool
    Backup       bool
}

func connectDatabase(db Database) {
    fmt.Println("Database Engine:", db.Engine)
    fmt.Println("Instance:", db.Instance)
    fmt.Println("Read Replica Enabled:", db.ReadReplica)
    fmt.Println("Automated Backup:", db.Backup)
}

func main() {
    db := Database{
        Engine:      "PostgreSQL",
        Instance:    "production-db",
        ReadReplica: true,
        Backup:      true,
    }

    connectDatabase(db)
}

Demonstrates AWS RDS concepts including managed PostgreSQL/MySQL databases, read replicas, and automated backups for backend applications.

Let’s Try →
79

AWS DynamoDB

package main

import "fmt"

type User struct {
    ID       string
    Email    string
    Username string
}

type DynamoTable struct {
    Name string
    GSI  string
}

func saveItem(table DynamoTable, user User) {
    fmt.Println("Table:", table.Name)
    fmt.Println("Stored User:", user.ID, user.Username)
    fmt.Println("Using GSI:", table.GSI)
}

func main() {
    table := DynamoTable{
        Name: "UsersTable",
        GSI:  "EmailIndex",
    }

    user := User{
        ID:       "user-101",
        Email:    "user@example.com",
        Username: "alice",
    }

    saveItem(table, user)
}

Demonstrates AWS DynamoDB concepts including NoSQL data storage, partitions, and Global Secondary Indexes (GSIs) for scalable applications.

Let’s Try →
80

AWS Lambda

package main

import "fmt"

type Event struct {
    Source string
    Data   string
}

func lambdaHandler(event Event) {
    fmt.Println("Lambda Function Executed")
    fmt.Println("Trigger:", event.Source)
    fmt.Println("Event Data:", event.Data)
}

func main() {
    fmt.Println("Cold Start: Initializing runtime")

    event := Event{
        Source: "API Gateway",
        Data:   "GET /users",
    }

    lambdaHandler(event)

    fmt.Println("Execution completed")
}

Demonstrates AWS Lambda concepts including serverless functions, event triggers, and cold start behavior in cloud applications.

Let’s Try →
81

API Gateway

package main

import (
    "fmt"
    "net/http"
)

func authMiddleware(next http.Handler) http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        token := r.Header.Get("Authorization")

        if token == "" {
            w.WriteHeader(http.StatusUnauthorized)
            fmt.Fprintln(w, "Authentication required")
            return
        }

        next.ServeHTTP(w, r)
    })
}

func apiHandler(w http.ResponseWriter, r *http.Request) {
    fmt.Fprintln(w, "REST API Response")
}

func main() {
    api := http.HandlerFunc(apiHandler)

    handler := authMiddleware(api)

    http.Handle("/users", handler)

    fmt.Println("API Gateway running on :8080")
    fmt.Println("Rate Limit: 100 requests/minute")

    http.ListenAndServe(":8080", nil)
}

Demonstrates API Gateway concepts including REST APIs, authentication, and rate limiting for managing backend API traffic.

Let’s Try →
82

AWS ECS

package main

import "fmt"

type TaskDefinition struct {
    Name      string
    Image     string
    CPU       string
    Memory    string
}

type ECSService struct {
    Name  string
    Tasks int
}

func deployService(service ECSService, task TaskDefinition) {
    fmt.Println("Deploying ECS Service:", service.Name)
    fmt.Println("Running Tasks:", service.Tasks)
    fmt.Println("Container Image:", task.Image)
    fmt.Println("CPU:", task.CPU)
    fmt.Println("Memory:", task.Memory)
}

func main() {
    task := TaskDefinition{
        Name:   "backend-task",
        Image:  "my-go-api:v1",
        CPU:    "512 units",
        Memory: "1GB",
    }

    service := ECSService{
        Name:  "api-service",
        Tasks: 3,
    }

    deployService(service, task)
}

Demonstrates AWS ECS concepts including container deployment, services, and task definitions for running scalable backend applications.

Let’s Try →
83

AWS EKS

package main

import "fmt"

type EKSCluster struct {
    Name       string
    Kubernetes string
    NodeGroups int
}

func deployCluster(cluster EKSCluster) {
    fmt.Println("EKS Cluster:", cluster.Name)
    fmt.Println("Kubernetes Version:", cluster.Kubernetes)
    fmt.Println("Node Groups:", cluster.NodeGroups)
}

func main() {
    cluster := EKSCluster{
        Name:       "production-cluster",
        Kubernetes: "1.30",
        NodeGroups: 3,
    }

    deployCluster(cluster)
}

Demonstrates AWS EKS concepts including managed Kubernetes clusters and node groups for running containerized applications.

Let’s Try →
84

AWS CloudWatch

package main

import "fmt"

type Metric struct {
    Name  string
    Value int
}

type Alarm struct {
    Metric    string
    Threshold int
}

func sendLog(message string) {
    fmt.Println("LOG:", message)
}

func checkAlarm(metric Metric, alarm Alarm) {
    if metric.Value > alarm.Threshold {
        fmt.Println("ALARM:", metric.Name, "threshold exceeded")
    } else {
        fmt.Println("Metric healthy:", metric.Name)
    }
}

func main() {
    metric := Metric{
        Name:  "CPU Usage",
        Value: 85,
    }

    alarm := Alarm{
        Metric:    "CPU Usage",
        Threshold: 80,
    }

    sendLog("API server started")
    checkAlarm(metric, alarm)
}

Demonstrates AWS CloudWatch concepts including logs, metrics, and alarms for monitoring backend applications and cloud resources.

Let’s Try →
85

AWS SNS

package main

import "fmt"

type Subscriber struct {
    Name string
    Type string
}

func publishMessage(topic string, message string, subscribers []Subscriber) {
    fmt.Println("SNS Topic:", topic)
    fmt.Println("Message:", message)

    for _, subscriber := range subscribers {
        fmt.Println("Delivered to:", subscriber.Name, "(", subscriber.Type, ")")
    }
}

func main() {
    subscribers := []Subscriber{
        {Name: "Email Service", Type: "Email"},
        {Name: "SMS Service", Type: "SMS"},
        {Name: "Order Service", Type: "HTTP"},
    }

    publishMessage(
        "order-events",
        "New order created",
        subscribers,
    )
}

Demonstrates AWS SNS concepts including notification publishing and fan-out messaging patterns for distributed applications.

Let’s Try →
86

AWS SQS

package main

import "fmt"

type Message struct {
    ID      string
    Content string
    Retries int
}

func processMessage(message Message) {
    fmt.Println("Processing Message:", message.ID)
    fmt.Println("Content:", message.Content)

    if message.Retries > 3 {
        fmt.Println("Moved to Dead Letter Queue")
        return
    }

    fmt.Println("Message processed successfully")
}

func main() {
    message := Message{
        ID:      "msg-101",
        Content: "Process payment",
        Retries: 1,
    }

    processMessage(message)
}

Demonstrates AWS SQS concepts including message queues and dead letter queues for reliable asynchronous backend processing.

Let’s Try →
87

AWS EventBridge

package main

import (
    "fmt"
    "time"
)

type Event struct {
    Source string
    Type   string
    Data   string
}

func routeEvent(event Event) {
    fmt.Println("Event Received")
    fmt.Println("Source:", event.Source)
    fmt.Println("Type:", event.Type)
    fmt.Println("Data:", event.Data)

    if event.Type == "ORDER_CREATED" {
        fmt.Println("Routing to Order Service")
    }
}

func scheduledEvent() {
    fmt.Println("Scheduled Event Triggered:", time.Now())
    fmt.Println("Running Daily Cleanup Job")
}

func main() {
    event := Event{
        Source: "Order Service",
        Type:   "ORDER_CREATED",
        Data:   "Order #1001",
    }

    routeEvent(event)
    scheduledEvent()
}

Demonstrates AWS EventBridge concepts including event routing and scheduled events for building event-driven backend systems.

Let’s Try →
88

AWS Secrets Manager

package main

import "fmt"

type Secret struct {
    Name     string
    Value    string
    Rotated  bool
}

func getSecret(secret Secret) {
    fmt.Println("Secret Name:", secret.Name)
    fmt.Println("Secure Storage: Enabled")

    if secret.Rotated {
        fmt.Println("Secret Rotation: Completed")
    }
}

func main() {
    databaseSecret := Secret{
        Name:    "production-db-password",
        Value:   "********",
        Rotated: true,
    }

    getSecret(databaseSecret)
}

Demonstrates AWS Secrets Manager concepts including secure secret storage and automatic secret rotation for protecting sensitive application credentials.

Let’s Try →
89

AWS Parameter Store

package main

import "fmt"

type Parameter struct {
    Name  string
    Value string
    Type  string
}

func loadConfiguration(parameter Parameter) {
    fmt.Println("Parameter:", parameter.Name)
    fmt.Println("Value:", parameter.Value)
    fmt.Println("Type:", parameter.Type)
}

func main() {
    config := Parameter{
        Name:  "/production/api/url",
        Value: "https://api.example.com",
        Type:  "String",
    }

    loadConfiguration(config)
}

Demonstrates AWS Parameter Store concepts including centralized configuration management for backend applications.

Let’s Try →
90

AWS CloudFront

package main

import "fmt"

type EdgeLocation struct {
    Region string
    Cache  bool
}

func serveContent(edge EdgeLocation, content string) {
    fmt.Println("Request received at:", edge.Region)

    if edge.Cache {
        fmt.Println("Serving from Edge Cache")
    } else {
        fmt.Println("Fetching from Origin Server")
    }

    fmt.Println("Content:", content)
}

func main() {
    edge := EdgeLocation{
        Region: "Asia Pacific Edge",
        Cache:  true,
    }

    serveContent(edge, "backend-api-response")
}

Demonstrates AWS CloudFront concepts including CDN distribution and edge caching for improving application performance.

Let’s Try →
91

AWS Route53

package main

import "fmt"

type DNSRecord struct {
    Domain string
    Target string
    Policy string
}

func resolveDNS(record DNSRecord) {
    fmt.Println("Domain:", record.Domain)
    fmt.Println("Routing To:", record.Target)
    fmt.Println("Routing Policy:", record.Policy)
}

func main() {
    record := DNSRecord{
        Domain: "api.example.com",
        Target: "load-balancer.amazonaws.com",
        Policy: "Weighted Routing",
    }

    resolveDNS(record)
}

Demonstrates AWS Route53 concepts including DNS management and routing policies for directing user traffic to backend services.

Let’s Try →
92

AWS Load Balancer

package main

import "fmt"

type LoadBalancer struct {
    Name string
    Type string
    Target string
}

func routeTraffic(lb LoadBalancer, request string) {
    fmt.Println("Load Balancer:", lb.Name)
    fmt.Println("Type:", lb.Type)
    fmt.Println("Request:", request)
    fmt.Println("Forwarding To:", lb.Target)
}

func main() {
    alb := LoadBalancer{
        Name:   "api-alb",
        Type:   "Application Load Balancer",
        Target: "Backend Services",
    }

    nlb := LoadBalancer{
        Name:   "tcp-nlb",
        Type:   "Network Load Balancer",
        Target: "High Performance Services",
    }

    routeTraffic(alb, "HTTP GET /users")
    routeTraffic(nlb, "TCP Connection")
}

Demonstrates AWS Load Balancer concepts including Application Load Balancer (ALB) and Network Load Balancer (NLB) for distributing backend traffic.

Let’s Try →
93

Auto Scaling

package main

import "fmt"

type Instance struct {
    ID      string
    Healthy bool
}

type ScalingPolicy struct {
    Metric     string
    Threshold  int
}

func checkHealth(instance Instance) bool {
    return instance.Healthy
}

func applyScaling(policy ScalingPolicy, load int) {
    fmt.Println("Scaling Metric:", policy.Metric)
    fmt.Println("Current Load:", load)

    if load > policy.Threshold {
        fmt.Println("Action: Add New Instances")
    } else {
        fmt.Println("Action: Maintain Current Capacity")
    }
}

func main() {
    instance := Instance{
        ID:      "server-01",
        Healthy: true,
    }

    policy := ScalingPolicy{
        Metric:    "CPU Usage",
        Threshold: 70,
    }

    fmt.Println("Instance Healthy:", checkHealth(instance))

    applyScaling(policy, 85)
}

Demonstrates Auto Scaling concepts including scaling policies and health checks for maintaining scalable and highly available backend systems.

Let’s Try →
94

Terraform

package main

import "fmt"

type TerraformResource struct {
    Name string
    Type string
}

type TerraformState struct {
    Resources int
}

type Module struct {
    Name string
}

func applyInfrastructure(resource TerraformResource, state TerraformState, module Module) {
    fmt.Println("Creating Resource:", resource.Name)
    fmt.Println("Resource Type:", resource.Type)
    fmt.Println("State Tracking Resources:", state.Resources)
    fmt.Println("Using Module:", module.Name)
}

func main() {
    resource := TerraformResource{
        Name: "production-server",
        Type: "AWS EC2",
    }

    state := TerraformState{
        Resources: 5,
    }

    module := Module{
        Name: "network-module",
    }

    applyInfrastructure(resource, state, module)
}

Demonstrates Terraform concepts including Infrastructure as Code, state management, and reusable modules for automating cloud infrastructure.

Let’s Try →
95

CI/CD

package main

import "fmt"

type Pipeline struct {
    Tool   string
    Stages []string
}

func runPipeline(pipeline Pipeline) {
    fmt.Println("CI/CD Tool:", pipeline.Tool)

    for _, stage := range pipeline.Stages {
        fmt.Println("Running Stage:", stage)
    }
}

func main() {
    pipeline := Pipeline{
        Tool: "GitHub Actions",
        Stages: []string{
            "Code Checkout",
            "Build Application",
            "Run Tests",
            "Create Docker Image",
            "Deploy to Kubernetes",
        },
    }

    runPipeline(pipeline)
}

Demonstrates CI/CD concepts including automated builds, testing, deployment pipelines, and tools such as GitHub Actions, GitLab CI, Jenkins, and ArgoCD.

Let’s Try →
96

Distributed Systems Fundamentals

package main

import "fmt"

type Node struct {
    Name string
    Data string
}

func replicateData(nodes []Node, data string) {
    fmt.Println("Replicating Data:", data)

    for _, node := range nodes {
        fmt.Println("Stored in Node:", node.Name)
    }
}

func main() {
    nodes := []Node{
        {Name: "Node-A"},
        {Name: "Node-B"},
        {Name: "Node-C"},
    }

    replicateData(nodes, "User Profile Data")

    fmt.Println("Consistency Model: Eventual Consistency")
    fmt.Println("Partition Strategy: Hash Based Partitioning")
}

Demonstrates distributed systems concepts including CAP Theorem, consistency models, replication, and partitioning for scalable backend architectures.

Let’s Try →
97

System Design

package main

import "fmt"

type System struct {
    Name          string
    Instances     int
    BackupEnabled bool
    HealthChecks  bool
}

func evaluateSystem(system System) {
    fmt.Println("System:", system.Name)
    fmt.Println("Instances:", system.Instances)
    fmt.Println("Backup Enabled:", system.BackupEnabled)
    fmt.Println("Health Checks:", system.HealthChecks)
}

func main() {
    system := System{
        Name:          "Production API Platform",
        Instances:     5,
        BackupEnabled: true,
        HealthChecks:  true,
    }

    evaluateSystem(system)
}

Demonstrates system design concepts including scalability, availability, reliability, and fault tolerance for building production-grade backend systems.

Let’s Try →
98

High Availability

package main

import "fmt"

type AvailabilityZone struct {
    Name   string
    Active bool
}

type LoadBalancer struct {
    HealthyServers int
}

func routeTraffic(lb LoadBalancer) {
    fmt.Println("Healthy Servers:", lb.HealthyServers)
    fmt.Println("Traffic routed successfully")
}

func failover(zone AvailabilityZone) {
    if !zone.Active {
        fmt.Println("Failover triggered from:", zone.Name)
        fmt.Println("Switching to standby zone")
    }
}

func main() {
    primary := AvailabilityZone{
        Name:   "us-east-1a",
        Active: false,
    }

    backup := AvailabilityZone{
        Name:   "us-east-1b",
        Active: true,
    }

    lb := LoadBalancer{
        HealthyServers: 3,
    }

    failover(primary)
    fmt.Println("Active Zone:", backup.Name)
    routeTraffic(lb)
}

Demonstrates high availability concepts including Multi-AZ deployment, automatic failover, and load balancing for resilient backend systems.

Let’s Try →
99

Performance Optimization

package main

import (
    "fmt"
    "time"
)

func expensiveOperation() int {
    total := 0

    for i := 0; i < 1000000; i++ {
        total += i
    }

    return total
}

func benchmark() {
    start := time.Now()

    result := expensiveOperation()

    duration := time.Since(start)

    fmt.Println("Result:", result)
    fmt.Println("Execution Time:", duration)
}

func main() {
    fmt.Println("CPU Profiling: Tracking processor usage")
    fmt.Println("Memory Profiling: Tracking allocations")

    benchmark()
}

Demonstrates performance optimization concepts including CPU profiling, memory profiling, and benchmarking for improving backend application efficiency.

Let’s Try →
100

Database Scaling

package main

import "fmt"

type DatabaseNode struct {
    Name string
    Role string
}

func executeQuery(node DatabaseNode, queryType string) {
    fmt.Println("Database Node:", node.Name)
    fmt.Println("Role:", node.Role)
    fmt.Println("Query Type:", queryType)
}

func main() {
    primary := DatabaseNode{
        Name: "Primary DB",
        Role: "Write Server",
    }

    replica := DatabaseNode{
        Name: "Read Replica",
        Role: "Read Server",
    }

    shard := DatabaseNode{
        Name: "Shard-01",
        Role: "Partitioned Data",
    }

    executeQuery(primary, "INSERT User")
    executeQuery(replica, "SELECT Users")
    executeQuery(shard, "User Data Partition")
}

Demonstrates database scaling concepts including sharding, replication, and read/write splitting for high-performance backend systems.

Let’s Try →
101

Go Distributed Cache with Redis Cluster

package main

import (
    "context"
    "fmt"

    "github.com/redis/go-redis/v9"
)

var ctx = context.Background()

func main() {
    cluster := redis.NewClusterClient(&redis.ClusterOptions{
        Addrs: []string{
            "localhost:7000",
            "localhost:7001",
            "localhost:7002",
        },
    })

    userID := "42"
    cacheKey := "user:" + userID

    cluster.Set(ctx, cacheKey, "Alice", 0)

    name, _ := cluster.Get(ctx, cacheKey).Result()
    fmt.Println("Cache Hit:", name)

    fmt.Println("Updating user record...")

    cluster.Del(ctx, cacheKey)
    fmt.Println("Cache Invalidated:", cacheKey)

    _, err := cluster.Get(ctx, cacheKey).Result()
    if err == redis.Nil {
        fmt.Println("Cache Miss")
    }
}

Demonstrates distributed caching using a Redis Cluster with cache invalidation after updating data.

Let’s Try →
102

Go Service Mesh with Istio and mTLS

package main

import (
    "fmt"
    "net/http"
)

func main() {
    http.HandleFunc("/hello", func(w http.ResponseWriter, r *http.Request) {
        fmt.Fprintln(w, "Hello from Service A")
    })

    fmt.Println("Service A listening on :8080")
    http.ListenAndServe(":8080", nil)
}

// In a Kubernetes cluster, Istio or Linkerd sidecars automatically
// intercept traffic between services and enforce mTLS.
// Example request from Service B:
// resp, _ := http.Get("http://service-a/hello")

Demonstrates two Go microservices communicating securely through an Istio service mesh with mutual TLS (mTLS) enabled.

Let’s Try →
103

Go Resilience Patterns

package main

import (
    "context"
    "fmt"
    "time"
)

func callService(ctx context.Context) error {
    select {
    case <-time.After(500 * time.Millisecond):
        return fmt.Errorf("service unavailable")
    case <-ctx.Done():
        return ctx.Err()
    }
}

func main() {
    ctx, cancel := context.WithTimeout(context.Background(), 300*time.Millisecond)
    defer cancel()

    for retry := 1; retry <= 3; retry++ {
        err := callService(ctx)
        if err == nil {
            fmt.Println("Request succeeded")
            return
        }

        fmt.Printf("Retry %d failed: %v\n", retry, err)
    }

    fmt.Println("Circuit Breaker Open")
    fmt.Println("Requests redirected to fallback")
}

Demonstrates common resilience patterns including Circuit Breaker, Retry, Bulkhead isolation, and Timeout handling when calling an external service.

Let’s Try →
104

Go Event Sourcing with Immutable Events

package main

import "fmt"

type Event struct {
    Type   string
    Amount int
}

func main() {
    eventStore := []Event{}

    eventStore = append(eventStore, Event{Type: "AccountCreated", Amount: 100})
    eventStore = append(eventStore, Event{Type: "MoneyDeposited", Amount: 50})
    eventStore = append(eventStore, Event{Type: "MoneyWithdrawn", Amount: 30})

    balance := 0
    for _, event := range eventStore {
        switch event.Type {
        case "AccountCreated":
            balance = event.Amount
        case "MoneyDeposited":
            balance += event.Amount
        case "MoneyWithdrawn":
            balance -= event.Amount
        }
    }

    fmt.Println("Current Balance:", balance)
}

Demonstrates Event Sourcing by storing immutable events in an event store and rebuilding application state from the event history.

Let’s Try →
105

Go CQRS with Command and Query Models

package main

import "fmt"

type CommandModel struct {
    Balance int
}

type QueryModel struct {
    CurrentBalance int
}

func main() {
    command := CommandModel{}
    query := QueryModel{}

    // Command: update state
    command.Balance += 100
    command.Balance += 50

    // Synchronize read model
    query.CurrentBalance = command.Balance

    // Query: read optimized view
    fmt.Println("Balance:", query.CurrentBalance)
}

Demonstrates Command Query Responsibility Segregation (CQRS) by separating write operations (commands) from read operations (queries).

Let’s Try →
106

Go Distributed Locks with Redis and Leader Election

package main

import (
    "context"
    "fmt"
    "time"

    "github.com/redis/go-redis/v9"
)

var ctx = context.Background()

func main() {
    client := redis.NewClient(&redis.Options{
        Addr: "localhost:6379",
    })

    acquired, err := client.SetNX(
        ctx,
        "leader-lock",
        "instance-1",
        10*time.Second,
    ).Result()

    if err != nil {
        panic(err)
    }

    if acquired {
        fmt.Println("Leader elected: instance-1")
        fmt.Println("Executing scheduled job...")
    } else {
        fmt.Println("Follower node")
    }
}

Demonstrates distributed locking using Redis to ensure only one instance becomes the leader and performs a critical task.

Let’s Try →
107

Go Consensus Algorithms with Raft

package main

import "fmt"

type Node struct {
    ID string
}

func main() {
    leader := Node{ID: "Node-1"}
    followers := []Node{
        {ID: "Node-2"},
        {ID: "Node-3"},
    }

    fmt.Println("Leader elected:", leader.ID)

    for _, follower := range followers {
        fmt.Printf("Replicating log entry to %s\n", follower.ID)
    }

    fmt.Println("Majority acknowledged")
    fmt.Println("Entry committed")
}

Demonstrates the core idea of Raft consensus where a leader replicates log entries to followers. Paxos is a related consensus algorithm with similar goals but greater conceptual complexity.

Let’s Try →
108

Go API Gateway Architecture

package main

import (
    "fmt"
    "net/http"
)

func gateway(w http.ResponseWriter, r *http.Request) {
    apiKey := r.Header.Get("X-API-Key")
    if apiKey != "secret-key" {
        http.Error(w, "Unauthorized", http.StatusUnauthorized)
        return
    }

    // Simulated rate limit check
    fmt.Println("Rate limit passed")

    // Simulated aggregation
    user := "User Profile"
    orders := "Recent Orders"

    fmt.Fprintf(w, "%s | %s", user, orders)
}

func main() {
    http.HandleFunc("/dashboard", gateway)
    fmt.Println("API Gateway listening on :8080")
    http.ListenAndServe(":8080", nil)
}

Demonstrates an API Gateway that performs authentication, rate limiting, and request aggregation before forwarding responses to clients.

Let’s Try →
109

Go Secure Software Design

package main

import (
    "fmt"
    "net/http"
    "regexp"
)

func loginHandler(w http.ResponseWriter, r *http.Request) {
    username := r.FormValue("username")

    valid := regexp.MustCompile(`^[a-zA-Z0-9_]{3,20}$`)
    if !valid.MatchString(username) {
        http.Error(w, "Invalid input", http.StatusBadRequest)
        return
    }

    fmt.Fprintf(w, "Welcome %s", username)
}

func main() {
    http.HandleFunc("/login", loginHandler)
    fmt.Println("Secure application listening on :8080")
    http.ListenAndServe(":8080", nil)
}

Demonstrates secure software design principles by validating input, applying threat modeling concepts, and following Secure SDLC practices aligned with OWASP recommendations.

Let’s Try →
110

Technical Leadership Practices

package main

import "fmt"

type ADR struct {
    Title    string
    Decision string
}

func main() {
    adr := ADR{
        Title:    "Adopt Event-Driven Architecture",
        Decision: "Approved",
    }

    fmt.Println("ADR:", adr.Title)
    fmt.Println("Status:", adr.Decision)

    fmt.Println("RFC reviewed by Platform and Payments teams")
    fmt.Println("Code review completed")
    fmt.Println("Mentoring session conducted")
    fmt.Println("Roadmap updated")
}

Demonstrates how technical leaders guide engineering teams through ADRs, RFCs, code reviews, mentoring, technical roadmaps, and cross-team design reviews.

Let’s Try →
111

Go Counter with Goroutines

package main

import (
    "fmt"
    "sync"
)

func main() {
    var count int
    var mu sync.Mutex
    var wg sync.WaitGroup

    for i := 0; i < 5; i++ {
        wg.Add(1)
        go func() {
        defer wg.Done()
        mu.Lock()
        count++
        fmt.Println("Count:", count)
        mu.Unlock()
        }()
    }

    wg.Wait()
}

Demonstrates a simple counter updated concurrently with goroutines.

Let’s Try →
112

Go Theme Toggle

package main

import (
    "fmt"
    "sync"
)

func main() {
    var isDark bool
    var mu sync.Mutex
    var wg sync.WaitGroup

    toggle := func() {
        mu.Lock()
        isDark = !isDark
        fmt.Println("Theme:", map[bool]string{true: "Dark", false: "Light"}[isDark])
        mu.Unlock()
    }

    for i := 0; i < 3; i++ {
        wg.Add(1)
        go func() { defer wg.Done(); toggle() }()
    }

    wg.Wait()
}

Toggles a dark/light theme flag concurrently.

Let’s Try →
113

Go Score Tracker

package main

import (
    "fmt"
    "sync"
)

func main() {
    score := 0
    var mu sync.Mutex
    var wg sync.WaitGroup

    increment := func() {
        mu.Lock()
        score += 10
        fmt.Println("Score:", score)
        mu.Unlock()
    }
    decrement := func() {
        mu.Lock()
        score -= 5
        fmt.Println("Score:", score)
        mu.Unlock()
    }

    wg.Add(2)
    go func() { defer wg.Done(); increment() }()
    go func() { defer wg.Done(); decrement() }()

    wg.Wait()
}

Tracks a score with concurrent increment and decrement.

Let’s Try →
114

Go Simple Timer

package main

import (
    "fmt"
    "time"
)

func main() {
    ticker := time.NewTicker(time.Second)
    defer ticker.Stop()

    count := 0
    for count < 3 {
        <-ticker.C
        count++
        fmt.Println("Time:", count, "sec")
    }
}

Counts seconds using goroutines and channels.

Let’s Try →
115

Go Health Tracker

package main

import (
    "fmt"
    "sync"
)

func main() {
    health := 100
    var mu sync.Mutex
    var wg sync.WaitGroup

damage := func() {
    mu.Lock()
    health -= 20
    fmt.Println("Health:", health)
    mu.Unlock()
}

heal := func() {
    mu.Lock()
    health += 10
    fmt.Println("Health:", health)
    mu.Unlock()
}

wg.Add(2)
go func() { defer wg.Done(); damage() }()
go func() { defer wg.Done(); heal() }()

wg.Wait()
}

Tracks health with concurrent damage and healing operations.

Let’s Try →
116

Go Level Tracker

package main

import (
    "fmt"
    "sync"
)

func main() {
    level := 1
    var mu sync.Mutex
    var wg sync.WaitGroup

    nextLevel := func() {
        mu.Lock()
        level++
        fmt.Println("Level:", level)
        mu.Unlock()
    }

    wg.Add(2)
    go func() { defer wg.Done(); nextLevel() }()
    go func() { defer wg.Done(); nextLevel() }()

    wg.Wait()
}

Tracks game levels using goroutines safely.

Let’s Try →
117

Go Coin Counter

package main

import (
    "fmt"
    "sync"
)

func main() {
    coins := 0
    var mu sync.Mutex
    var wg sync.WaitGroup

    collectCoin := func() { mu.Lock(); coins++; fmt.Println("Coins:", coins); mu.Unlock() }
    loseCoin := func() { mu.Lock(); coins--; fmt.Println("Coins:", coins); mu.Unlock() }

    wg.Add(2)
    go func() { defer wg.Done(); collectCoin() }()
    go func() { defer wg.Done(); loseCoin() }()

    wg.Wait()
}

Counts coins collected and lost concurrently.

Let’s Try →
118

Go Ammo Tracker

package main

import (
    "fmt"
    "sync"
)

func main() {
    ammo := 10
    var mu sync.Mutex
    var wg sync.WaitGroup

shoot := func() { mu.Lock(); ammo--; fmt.Println("Ammo:", ammo); mu.Unlock() }
    reload := func() { mu.Lock(); ammo = 10; fmt.Println("Ammo reloaded:", ammo); mu.Unlock() }

    wg.Add(2)
    go func() { defer wg.Done(); shoot() }()
    go func() { defer wg.Done(); reload() }()

    wg.Wait()
}

Tracks ammo usage with shoot and reload actions using goroutines.

Let’s Try →
119

Go Star Collector

package main

import (
    "fmt"
    "sync"
)

func main() {
    stars := 0
    var mu sync.Mutex
    var wg sync.WaitGroup

    collectStar := func() { mu.Lock(); stars++; fmt.Println("Stars:", stars); mu.Unlock() }
    loseStar := func() { mu.Lock(); stars--; fmt.Println("Stars:", stars); mu.Unlock() }

    wg.Add(2)
    go func() { defer wg.Done(); collectStar() }()
    go func() { defer wg.Done(); loseStar() }()

    wg.Wait()
}

Counts collected stars using concurrent operations.

Let’s Try →

Frequently Asked Questions about Go

What is Go?

Go (Golang) is a statically typed, compiled programming language designed at Google. It emphasizes simplicity, concurrency, and high-performance networking and system programming, making it ideal for cloud services, web backends, and distributed systems.

What are the primary use cases for Go?

Backend web services and APIs. Cloud-native and distributed systems. Command-line utilities. Network programming and microservices. DevOps and infrastructure tooling

What are the strengths of Go?

High performance due to compilation. Concurrency primitives built-in and easy to use. Strong standard library for common tasks. Cross-platform compilation. Easy deployment as a single statically linked binary

What are the limitations of Go?

No generics before Go 1.18 (now available but limited). Minimalist standard library for GUI or graphics. Error handling requires explicit checks. Limited metaprogramming or macros. Lacks some modern language features like operator overloading

How can I practice Go typing speed?

CodeSpeedTest offers 119+ real Go code examples for typing practice. You can measure your WPM, track accuracy, and improve your coding speed with guided exercises.

Learn Other Programming Languages

CReactPythonC++RustTypeScriptKotlinPHPJavaC#RubyMqlCqlN1qlCypherGremlinPartiqlHaskellElixirFsharpView all languages →
CodeSpeedTest

Improve your coding speed, code accuracy, and programming syntax WPM with practice sessions across 500+ programming languages.

Quick Links

HomeAboutFeaturesGetting StartedLanguages

Legal & Support

Pro ⚡ PricingContactPrivacy PolicyTerms of Service

Connect

CodeSpeedTest on GitHubCodeSpeedTest on TwitterEmail CodeSpeedTest

© 2026 CodeSpeedTest. All rights reserved.