Web
261 articles
Add middleware in Go web servers
Add middleware in Go by wrapping your http.Handler with a function that executes logic before passing the request to the next handler.
Complete Guide to the net Package in Go
The Go net package provides a unified interface for TCP, UDP, and Unix network I/O operations.
Complete Guide to the net/url Package in Go
The net/url package parses, resolves, and encodes URLs in Go, providing structured access to scheme, host, and path components.
Environment variables
Set the GODEBUG environment variable with key=value pairs to control Go runtime behavior and maintain backwards compatibility.
File uploads in Go
Parse multipart form requests in Go using ParseMultipartForm and FormFile to handle file uploads.
Fix: "http: panic serving" in Go
Fix the 'http: panic serving' error in Go by wrapping your HTTP handler in a defer/recover block to catch panics and return a 500 error.
Fix: "http: server gave HTTP response to HTTPS client"
Fix the 'http: server gave HTTP response to HTTPS client' error by setting GODEBUG=http2client=0 to disable HTTP/2.
Fix: "http: wrote more than the declared Content-Length"
Fix the 'http: wrote more than the declared Content-Length' error by ensuring your response body size matches the Content-Length header.
Fix: "net/http: request canceled (Client.Timeout exceeded)"
Fix the 'request canceled (Client.Timeout exceeded)' error by increasing the Timeout value in your http.Client configuration.
Fix: "template: X is not defined" in Go
Fix the 'template: X is not defined' error by ensuring the variable X is present in the data map or registered in the FuncMap before executing the template.
Fix: "x509: certificate signed by unknown authority"
Fix x509 certificate errors in Go by setting GODEBUG=x509ignoreCN=0 or updating your CA bundle.
Gin vs Echo vs Chi vs Fiber: Which Go Web Framework to Use
Choose Echo for the best balance of performance, middleware ecosystem, and developer experience in production; pick Fiber if you need raw speed and a Node.js-like syntax, or Gin if you are already invested in its specific middleware patterns.
Go for Web Development: Pros and Cons
Go provides fast performance and easy concurrency for web development but requires verbose error handling and has a steeper learning curve for complex patterns.
Go vs Node.js: Backend Performance and Developer Experience
Go wins on raw performance and concurrency, while Node.js excels in developer speed and ecosystem breadth for I/O-heavy tasks.
Go vs TypeScript: Which Is Better for APIs
Go offers superior performance and concurrency for backend APIs, while TypeScript provides better ecosystem integration for JavaScript developers.
Go Wasm vs TinyGo Wasm: Comparison and Trade-Offs
Standard Go Wasm offers full compatibility for web apps, while TinyGo Wasm provides minimal binaries for embedded devices.
gqlgen vs graphql-go: Which GraphQL Library to Use
Use **gqlgen** for new Go projects because it is the industry standard, actively maintained, and generates type-safe code that integrates seamlessly with Go's tooling.
Graceful shutdown
Implement graceful shutdown for GOCACHEPROG by handling the 'close' command and exiting after responding.
gRPC authentication
Secure gRPC connections in Go by configuring TLS credentials using the grpc/credentials package for both clients and servers.
gRPC client in Go
Create a gRPC-compatible HTTP/2 client in Go using http2.Transport or standard http.Client with TLS.
gRPC-Gateway REST and gRPC
gRPC-Gateway generates a REST API from gRPC definitions, translating HTTP/JSON requests into gRPC calls for unified service exposure.
gRPC Load Balancing in Go
Go requires manual implementation of gRPC load balancing via custom Transport dial functions or external proxies.
gRPC server in Go
Start a gRPC-compatible HTTP/2 server in Go using net/http and golang.org/x/net/http2.
gRPC streaming
gRPC streaming requires the google.golang.org/grpc library and proto definitions, as the provided http2 source only handles the underlying transport layer.
gRPC vs REST: When to Use Which in Go
Use gRPC for high-performance internal microservices with strict contracts and REST for public APIs requiring broad compatibility and simplicity.
Handle CORS in Go
Manually add CORS headers like Access-Control-Allow-Origin to Go HTTP responses using a middleware wrapper.
How to Add gRPC Interceptors (Middleware) in Go
Add gRPC interceptors in Go by wrapping your server or client options with UnaryInterceptor or StreamInterceptor functions to handle cross-cutting concerns like logging and auth.
How to Add Health Check Endpoints in Go
Add a /health handler to your Go HTTP server that returns a 200 OK status to confirm the application is running.
How to Auto-Escape HTML in Go Templates
Go templates automatically escape HTML to prevent XSS attacks, rendering special characters as safe text by default.
How to Bind and Validate Requests in Echo
Bind requests to structs with c.Bind() and validate data using c.Validate() or middleware in Echo.
How to Broadcast Messages to Multiple WebSocket Clients in Go
Broadcast to multiple WebSocket clients in Go by iterating over a connection map and writing the message to each active socket.
How to Build a 12-Factor App in Go
Build a 12-Factor App in Go by externalizing configuration to environment variables and designing stateless processes for scalable deployment.
How to Build a Blog Engine in Go
Initialize a Go module, write a simple HTTP handler in main.go, and run the server to start your blog engine.
How to Build a Caching Proxy in Go
Build a Go caching proxy using an HTTP server and sync.Map to store and serve upstream responses.
How to Build a Chat Application in Go with WebSockets
Build a Go chat app by upgrading HTTP connections to WebSockets and broadcasting messages to all clients via a shared channel.
How to Build a Discord Bot in Go
Initialize a Go module, install a Discord library, write a handler for messages, and run the program to create a Discord bot.
How to Build a File Upload Service in Go
Build a Go file upload service using net/http to handle POST requests and os.Create to save files.
How to Build a Full-Stack App with Go and HTMX
You build a full-stack app with Go and HTMX by using Go as a robust backend that renders HTML templates and serves JSON or HTML fragments, while HTMX on the frontend handles AJAX, CSS transitions, and DOM updates without writing custom JavaScript.
How to Build a GraphQL API in Go
Build a GraphQL API in Go by defining a schema, generating code with gqlgen, implementing resolvers, and running an HTTP server.
How to Build a Job Scheduler in Go
Build a Go job scheduler using time.NewTicker to run tasks at fixed intervals without external libraries.
How to Build a Metrics Dashboard Backend in Go
Build a Go metrics backend by creating an HTTP server with JSON endpoints using the net/http package.
How to Build an AI Chat Application Backend in Go
Initialize a Go module, write a simple HTTP handler to process JSON messages, and run the server to start your AI chat backend.
How to Build an Image Processing Service in Go
Build a Go image processing service by creating an HTTP handler that decodes uploaded images and re-encodes them using the standard library.
How to Build a Notification Service in Go
Build a Go notification service using a buffered channel and a worker goroutine to handle messages asynchronously.
How to Build an SMTP Client in Go
Send emails in Go using the standard net/smtp package with a single SendMail function call.
How to Build a Rate Limiter Service in Go
Implement a Go rate limiter using the golang.org/x/time/rate package to control request frequency and prevent server overload.
How to Build a Real-Time Chat Application in Go
Build a real-time chat application in Go by leveraging the `net/http` package for HTTP/WebSocket upgrades and the `gorilla/websocket` library to manage persistent, full-duplex connections between clients and a central server.
How to Build a REST API with Authentication in Go
Use the standard `net/http` package combined with a middleware pattern to handle authentication, typically by validating a Bearer token or session cookie before the request reaches your handler.
How to Build a REST API with Chi in Go
Build a REST API in Go using the Chi router by importing the package, defining handlers, and mounting routes to the router instance.
How to Build a REST API with Echo in Go
Use the Echo framework to initialize a server, define routes with HTTP methods, and attach handler functions that process requests and return JSON responses.
How to Build a REST API with Fiber in Go
Use Fiber to define routes with a lightweight router, bind JSON payloads to structs, and return responses using the built-in `c.JSON()` method.
How to Build a REST API with Gin in Go
Initialize a Go module, install Gin, define a route handler, and run the server to create a basic REST API.
How to Build a Simple Proxy in Go
Build a simple Go proxy using httputil.NewSingleHostReverseProxy to forward HTTP requests to a target URL.
How to Build a Static Site Generator in Go
Build a static site generator in Go by parsing templates and source files to output static HTML pages.
How to Build a Telegram Bot in Go
TITLE: How to Build a Telegram Bot in Go
How to Build a TODO API in Go (Full CRUD)
You can build a full CRUD TODO API in Go using the standard library's `net/http` package by defining a struct for your data, creating a slice to act as an in-memory store, and registering four handler functions for Create, Read, Update, and Delete operations.
How to Build a URL Shortener in Go
Build a Go URL shortener by mapping short keys to long URLs in an HTTP handler.
How to Build a Web App Frontend in Go with Wasm
Use the TinyGo compiler with the --target wasm flag to build Go frontend applications that run in the browser as WebAssembly.
How to Build a Web Scraper in Go
Build a Go web scraper using net/http to fetch pages and golang.org/x/net/html to parse and extract data.
How to build REST API with Gin
Build a REST API with Gin by initializing a module, defining routes with handlers, and running the server.
How to Build Serverless Go Applications
Build a serverless Go app by writing an HTTP handler, initializing a module, and compiling a static binary for cloud deployment.
How to Call Anthropic Claude API from Go
Initialize the Anthropic Go SDK client with your API key and call Messages.Create to send a prompt and receive a response from Claude.
How to Call Go Functions from JavaScript Wasm
Export Go functions with //export, compile to wasm, and call them via WebAssembly.instantiate in JavaScript.
How to Call JavaScript from Go Wasm
Call JavaScript from Go WebAssembly using the syscall/js package to access global objects and invoke methods.
How to Call OpenAI API from Go
Call the OpenAI API from Go using the sashabaranov/go-openai client library to send chat requests and receive text responses.
How to Chain Multiple Middleware in Go
Chain Go middleware by wrapping handlers sequentially using a helper function that iterates through the middleware list in reverse order.
How to Compile Go to WebAssembly (GOOS=js GOARCH=wasm)
To compile Go to WebAssembly, set the environment variables `GOOS=js` and `GOARCH=wasm` before running `go build`, then use a JavaScript runtime like `wasm_exec.js` to execute the resulting `.wasm` binary in a browser.
How to Create a Basic HTTP Server in Go
Create a basic HTTP server in Go using the net/http package to handle requests and serve responses.
How to Create a gRPC Client in Go
Create a gRPC client in Go by generating code from a .proto file using protoc and calling the generated client methods.
How to Create a gRPC Server in Go
Create a gRPC server in Go by defining a proto service, generating code, and running a listener with grpc.NewServer().
How to Create a TCP Client in Go
Use the `net.Dial` function from the standard library to establish a TCP connection, then wrap the returned `net.Conn` interface with `bufio` readers and writers for efficient I/O.
How to Create a TCP Server in Go
Create a TCP server in Go using the net package to listen on a port and handle incoming connections.
How to Create a UDP Server and Client in Go
Create a UDP server and client in Go using the net package to listen for and send datagrams without a persistent connection.
How to create HTTP server
Start a Go HTTP server by defining a handler function and calling http.ListenAndServe with your desired port.
How to Define a GraphQL Schema in Go
Define GraphQL schemas in Go by using the gqlgen library to generate code from .graphql files.
How to Define a Protocol Buffer (.proto) File
To define a Protocol Buffer file, create a `.proto` file with a `syntax` declaration, specify the `package`, and define `message` types with field numbers and data types.
How to Deploy a Go App to AWS Lambda
Deploy a Go app to AWS Lambda by compiling a static binary, zipping it, and uploading it as a deployment package.
How to Deploy a Go App to Google Cloud Functions
Deploy a Go app to Google Cloud Functions by building a Linux binary and using gcloud to configure and launch the service.
How to Design Microservices in Go
Design Go microservices by building independent binaries with HTTP handlers, context-aware cancellation, and graceful shutdown logic.
How to Download a File with HTTP in Go
Download a file in Go using net/http.Get and io.Copy to save the response body to disk.
How to Follow or Disable Redirects in Go
Disable HTTP/2 redirects and other behaviors in Go by setting GODEBUG environment variables or using //go:debug directives.
How to Generate Go Code from Proto Files
Use the official `protoc` compiler with the Go plugin (`protoc-gen-go`) to compile your `.proto` files into idiomatic Go source code.
How to Generate Swagger/OpenAPI Docs for a Go API
Generate Swagger/OpenAPI docs for a Go API by installing the swag CLI and running swag init to scan your code comments.
How to Handle 404 and Error Pages in Go
Go requires manual registration of handlers to serve 404 and custom error pages since it does not provide automatic fallback behavior.
How to Handle Configuration in Microservices with Go
Configure Go microservices runtime behavior using the GODEBUG environment variable or go.mod directives to manage compatibility and security settings.
How to handle cookies in Go
Go handles cookies manually using the net/http package to read and write http.Cookie objects.
How to Handle CORS Properly in Go
Manually set Access-Control-Allow-Origin headers in Go HTTP handlers to enable cross-origin requests.
How to Handle File Uploads in a Go HTTP Server
Handle file uploads in Go by parsing multipart forms with ParseMultipartForm and saving the file stream using FormFile.
How to Handle File Uploads in Gin
Handle file uploads in Gin by parsing the multipart form and using FormFile to retrieve the uploaded file as an io.Reader.
How to Handle GraphQL Queries, Mutations, and Subscriptions in Go
Go requires third-party libraries like gqlgen to implement GraphQL queries, mutations, and subscriptions.
How to Handle gRPC Metadata (Headers) in Go
Handle gRPC metadata in Go by retrieving it from the request context using metadata.FromIncomingContext or attaching it with metadata.AppendToOutgoingContext.
How to Handle HTTP Cookies in Go
Use the net/http package to read cookies from requests and write them to responses in Go.
How to Handle Inter-Service Communication in Go
Use Go's net/http or gRPC libraries to send requests between services running on different hosts or ports.
How to Handle JSON Request and Response in Gin
Handle JSON in Gin using ShouldBindJSON for requests and c.JSON for responses.
How to Handle Keep-Alive Connections in Go
Go automatically reuses HTTP connections for performance; disable this by setting Transport.DisableKeepAlives to true.
How to Handle N+1 Query Problem in Go GraphQL
Fix the N+1 query problem in Go GraphQL by implementing data loaders to batch database requests into a single query.
How to Handle Rate Limiting in HTTP Clients in Go
Implement rate limiting in Go HTTP clients by wrapping the Transport with a golang.org/x/time/rate limiter to control request frequency.
How to Handle Request Timeouts in Go Web Servers
Disable HTTP/2 in Go web servers and clients by setting GODEBUG=http2client=0,http2server=0 to prevent timeouts from buggy implementations.
How to Handle Routes in Go with net/http
Handle routes in Go by mapping URL patterns to functions using http.HandleFunc and starting the server with http.ListenAndServe.
How to Handle WebSocket Authentication in Go
Implement WebSocket authentication in Go by validating credentials during the HTTP handshake before allowing the connection upgrade.
How to Handle WebSocket Reconnection on the Client Side
Use an exponential backoff loop with jitter to safely retry WebSocket connections on the client side until success or a retry limit is reached.
How to Hash Passwords in Go with argon2
Hash passwords in Go using the golang.org/x/crypto/argon2 package with Argon2id for secure storage.
How to Hash Passwords in Go with bcrypt
Hash passwords in Go using the bcrypt package with GenerateFromPassword and CompareHashAndPassword functions.
How to Implement a Connection Pool in Go
Configure a Go database connection pool by setting max open, max idle, and max lifetime limits on the DB object.
How to Implement a DNS Client or Server in Go
Implement a Go DNS server using net.Listen and net/dns.Server, or a client using net/dns.Client to exchange DNS messages.
How to Implement API Gateway Pattern in Go
Implement an API Gateway in Go by using http.ServeMux to route requests to backend services based on URL paths.
How to Implement API Versioning in Go
Implement API versioning in Go using URL path prefixes and GODEBUG directives to manage different API behaviors.
How to Implement a Port Scanner in Go
Implement a Go port scanner by using net.DialTimeout to check if a specific TCP port on a target host accepts connections.
How to Implement a Template Cache in Go
Parse Go templates once at startup using template.Must and store the result in a variable to avoid repeated parsing overhead.
How to Implement Authentication Middleware in Go
Implement Go authentication middleware by wrapping handlers to validate request headers and reject unauthorized access with a 401 status.
How to Implement Basic Auth in Go
Implement Basic Auth in Go using the net/http package's BasicAuth helper to validate credentials and return 401 errors for unauthorized access.
How to Implement Circuit Breaker Pattern in Go
Go has no built-in circuit breaker; use the sony/gobreaker library to stop cascading failures when external services are down.
How to Implement Compression Middleware (gzip) in Go
Implement gzip compression in Go by wrapping your handler with a middleware that checks Accept-Encoding and writes to a gzip.Writer.
How to Implement CORS Middleware in Go
Implement CORS in Go by creating a middleware handler that sets Access-Control headers and handles preflight OPTIONS requests.
How to Implement DataLoader Pattern in Go GraphQL
Go lacks a native DataLoader, requiring manual implementation of request batching and caching to optimize database queries.
How to Implement Event-Driven Architecture in Go
Use Go channels and a central event bus to decouple components and handle asynchronous events efficiently.
How to Implement Graceful Shutdown for an HTTP Server in Go
Implement graceful shutdown in Go by calling http.Server.Shutdown with a context timeout to stop new connections and wait for active requests.
How to Implement Graceful Shutdown in Go Microservices
Implement graceful shutdown in Go by catching OS signals, canceling a context, and calling server.Shutdown to finish active requests before exiting.
How to Implement GraphQL Authentication in Go
Configure Go module authentication by setting the GOAUTH environment variable to a credential command like git or netrc.
How to Implement Health Check Endpoints in Go
Implement a Go health check endpoint by creating an HTTP handler that returns a 200 status code and registering it at a specific path like /health.
How to Implement Heartbeat/Ping-Pong for WebSockets in Go
Implement WebSocket heartbeats in Go by using SetPingHandler and SetPongHandler to track liveness and sending periodic PingMessage frames.
How to Implement JWT Authentication in Gin/Echo/Chi
Use a middleware function to intercept requests, extract the JWT from the `Authorization` header, verify the signature and expiration, and inject the user claims into the request context for downstream handlers.
How to Implement JWT Authentication in Go
Implement JWT authentication in Go by generating signed tokens with a secret key and validating them in HTTP middleware.
How to Implement Logging Middleware in Go
Wrap your HTTP handler in a function that logs request details before and after execution to implement logging middleware in Go.
How to Implement OAuth2 Flow in Go
Use the `GOAUTH` environment variable to configure authentication commands for the `go` command.
How to Implement Pagination in a Go API
Implement Go API pagination by parsing query parameters and slicing your data array based on calculated offsets.
How to Implement Rate Limiting in a Go HTTP Server
Implement rate limiting in a Go HTTP server using the golang.org/x/time/rate package to restrict request frequency.
How to Implement Recovery (Panic Catch) Middleware in Go
Implement panic recovery middleware in Go by wrapping handlers with a defer-recover block to catch errors and return 500 responses.
How to Implement Request ID Middleware in Go
Add unique request tracking to Go HTTP servers using context and middleware.
How to Implement Request Validation in Go
Implement request validation in Go by using the validator library to define struct tags and run validation checks.
How to Implement Resolvers in gqlgen
Implement gqlgen resolvers by defining Go structs matching your schema and registering them in resolver.go.
How to Implement Retry with Exponential Backoff in Go
Implement retry with exponential backoff in Go using a loop that doubles the wait time and adds jitter on each failure.
How to Implement Server-Sent Events (SSE) in Go
Implement SSE in Go by setting the text/event-stream header and flushing data to the response writer.
How to Implement Service Discovery in Go
Go lacks native service discovery, requiring external tools like Consul or DNS lookups via the net package to locate services dynamically.
How to Implement the Saga Pattern in Go
Implement the Saga Pattern in Go by defining a coordinator that executes steps sequentially and triggers compensating actions on failure to ensure data consistency.
How to Implement Timeout Middleware in Go
Implement Go timeout middleware by wrapping your handler with a context that enforces a deadline using context.WithTimeout.
How to Implement TLS for TCP Connections in Go
Secure TCP connections in Go by wrapping the net.Conn with tls.Client or tls.Server and performing a handshake.
How to Implement Webhook Handlers in Go
Implement Go webhook handlers by creating an HTTP endpoint that validates signatures and parses JSON payloads securely.
How to Implement WebSockets in Go
Implement WebSockets in Go by using the gorilla/websocket package to upgrade HTTP connections and handle bidirectional data streams.
How to Implement WebSockets in Go with gorilla/websocket
Implement real-time bidirectional communication in Go by upgrading HTTP connections using the gorilla/websocket library.
How to Interop Go with Other Languages via gRPC
Use the official gRPC Go library and protoc compiler to generate code from .proto files for cross-language interoperability.
How to Make an HTTP GET Request in Go
Use the standard `net/http` package's `http.Get()` function for simple requests or `http.Client` with `http.NewRequest()` when you need to customize headers, timeouts, or handle errors more granularly.
How to Make an HTTP POST Request in Go
Send an HTTP POST request in Go using the standard library's http.Post function with JSON data.
How to make HTTP requests
Use the standard library's `net/http` package for most cases, as it provides a robust, dependency-free client with built-in support for timeouts and TLS.
How to Make HTTPS Requests with Custom TLS in Go
Configure a custom http.Transport with a tls.Config to handle specific TLS requirements for HTTPS requests in Go.
How to Parse and Build IP Addresses in Go
Use net.ParseIP to convert strings to IP objects and IP.String() to convert them back.
How to Parse and Manipulate URLs in Go
Parse and manipulate URLs in Go using the net/url package to extract components like host and path.
How to Pass Data to Templates in Go
Pass data to Go templates by creating a struct and executing the template with that struct as the data argument.
How to Read an HTTP Response Body in Go
Read an HTTP response body in Go using io.ReadAll on resp.Body and ensure you defer resp.Body.Close().
How to Read Request Body and Query Parameters in Go
Read query parameters with r.URL.Query() and parse the request body using json.NewDecoder(r.Body) in Go.
How to Retry Failed HTTP Requests in Go
Retry failed HTTP requests in Go by wrapping the client call in a loop with exponential backoff for transient errors.
How to Return JSON Responses from a Go HTTP Server
Set Content-Type to application/json and use json.NewEncoder to write data for JSON responses in Go.
How to Reuse HTTP Connections in Go (Connection Pooling)
Reuse HTTP connections in Go by sharing a single http.Client instance with default Transport settings to enable automatic connection pooling.
How to Run Go Wasm in the Browser
Compile Go to WebAssembly with GOOS=js GOARCH=wasm and serve the output file to run it in a browser.
How to Scale WebSocket Connections in Go
Scale WebSocket connections in Go by running multiple instances behind a load balancer and tuning runtime settings.
How to Send Emails from Go
Send emails in Go using the net/smtp package with a simple SMTP client and plain text message construction.
How to Send Form Data (application/x-www-form-urlencoded) in Go
Encode form data using url.Values and set the Content-Type header to application/x-www-form-urlencoded in Go.
How to Send JSON in an HTTP Request in Go
Send JSON in Go by marshaling your struct to bytes and posting it with the application/json content type.
How to Serve an SPA (React/Vue) from a Go Backend
Serve a React or Vue SPA from Go by mounting a static file server and adding a fallback handler to return index.html for all non-file routes.
How to Serve Embedded Static Files from an HTTP Server
Serve embedded static files in Go by creating an embed.FS variable and passing it to http.FileServer.
How to Serve HTML Pages from a Go HTTP Server
Serve HTML pages from a Go HTTP server using http.FileServer and http.Dir to handle static file requests.
How to Serve Static Files in Go
Serve static files in Go using http.FileServer and http.Dir to map a local directory to a web path.
How to Set a Custom Transport for HTTP in Go
Set a custom HTTP transport in Go by creating a new http.Transport and assigning it to the http.Client's Transport field.
How to Set Headers on an HTTP Request in Go
Set HTTP request headers in Go by calling the Header.Set method on the Request object before executing the request.
How to set HTTP headers
Set HTTP headers in Go by using the Header.Set method on Request or ResponseWriter objects, or control HTTP behavior via GODEBUG environment variables.
How to Set HTTP Response Headers and Status Codes in Go
Set HTTP status codes with WriteHeader and custom headers with Header.Set before writing the response body in Go.
How to Set Timeouts on Network Connections in Go
Configure Go network timeouts using http.Client.Timeout or net.Dialer.Timeout to prevent hanging connections.
How to Set Up gRPC in Go (protoc, protoc-gen-go)
Install protoc and the Go plugins, then run the protoc command with specific flags to generate gRPC service code from your proto files.
How to Stream an HTTP Response Body in Go
Stream HTTP response bodies in Go by reading Response.Body as an io.Reader in a loop or using io.Copy for direct transfer.
How to Stream LLM Responses in Go (Server-Sent Events)
Stream LLM responses in Go using Server-Sent Events by setting the text/event-stream header and flushing the response writer after each chunk.
How to Structure a Go Microservice
Structure a Go microservice by separating handlers, business logic, and configuration into distinct packages and initializing them in main.go.
How to Structure a REST API in Go
Structure a Go REST API by separating handlers, models, and main entry points using the net/http package.
How to Test HTTP Handlers in Go with httptest
Test Go HTTP handlers instantly using httptest.NewRequest and httptest.NewRecorder to mock requests and capture responses.
How to Upload a File with HTTP in Go (Multipart)
Upload a file in Go using the mime/multipart package to create a multipart/form-data HTTP POST request.
How to Use a Proxy for HTTP Requests in Go
Configure Go HTTP clients to use system proxy settings by setting the Transport Proxy to http.ProxyFromEnvironment.
How to Use AWS S3 from Go
Use the official AWS SDK for Go v2 to interact with S3 by installing the module, configuring credentials via environment variables, and calling the `PutObject` or `GetObject` methods.
How to Use Bearer Token / OAuth2 in HTTP Requests in Go
Send Bearer tokens in Go by setting the Authorization header to 'Bearer <token>' or configuring OAuthTokenProvider for database connections.
How to Use Bidirectional Streaming RPC in Go
Implement bidirectional streaming RPC in Go by defining server and client methods that loop through Send and Recv calls on the generated stream interface.
How to Use bubbletea for Terminal UIs in Go
Bubbletea is a Go framework that builds terminal user interfaces using the Model-View-Update (MVU) pattern, where you define a model, handle events in an update function, and render the view.
How to Use buf Instead of protoc for Managing Proto Files
Use `buf` as a drop-in replacement for `protoc` to gain better dependency management, linting, and breaking change detection, while keeping the same output format.
How to Use Chi Middleware and Router Groups
Use Chi middleware by passing it to `r.Use()` to apply it globally or to specific routes, and create router groups with `r.Group()` to organize routes and apply scoped middleware.
How to Use Client Streaming RPC in Go
Client streaming RPCs allow a client to send a stream of messages to the server for a single request, while the server waits to receive all messages before processing and returning a single response.
How to Use Connect-go (Connect Protocol) as a gRPC Alternative
Connect-go is a lightweight, HTTP/2-based RPC framework that offers a simpler, more web-friendly alternative to gRPC by using standard HTTP/2 streaming and JSON/Protobuf encoding without requiring the complex gRPC wire format or metadata handling.
How to Use Context with HTTP Requests for Cancellation and Timeout
Create a context with a timeout or cancel function and pass it to NewRequestWithContext to control HTTP request lifecycles.
How to Use Fiber Middleware and Route Groups
Fiber middleware executes before your route handlers, while route groups allow you to organize routes under a common prefix and share middleware across them.
How to Use Firebase from Go
Use the official Firebase Go SDK to initialize a client with your service account credentials and connect to Firestore, Auth, or Storage.
How to Use Gin with GORM for a Full CRUD API
Build a full CRUD API in Go using Gin for routing and GORM for database operations with a single model and four endpoints.
How to Use go:embed to Embed Templates in Your Binary
Embed template files into your Go binary using the //go:embed directive and embed.FS type.
How to Use Go Kit for Building Microservices
Go Kit is a toolkit for building microservices in Go that provides a consistent, opinionated structure for handling transport, middleware, and service interfaces, though it is now in maintenance mode and not actively developed.
How to Use Google Cloud Pub/Sub from Go
Use the cloud.google.com/go/pubsub library to create topics and subscriptions, then publish and receive messages in Go.
How to Use go-swagger for Swagger Code Generation
Install go-swagger and run the generate command with your spec file to create Go server code.
How to Use Go Wasm with WASI (WebAssembly System Interface)
Go does not support WASI with the js/wasm target; use GOOS=wasip1 GOARCH=wasm to compile for WASI instead.
How to Use gqlgen for GraphQL in Go
Execute Weaviate GraphQL queries in Go by chaining builder methods on the client instance.
How to Use graphql-go for GraphQL in Go
Execute GraphQL queries in Go using the Weaviate client's fluent builder pattern to retrieve vector-based search results.
How to Use GraphQL with GORM in Go
You can integrate GraphQL with GORM by using a GraphQL server library like `gqlgen` to define your schema and resolvers, then wiring those resolvers to call your GORM repository methods for database operations.
How to Use gRPC Deadlines and Timeouts in Go
Set gRPC deadlines and timeouts in Go by creating a context with context.WithTimeout or context.WithDeadline and passing it to your client call.
How to Use gRPC-Gateway for REST and gRPC Together in Go
Use gRPC-Gateway to generate a reverse proxy that automatically translates REST/JSON requests into gRPC calls for a unified Go backend.
How to Use gRPC Health Checking in Go
Use the google.golang.org/grpc/health package to register and manage gRPC health checks in Go.
How to Use gRPC Reflection in Go
Enable gRPC reflection in Go by importing the reflection package and calling reflection.Register on your server instance.
How to Use gRPC with TLS in Go
Configure a Go gRPC server with TLS by loading certificates and setting the server's TLSConfig.
How to Use html/template in Go
Use html/template to parse a template string and execute it with data to generate safe HTML output.
How to Use HTTP Basic Authentication in Go
Use SetBasicAuth to send credentials or BasicAuth to validate them in Go HTTP requests and handlers.
How to Use http.Client with Timeouts in Go
Always configure a `http.Client` with a `Timeout` or a `Transport` containing `DialTimeout`, `TLSHandshakeTimeout`, and `ResponseHeaderTimeout` to prevent your application from hanging indefinitely on slow or unresponsive servers.
How to Use http.Handler and http.HandlerFunc in Go
Use http.HandlerFunc to convert a function into an http.Handler for serving web requests in Go.
How to Use HTTPS/TLS with a Go HTTP Server
Start a Go HTTPS server by calling http.ListenAndServeTLS with your certificate and key file paths.
How to Use Kafka with Go (segmentio/kafka-go, confluent-kafka-go)
Use segmentio/kafka-go for simplicity or confluent-kafka-go for performance when connecting Go applications to Kafka.
How to Use Message Queues (NATS, RabbitMQ, Kafka) in Go
Connect to NATS, RabbitMQ, or Kafka in Go by installing their respective third-party client libraries and using their connection methods.
How to Use Middleware in Echo
Use Echo middleware by passing a wrapper function to e.Use() that executes logic before and after the next handler.
How to Use Middleware in Gin
Register middleware in Gin using the Use method on your router or pass it directly to specific route handlers to execute logic before and after request processing.
How to Use Middleware in Go HTTP Servers
Implement Go HTTP middleware by wrapping http.Handler functions to execute logic before or after the main request handler.
How to Use Middleware Patterns Outside HTTP in Go
Implement middleware outside HTTP in Go by wrapping core handler functions with closures that execute logic before and after the main handler.
How to Use NATS for Messaging in Go
Connect to a NATS server using the Go client library to publish and subscribe to messages on specific subjects.
How to Use net.Conn and net.Listener in Go
Create a net.Listener with net.Listen and use Accept to get a net.Conn for bidirectional data transfer.
How to Use net.Dial and net.DialContext in Go
Use net.Dial for basic connections and net.DialContext to add timeouts and cancellation support to your Go network code.
How to use net http Client
Use http.Client to send requests, customize settings like timeout, and always close response bodies for proper connection reuse.
How to Use nhooyr/websocket (Modern WebSocket Library) in Go
Use `nhooyr/websocket` by importing the package and calling `websocket.Dial` to establish a connection, then use the returned `Conn` object to read and write messages with automatic framing and compression handling.
How to Use oapi-codegen for OpenAPI Code Generation
Use `oapi-codegen` by first installing the CLI tool, then running it against your OpenAPI specification file to generate Go client, server, and model code.
How to Use OAuth2 in Go
Configure the GOAUTH environment variable to enable automatic authentication for private Go modules using netrc, git, or custom commands.
How to Use Partial Templates in Go
Load multiple files with ParseFiles and render specific partials using ExecuteTemplate with the target file name.
How to Use RabbitMQ in Go with amqp091-go
Connect to RabbitMQ in Go by dialing the server URL and publishing messages via an amqp091-go channel.
How to Use ResponseWriter in Go
Use http.ResponseWriter in your handler function to set status codes, headers, and write the response body to the client.
How to Use Route Groups in Gin
Use `r.Group()` to define a common path prefix and middleware for a set of routes, keeping your router configuration DRY and organized.
How to Use Server Streaming RPC in Go
Implement server streaming RPC in Go by defining a stream in your proto file and using the Send method in your server handler to push multiple responses.
How to Use Template Conditionals and Loops in Go
Use if and range directives in Go templates to handle conditionals and loops.
How to Use Template Functions (FuncMap) in Go
Register custom Go functions in a template.FuncMap and pass them to template.New().Funcs() to use them inside your templates.
How to Use Template Inheritance and Layouts in Go
Go lacks native template inheritance; use {{define}} and {{template}} to manually compose reusable layout blocks.
How to Use templ for Type-Safe Go Templates
Generate type-safe Go code from templ files using the templ generate command and import the resulting package.
How to Use text/template in Go
Use text/template to parse a template string and execute it with data to generate dynamic text output.
How to Use the AWS SDK for Go v2
Use the AWS SDK for Go v2 by initializing a configured `Session` or `Config` object with your region and credentials, then creating specific service clients (like S3 or EC2) from that configuration to perform operations.
How to Use the Azure SDK for Go
Use the official Azure SDK for Go modules to interact with Azure services by initializing a client with your credentials and calling service methods.
How to Use the GitHub API in Go (go-github)
Use the go-github library to authenticate and call GitHub API endpoints for automating repository management.
How to Use the Google Cloud Client Libraries for Go
Initialize a Google Cloud client in Go by importing the specific service package, creating a client with context, and setting the GOOGLE_APPLICATION_CREDENTIALS environment variable.
How to Use the New ServeMux in Go 1.22+ (Method Matching, Wildcards)
Use http.NewServeMux() with method-prefixed patterns and wildcard handlers to route HTTP requests in Go 1.22+.
How to Use the OpenAI API in Go
Initialize the OpenAI client in Go with your API key and call CreateChatCompletion to generate text responses.
How to Use the Outbox Pattern in Go for Reliable Messaging
Use the Outbox Pattern to guarantee message delivery by storing messages in a database table within the same transaction as your business logic and processing them asynchronously.
How to Use the Slack API in Go
Use the official `slack-go/slack` library to interact with the Slack API, as it handles authentication, rate limiting, and JSON serialization automatically.
How to Use the Stripe API in Go
Initialize the Stripe Go client with your secret key and call API methods like Charge.New to process payments securely.
How to Use the Twilio API in Go
Use the official `go-twilio` client library to authenticate with your Account SID and Auth Token, then call the appropriate service methods (like `CreateMessage`) to interact with Twilio resources.
How to Use Unary RPC in Go
Unary RPC in Go is a one-request-one-response communication pattern implemented via Protocol Buffers and gRPC.
How to Use Unix Domain Sockets in Go
Create a Unix domain socket in Go using net.ListenUnix with a file path and accept connections via AcceptUnix.
How to Use WebSockets with Redis Pub/Sub for Scaling
Scale WebSockets by having servers publish client messages to a Redis channel and subscribe to it to broadcast updates across all instances.
How to Validate Request Data in Gin
Validate Gin request data by defining validation tags on struct fields and using ShouldBindJSON to automatically check incoming JSON payloads.
How to Write Reusable Middleware for net/http
Write a function that accepts an `http.Handler` and returns a new `http.Handler` wrapping it to execute logic before or after the request.
HTTP/2 and HTTP/3 Support in Go
Go enables HTTP/2 by default and supports HTTP/3 via the x/net/http3 package, with GODEBUG settings available to disable HTTP/2.
JWT authentication in Go
Verify JWT tokens in Go by parsing an X.509 certificate to extract the public key and using the golang-jwt library to validate the signature.
Limitations of Go WebAssembly and Workarounds
Go WebAssembly lacks OS and threading support but works via browser APIs or runtimes like wazero.
Monolith vs Microservices in Go: When to Split
Split a Go monolith into microservices when you need independent scaling or team autonomy, starting by extracting a bounded context into a new module.
net/http vs Gin vs Chi: When You Don't Need a Framework
Use net/http for zero-dependency services, chi for lightweight routing, and avoid heavy frameworks like Gin unless specific features are required.
Protobuf with Go
Generate Go code from Protobuf definitions using the protoc compiler and the protoc-gen-go plugin.
REST API with Chi router
Create a REST API in Go using the Chi router by initializing a mux, defining routes, and starting the HTTP server.
REST API with Echo
You build a REST API with Echo by initializing an `echo.Echo` instance, defining routes with HTTP methods, and attaching handler functions that read request data and write JSON responses.
REST vs GraphQL in Go: When to Use Which
Use REST for simple, cacheable resources and GraphQL for flexible, complex data fetching where clients control the response shape.
Serve static files
Use the standard library's `http.FileServer` wrapped around `http.Dir` to serve static assets directly from your file system.
SSE vs WebSockets in Go: When to Use Which
Use SSE for simple server-to-client streaming with standard HTTP, and WebSockets for full-duplex, real-time bidirectional communication.
The Default HTTP Client Has No Timeout Gotcha
The default Go HTTP client has no timeout, so you must explicitly set a Timeout on the client or use a context to prevent hanging requests.
Validate request bodies
Go requires manual parsing and field checking to validate HTTP request bodies since no built-in validator exists.
WebSockets in Go
Enable WebSockets in Go by using the http.Hijacker interface to take control of the underlying network connection.
What Is gRPC and Why Use It in Go
gRPC is a high-performance RPC framework for Go that uses HTTP/2 and Protocol Buffers for efficient, strongly typed service communication.
What Is Middleware in Go and How to Write It
Go middleware is a function wrapping an http.Handler to intercept and modify requests or responses before they reach the final handler.
What Is the Difference Between html/template and text/template
Use html/template for safe web pages with automatic escaping and text/template for raw text files without escaping.
What Is WebAssembly and How Does Go Support It
WebAssembly is a binary format for running Go in browsers, compiled using GOOS=wasm and GOARCH=wasm with wasmexport/wasmimport directives.