//Original Go Code Library

HandcraftedGo Code Snippets

Meticulously crafted, production-ready Go code snippets created from scratch. Each example is carefully designed, thoroughly tested, and professionally documented to help developers build robust applications with Go.

main.go
package main

import "fmt"

func main() {
    fmt.Println("Hello, Go!")
}
~/snippets/filter
</>CATEGORY
[#]DIFFICULTY
Concurrencyintermediate
Go 1.13++

Concurrent Task Execution with WaitGroup

Runs several independent tasks concurrently and waits for them while collecting any failures into a single report.

}
"keyword">func main() {
	// Create a list of tasks
	tasks := []Task{
		{ID: 1, DelayMs: 100},
goroutineswaitgroupconcurrency +2
File Iointermediate
Go 1.16++

Comprehensive File I/O Operations

Wraps common file operations so writes are crash-safe, reads verify state, and temporary files are cleaned up automatica...

		"keyword">return fmt.Errorf("failed to write to temp file: %w", err)
	}
	// Sync to disk to ensure data is written
	"keyword">if err := tempFile.Sync(); err != nil {
		"keyword">return fmt.Errorf("failed to sync temp file: %w", err)
file ioatomic writedefer +3
Webadvanced
Go 1.18++

REST API Server with Middleware

Implements a small user API with middleware, structured routing, and guarded state access.

		"keyword">return false
	}
	delete(us.users, id)
	"keyword">return true
}
rest apihttp servermiddleware +4
Data Structuresintermediate
Go 1.16++

Advanced JSON Handling

Shows how to precisely shape JSON payloads for a user model while keeping Go types safe.

		Alias: (*Alias)(u),
	}
	"keyword">if err := json.Unmarshal(data, &aux); err != nil {
		"keyword">return fmt.Errorf("failed to unmarshal user: %w", err)
	}
jsonmarshalingunmarshaling +3
Error Handlingintermediate
Go 1.13++

Modern Error Handling with Wrapping

Models validation, database, and filesystem failures as rich errors and shows how to unwrap or classify them safely.

		}
	}
	"keyword">if len(username) < 3 {
		"keyword">return &ValidationError{
			Field:   "username",
error wrappingerrors.Iserrors.As +2
Cryptoadvanced
Go 1.18++

Cryptographic Hashing and AES Encryption

Combines authentication-safe hashing with symmetric encryption so credentials and payloads are protected end to end.

	combined := append(data, saltBytes...)
	// Compute hash
	hashBytes := sha256.Sum256(combined)
	computedHash := base64.StdEncoding.EncodeToString(hashBytes[:])
	// Compare hashes (constant time comparison would be better "keyword">for production)
bcryptsha256aes-gcm +4
Data Structuresintermediate
Go 1.18++

Advanced Slice and Map Utilities

Provides functional-style utilities for slices and maps without sacrificing allocations or compile-time type checking.

		key := keyFunc(item)
		groups[key] = append(groups[key], item)
	}
	"keyword">return groups
}
slicesmapsgenerics +4
Networkingadvanced
Go 1.18++

TCP Client and Server Implementation

Starts a TCP server that accepts clients in goroutines, responds to messages, and can be stopped via context or client c...

		}
	}
}
// Stop gracefully stops the TCP server
"keyword">func (s *TCPServer) Stop() {
tcpserverclient +3
Data Structuresadvanced
Go 1.18++

Advanced Configuration Loading

Centralizes configuration resolution so deployments can override settings safely without code changes.

	// Bind specific environment variables (optional, "keyword">for clarity)
	bindEnvVars(v)
	// 4. Bind command-line flags (highest priority)
	flags := pflag.NewFlagSet("app", pflag.ExitOnError)
	bindFlags(v, flags)
configurationviperenvironment variables +4
Webintermediate
Go 1.8+

Graceful Shutdown for HTTP Servers

Demonstrates how to stop an HTTP server cleanly instead of abruptly killing connections.

"keyword">func main() {
	// Create router and register handler
	r := http.NewServeMux()
	r.HandleFunc("/api/process", handler)
	// Configure HTTP server with timeouts (critical "keyword">for production)
httpgraceful shutdownsignal handling +2
Concurrencyintermediate
Go 1.13+

Rate Limiting with Token Bucket Algorithm

Controls how many operations can run per interval by consuming and refilling tokens at a steady pace.

"keyword">func (tb *TokenBucket) refill() {
	tb.mu.Lock()
	"keyword">defer tb.mu.Unlock()
	now := time.Now()
	elapsed := now.Sub(tb.lastRefill)
rate limitingtoken bucketconcurrency +2
Data Structuresintermediate
Go 1.16+

Struct Validation with Go Playground Validator

Validates a user payload with built-in tags and a custom phone validator to produce readable error lists.

		"keyword">return nil
	}
	// Process validation errors into a user-friendly "keyword">map
	errorMap := make("keyword">map["type">string]"type">string)
	"keyword">for _, err := "keyword">range errs.(validator.ValidationErrors) {
validationstructinput validation +2
Data Structuresadvanced
Go 1.14+

In-Memory Caching with TTL and Eviction

Thread-safe in-memory cache with TTL expiration, cleanup ticker, and LRU-style eviction when capacity is reached.

	"keyword">for key, item := "keyword">range c.items {
		"keyword">if item.expiration.Before(now) {
			c.lruList.Remove(item.listElement)
			delete(c.items, key)
			expiredCount++
cachingttllru +2
Networkingadvanced
Go 1.17+

gRPC Client/Server Implementation

Implements a unary gRPC service for user lookup with both server and client using manual service registration.

	}
	user, ok := s.users[userID]
	"keyword">if !ok {
		"keyword">return nil, status.Errorf(codes.NotFound, "user %d not found", userID)
	}
grpcprotobuftls +2
Networkingadvanced
Go 1.16+

Distributed Lock with Redis (Redlock Algorithm)

Implements a Redis-backed distributed mutex that acquires, renews, and releases locks safely across processes.

		success, err := rl.client.SetNX(ctx, rl.lockKey, rl.lockValue, rl.expireTime).Result()
		"keyword">if err != nil {
			"keyword">return false, fmt.Errorf("redis setnx failed: %v", err)
		}
		"keyword">if success {
distributed lockredisredlock +2
Webintermediate
Go 1.15+

WebSocket Server/Client with Real-Time Messaging

Full-duplex WebSocket example with a server that tracks clients and a client that sends and receives broadcast messages.

// readPump reads messages from the client and forwards to the hub "keyword">for broadcast
"keyword">func (c *WebSocketClient) readPump() {
	"keyword">defer "keyword">func() {
		c.hub.unregister <- c
		c.conn.Close()
websocketreal-timechat +2
Data Structuresintermediate
Go 1.17+

Database Migration with GORM (PostgreSQL)

Migration runner for PostgreSQL that applies up and down migrations with version tracking using GORM models.

		}
		log.Printf("Successfully applied migration %s", migration.Version)
	}
	"keyword">return nil
}
gormpostgresqldatabase migration +2
File Iointermediate
Go 1.14+

CSV Data Processing with Concurrency

High-throughput CSV pipeline that streams records, processes them with worker goroutines, and writes transformed rows co...

	"keyword">for record := "keyword">range inputChan {
		p.processRecord(record)
		outputChan <- record
		p.progressChan <- 1 // Report progress
	}
csvconcurrencydata processing +2
Webintermediate
Go 1.16+

JWT Authentication Middleware for HTTP Servers

HTTP middleware that parses, validates, and enforces JWTs with HMAC signing and role-based checks.

				"keyword">return
			}
			claims := &CustomClaims{}
			token, err := jwt.ParseWithClaims(tokenString, claims, "keyword">func(token *jwt.Token) ("keyword">interface{}, "type">error) {
				"keyword">if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
jwtauthenticationmiddleware +2
Concurrencyintermediate
Go 1.16+

Background Job Scheduler with Cron Expression Support

In-process scheduler that registers cron-style jobs, tracks runs, and supports graceful shutdown.

	"keyword">if job.ID == "" {
		"keyword">return fmt.Errorf("job.ID cannot be empty")
	}
	"keyword">if job.CronExpr == "" {
		"keyword">return fmt.Errorf("job.CronExpr cannot be empty")
cronschedulerbackground jobs +2
Networkingadvanced
Go 1.17+

gRPC Bidirectional Stream Chat Service

Bidirectional gRPC chat example where clients stream messages to the server and receive broadcast updates in real time.

"keyword">func (c *chatServiceClient) ChatStream(ctx context.Context, opts ...grpc.CallOption) (ChatService_ChatStreamClient, "type">error) {
	desc := &ChatService_ServiceDesc.Streams[0]
	stream, err := c.cc.NewStream(ctx, desc, "/chat.ChatService/ChatStream", opts...)
	"keyword">if err != nil {
		"keyword">return nil, err
grpcbidirectional streamchat service +2
File Ioadvanced
Go 1.16+

Resumable File Upload/Download with Chunking

Chunked upload and download service that supports pausing and resuming large file transfers with checksum validation.

		TotalChunks: totalChunks,
		ChunksReceived: make("keyword">map["type">int]"type">bool),
	}
	s.mu.Lock()
	s.files[fileID] = fileMeta
resumable uploadfile chunkinghttp +2
Webintermediate
Go 1.16+

Circuit Breaker for Resilient External API Calls

Wraps outbound HTTP calls with a Hystrix-like circuit breaker to stop hammering unhealthy dependencies.

	Data "type">string `json:"data"`
	Status "type">string `json:"status"`
}
// CallAPI makes a resilient API call using the circuit breaker
"keyword">func (c *ExternalAPIClient) CallAPI(endpoint "type">string) (*APIResponse, "type">error) {
circuit breakerresiliencehystrix +2
Data Structuresintermediate
Go 1.14+

Zero-Allocation Slice Filter and Map Utilities

Performance-focused slice helpers that avoid extra allocations by pre-sizing outputs and reusing buffers.

	acc := initial
	"keyword">for _, v := "keyword">range input {
		acc = reducer(acc, v)
	}
	"keyword">return acc
zero allocationslice utilitiesperformance +2
File Iointermediate
Go 1.16+

Real-Time Log Aggregator with Tail and Filter

Tails multiple log files concurrently, filters lines with regex, and streams matches to outputs in near real time.

	"keyword">for _, r := "keyword">range a.filters {
		"keyword">if r.MatchString(line) {
			"keyword">return true
		}
	}
log aggregationlog tailingregex filter +2
Webintermediate
Go 1.17+

GeoIP Lookup Service with MaxMind Database

Memory-caches MaxMind GeoLite2 data to serve fast IP-to-location lookups with IPv4 and IPv6 support.

	"keyword">return nil
}
// LookupCity retrieves city-level geolocation data "keyword">for an IP address
"keyword">func (s *GeoIPService) LookupCity(ipStr "type">string) (*geoip2.City, "type">error) {
	s.mu.RLock()
geoipmaxmindgeolocation +2
Networkingadvanced
Go 1.16+

Asynchronous Task Queue with Redis Backend

Redis-backed task queue with enqueue, worker pools, retries, delays, and dead-letter handling for failed jobs.

	"keyword">if err != nil {
		"keyword">return fmt.Errorf("marshal task: %w", err)
	}
	member := "type">string(b)
	"keyword">if delay > 0 {
task queueredisasynchronous tasks +2
File Iointermediate
Go 1.17+

Hardware System Info Monitor (CPU/Memory/Disk)

Cross-platform sampler that periodically collects CPU, memory, disk, and network stats for health monitoring.

		"keyword">return nil, fmt.Errorf("failed to get CPU usage: %v", err)
	}
	"keyword">if len(cpuPercent) > 0 {
		stats.CPUUsage = cpuPercent[0]
	}
system monitoringcpumemory +2
Webadvanced
Go 1.18+

OAuth2 Authentication with Google and GitHub Providers

OAuth2 helper that handles Google and GitHub provider flows, exchanges codes for tokens, and persists sessions with secu...

// callbackHandler handles the OAuth provider's callback and retrieves user profile
"keyword">func (s *OAuthService) callbackHandler(w http.ResponseWriter, r *http.Request) {
	providerName := r.URL.Query().Get("provider")
	"keyword">if providerName == "" {
		http.Error(w, "provider query parameter required", http.StatusBadRequest)
oauth2googlegithub +2
Data Structuresintermediate
Go 1.18+

Binary Search Tree (BST) Implementation with CRUD Operations

Generic binary search tree with thread-safe insert, search, delete, and traversal helpers.

	}
	"keyword">if value < n.value {
		"keyword">var deleted "type">bool
		n.left, deleted = deleteNode(n.left, value)
		"keyword">return n, deleted
bstbinary search treedata structures +3
Networkingintermediate
Go 1.16+

SMTP Email Sender with Attachments and HTML Support

SMTP client helper that sends text or HTML emails with attachments, CC or BCC, and TLS configuration.

	}
	// Add attachments
	"keyword">for _, file := "keyword">range config.Attachments {
		"keyword">if err := addAttachment(writer, file); err != nil {
			"keyword">return fmt.Errorf("failed to add attachment %s: %w", file, err)
smtpemailattachments +3
Concurrencyadvanced
Go 1.17+

Deadlock Detection in Goroutine Communication

Illustrates deadlock-prone channel patterns and a detector that uses timeouts to surface stuck goroutines.

		ctx, cancel := context.WithTimeout(d.ctx, d.timeout)
		"keyword">defer cancel()
		// Channel to track completion
		done := make("keyword">chan "keyword">struct{}, 1)
		// Run the target function in a separate goroutine
deadlockgoroutinecontext +3
Networkingintermediate
Go 1.19+

Protobuf Serialization/Deserialization with Go

Defines proto3 schemas with enums and nested messages and uses dynamicpb to serialize and deserialize without generated...

			{Name: proto.String("email"), Number: proto.Int32(3), Label: descriptorpb.FieldDescriptorProto_LABEL_OPTIONAL.Enum(), Type: descriptorpb.FieldDescriptorProto_TYPE_STRING.Enum()},
			{Name: proto.String("age"), Number: proto.Int32(4), Label: descriptorpb.FieldDescriptorProto_LABEL_OPTIONAL.Enum(), Type: descriptorpb.FieldDescriptorProto_TYPE_INT32.Enum()},
			{Name: proto.String("">type"), Number: proto.Int32(5), Label: descriptorpb.FieldDescriptorProto_LABEL_OPTIONAL.Enum(), Type: descriptorpb.FieldDescriptorProto_TYPE_ENUM.Enum(), TypeName: proto.String(".user.UserType")},
			{Name: proto.String("address"), Number: proto.Int32(6), Label: descriptorpb.FieldDescriptorProto_LABEL_OPTIONAL.Enum(), Type: descriptorpb.FieldDescriptorProto_TYPE_MESSAGE.Enum(), TypeName: proto.String(".user.User.Address")},
			{Name: proto.String("hobbies"), Number: proto.Int32(7), Label: descriptorpb.FieldDescriptorProto_LABEL_REPEATED.Enum(), Type: descriptorpb.FieldDescriptorProto_TYPE_STRING.Enum()},
protobufserializationdeserialization +3
Data Structuresadvanced
Go 1.18+

Bloom Filter Implementation for Efficient Membership Testing

Thread-safe Bloom filter that computes optimal hash counts, supports add and contains, and can be serialized for persist...

		// Convert hash bytes to uint and mod by size to get bit position
		position := binary.BigEndian.Uint64(hash[:8]) % uint64(b.size)
		hashes[i] = uint(position)
	}
	"keyword">return hashes
bloom filterdata structuresmembership testing +2
File Iointermediate
Go 1.18+

Image Processing with Resizing, Cropping and Format Conversion

Image utility that resizes, crops, rotates, and converts between formats using imaging with controllable quality setting...

	}
	ip.image = imaging.Crop(ip.image, cropRect)
	"keyword">return nil
}
// Rotate rotates the image by the specified degrees (counter-clockwise)
image processingresizecrop +4
Webadvanced
Go 1.19+

WebSocket Pub/Sub Server with Room Support

Room-based WebSocket broker that manages subscribers per room, broadcasts messages, and tracks presence with ping or pon...

				Type:    "presence",
				Username: client.username,
				Content:  fmt.Sprintf("%s joined the room", client.username),
				Room:     r.name,
				Timestamp: time.Now().Unix(),
websocketpub/subchat +3
Data Structuresadvanced
Go 1.18+

Time Series Data Aggregation with Sliding Window

Sliding-window aggregator that maintains rolling sums, counts, minimums, maximums, and averages over time-based buckets.

	s.trimOldDataPoints(time.Now().Add(-s.windowSize))
}
// trimOldDataPoints removes data points older than the specified cutoff time
"keyword">func (s *SlidingWindowAggregator) trimOldDataPoints(cutoff time.Time) {
	// Iterate from front and remove old data points
time seriessliding windowaggregation +2
Webintermediate
Go 1.18+

Environment Variable Manager with Type Conversion and Validation

Typed environment loader that reads environment variables with defaults, required checks, and per-type parsers for integ...

			e.values[name] = envVar.Default
			"keyword">return
		}
		// Use zero value "keyword">for optional variables with no "keyword">default
		e.values[name] = getZeroValue(envVar.Type)
env varsconfigurationvalidation +2
Data Structuresintermediate
Go 1.18+

LRU Cache with TTL and Automatic Eviction

LRU cache that tracks recency and TTL per entry, expiring stale items automatically and enforcing a maximum size.

	// Check "keyword">if key already exists
	"keyword">if elem, exists := c.items[key]; exists {
		// Update existing entry
		c.order.MoveToFront(elem)
		entry := elem.Value.(*CacheEntry)
lru cachettleviction +2
File Iointermediate
Go 1.18+

CSV to JSON Converter with Streaming Processing

Streams a CSV file line-by-line and emits JSON records without loading the entire file, supporting custom delimiters and...

			"keyword">break
		}
		"keyword">if err != nil {
			"keyword">return fmt.Errorf("failed to read row: %w", err)
		}
csvjsonstreaming +2
Networkingintermediate
Go 1.18+

Concurrent TCP Port Scanner with Timeout Control

Concurrent TCP port scanner that sweeps ranges with per-connection timeouts and reports open ports quickly.

	"keyword">for port := start; port <= end; port++ {
		ports = append(ports, port)
	}
	"keyword">return NewPortScanner(target, ports, timeout, concurrency)
}
port scannertcpconcurrency +2
Webadvanced
Go 1.19+

JWT Token Revocation with Redis Blacklist

Adds JWT revocation by storing unique token identifiers in Redis and checking them on each request.

		// Validate signing method
		"keyword">if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
			"keyword">return nil, fmt.Errorf("unexpected signing method: %v", token.Header["alg"])
		}
		"keyword">return m.secretKey, nil
jwtredistoken revocation +2
Webintermediate
Go 1.19+

IP-Based Rate Limiter Middleware for HTTP Servers

HTTP middleware that rate-limits requests per client IP using a token bucket and returns 429 with Retry-After hints.

"keyword">func (i *IPRateLimiter) GetLimiter(ip "type">string) *rate.Limiter {
	i.mu.RLock()
	limiter, exists := i.limiters[ip]
	i.mu.RUnlock()
	"keyword">if exists {
rate limitermiddlewarehttp +2
Webintermediate
Go 1.16++

Graceful HTTP Server Shutdown with Signal Handling

Runs an HTTP server with sane timeouts and health endpoints, shutting down gracefully on OS signals with context cancell...

		writeJSON(w, http.StatusOK, "keyword">map["type">string]"keyword">interface{}{"status": "ok"})
	})
	mux.HandleFunc("/readyz", "keyword">func(w http.ResponseWriter, r *http.Request) {
		writeJSON(w, http.StatusOK, "keyword">map["type">string]"keyword">interface{}{"ready": true})
	})
httpgraceful shutdownsignals +3
Networkingintermediate
Go 1.18++

HTTP Client with Retries, Backoff, and Retry-After Support

HTTP client helper that wraps requests with retry logic, exponential backoff with jitter, and Retry-After support.

	"keyword">return d - (d / 6) + jitter
}
"keyword">func parseRetryAfterSeconds(resp *http.Response) (time.Duration, "type">bool) {
	"keyword">if resp == nil {
		"keyword">return 0, false
http clientretriesbackoff +3
Concurrencyintermediate
Go 1.18++

Context-Cancelable Worker Pool with First-Error Cancellation

Worker pool that processes jobs with bounded concurrency and cancels remaining work on the first failure.

				"keyword">select {
				"keyword">case errCh <- err:
				"keyword">default:
				}
				cancel()
worker poolcontext cancellationfirst error +2
Concurrencyadvanced
Go 1.18++

Bounded Parallel Map with Generics and Ordered Results

Parallel map helper that limits concurrency, preserves input order, and aborts on the first error.

	}
	sem := make("keyword">chan "keyword">struct{}, concurrency)
	out := make("keyword">chan result, len(items))
	"keyword">var wg sync.WaitGroup
	"keyword">for i := "keyword">range items {
genericsparallel mapbounded concurrency +2
Data Structuresintermediate
Go 1.18++

Thread-Safe LRU Cache with O(1) Get/Put

Classic LRU cache using a map plus a doubly linked list to provide O(1) get and put with deterministic eviction.

	}
}
"keyword">func (c *LRUCache) Get(key "type">string) ("type">string, "type">bool) {
	c.mu.Lock()
	"keyword">defer c.mu.Unlock()
lrucachemutex +2
Data Structuresbeginner
Go 1.18++

Disjoint Set Union (Union-Find) with Path Compression

Union-Find data structure with path compression and union by rank for near constant-time connectivity queries.

	"keyword">if d.parent[x] != x {
		d.parent[x] = d.Find(d.parent[x])
	}
	"keyword">return d.parent[x]
}
union-finddsupath compression +2
Data Structuresadvanced
Go 1.18++

In-Process Task Scheduler Using a Min-Heap

Min-heap scheduler that executes tasks at specific times without busy-waiting, supporting dynamic scheduling and cancell...

}
"keyword">func (s *Scheduler) Schedule(t *Task) {
	s.mu.Lock()
	heap.Push(&s.h, t)
	s.mu.Unlock()
schedulerheaptimers +2
File Iointermediate
Go 1.16++

Atomic JSON Config Writes with fsync (Crash-Safe)

Crash-safe JSON writer that uses temp files, fsync, and atomic rename so configuration files are never left half-written...

		os.Remove(tmpName)
	}
	"keyword">if _, err := tmp.Write(data); err != nil {
		cleanup()
		"keyword">return fmt.Errorf("write temp: %w", err)
atomic writefsyncjson +2
File Iointermediate
Go 1.18++

Streaming File Copy with Progress and SHA-256 Verification

Copies large files with constant memory usage while reporting progress and verifying integrity with SHA-256.

		dst.Close()
	}()
	hasher := sha256.New()
	buf := make([]"type">byte, 256*1024)
	"keyword">var total "type">int64
streamingfile copyprogress +2
Networkingintermediate
Go 1.18++

TCP Line Protocol Server with Deadlines and Graceful Shutdown

Concurrent TCP server implementing a simple line-based protocol with deadlines and graceful shutdown.

			"keyword">return
		}
		line, err := r.ReadBytes(newline)
		"keyword">if err != nil {
			"keyword">return
tcp serverdeadlinestimeouts +2
Webadvanced
Go 1.18++

Reverse Proxy with Authentication and Timeouts

Reverse proxy built on net/http/httputil that forwards requests, adds simple bearer authentication, and enforces timeout...

	proxy.ErrorHandler = "keyword">func(w http.ResponseWriter, r *http.Request, err "type">error) {
		http.Error(w, fmt.Sprintf("upstream ">error: %v", err), http.StatusBadGateway)
	}
	proxy.Transport = &http.Transport{
		Proxy: http.ProxyFromEnvironment,
reverse proxyhttputilhttp +2
Webintermediate
Go 1.18++

Server-Sent Events (SSE) Broadcaster with Keep-Alives

Server-Sent Events broadcaster that lets clients subscribe, keeps connections alive, and broadcasts messages over HTTP.

	}
	"keyword">return id, c, unsubscribe
}
"keyword">func (b *Broker) Publish(msg "type">string) {
	b.mu.RLock()
sseserver-sent eventsstreaming +2
Webadvanced
Go 1.18++

Streaming Multipart File Upload with Size Limits and SHA-256

Processes multipart file uploads without buffering entire files, enforcing size limits and computing SHA-256 while strea...

			http.Error(w, "failed to create upload dir", http.StatusInternalServerError)
			"keyword">return
		}
		"keyword">var savedPath "type">string
		"keyword">var written "type">int64
multipartuploadstreaming +3
Cryptointermediate
Go 1.18++

AES-GCM Encryption and Decryption (Authenticated)

Helper for encrypting and decrypting byte slices with AES-GCM using random nonces and returning nonce plus ciphertext pa...

	"keyword">if _, err := io.ReadFull(rand.Reader, nonce); err != nil {
		"keyword">return nil, err
	}
	ciphertext := gcm.Seal(nil, nonce, plaintext, nil)
	out := append(nonce, ciphertext...)
aesgcmencryption +2
Cryptointermediate
Go 1.18++

HMAC-Signed Expiring Tokens (Stateless)

Creates stateless tokens signed with HMAC-SHA256 and expiration timestamps, plus verification helpers using constant-tim...

		"keyword">return "", err
	}
	body := base64.RawURLEncoding.EncodeToString(b)
	sig := sign(secret, body)
	"keyword">return body + "." + sig, nil
hmactokensexpiration +2
Cryptoadvanced
Go 1.18++

Self-Signed TLS Certificate Generation and HTTPS Server

Generates a self-signed certificate on startup, writes PEM files, and launches an HTTPS server for local development.

	tpl := x509.Certificate{
		SerialNumber: serial,
		Subject: pkix.Name{
			Organization: []"type">string{"Local Dev Cert"},
			CommonName:   "localhost",
tlsx509self-signed +2
Error Handlingbeginner
Go 1.13++

Rich Error Types with Wrap/Unwrap and errors.Is/As

Custom error type capturing operation context plus helpers showing errors.Is and errors.As and wrapped stacks.

	"keyword">return fmt.Sprintf("%s: %v", e.Op, e.Err)
}
"keyword">func (e *OpError) Unwrap() "type">error { "keyword">return e.Err }
"keyword">func loadUser(id "type">string) "type">error {
	"keyword">if id == "" {
errorswrappingerrors.Is +2
Error Handlingintermediate
Go 1.18++

Retry Helper with Exponential Backoff, Jitter, and Context

Reusable retry helper that applies exponential backoff with jitter, supports context cancellation, and lets callers defi...

		"keyword">if err == nil {
			"keyword">return nil
		}
		"keyword">if errors.Is(err, ErrPermanent) {
			"keyword">return err
retrybackoffjitter +2
Concurrencyintermediate
Go 1.18++

In-Memory Pub/Sub with Unsubscribe and Backpressure

Lightweight in-process pub/sub topic with subscriber management, non-blocking publishes, and explicit unsubscribe suppor...

	id := t.next
	c := make("keyword">chan "type">string, buffer)
	t.subs[id] = c
	unsubscribe = "keyword">func() {
		t.mu.Lock()
pubsubchannelsbackpressure +2
Networkingbeginner
Go 1.18++

UDP Echo Server and Client with Deadlines

Simple UDP echo pair showing packet send and receive with deadlines and graceful shutdown loops.

			"keyword">case <-ctx.Done():
				"keyword">return
			"keyword">default:
			}
			_ = conn.SetReadDeadline(time.Now().Add(1 * time.Second))
udpecho serverdeadlines +2