Go Programming Language: Getting Started
You've got a PHP or Node service that does one slow thing, like calling three upstream APIs per request or chewing through a queue, and it's starting to eat memory and servers. You could tune it, or you could rewrite that one piece in something that compiles to a small binary and handles concurrency without a pile of callbacks or worker processes. That's usually the moment people start looking at Go.
This post covers what you need to get going: installing Go and setting up a module, the core syntax (variables, functions, structs, interfaces), goroutines and channels, and a small REST API built with nothing but the standard library. At the end I'll go through what I'd check before putting a Go service in production, and when I wouldn't bother with Go at all.
A lot of the tooling you probably already run is written in Go: Docker, Kubernetes, Terraform, Hugo, Caddy, Prometheus, and CockroachDB. Go was created at Google in 2009 by Robert Griesemer, Rob Pike, and Ken Thompson, mainly to make large server codebases faster to build and easier to maintain than C++ or Java.
Why Learn Go?
The thing I like most is deployment. Go compiles to a single native binary with no runtime to install, so you can copy one file to a Linux server and run it. No Node.js version on the box, no JVM mismatch, no Python virtualenv.
The other reasons people pick it:
- Compiled Performance: Go compiles to machine code and has a garbage collector, so you get good speed without managing memory by hand
- Goroutines: lightweight threads managed by the Go runtime. Running tens or hundreds of thousands of them in one process is normal
- Small Language: there isn't much syntax to learn. Most developers coming from PHP or JavaScript can write useful code within a week or two
- Fast Compilation: even big projects usually build in seconds, which keeps the edit and run loop short
- Single Binary Deployment: cross-compile for another OS or architecture with one environment variable
- Standard Library: HTTP server and client, JSON, crypto, testing, and profiling all ship with the language
| Feature | Go | Python | Node.js |
|---|---|---|---|
| Execution | Compiled (native binary) | Interpreted | JIT (V8 engine) |
| Performance | Fast (native code) | Moderate | Good |
| Concurrency Model | Goroutines + Channels | GIL limits true threading | Single-threaded event loop |
| Memory Usage | Very low | High | Moderate |
| Deployment | Single static binary | Requires Python runtime | Requires Node.js |
| Type System | Static, inferred | Dynamic | Dynamic (TypeScript opt-in) |
| Learning Curve | Low-Moderate | Very Low | Low |
Installation and Your First Program
The official site has prebuilt installers for Linux, macOS, and Windows, so setup takes a few minutes.
Download and Install Go
Visit go.dev/dl and download the installer for your OS. On macOS/Linux you can also use a package manager.
# macOS (Homebrew)
brew install go
# Ubuntu/Debian
sudo apt install golang-go
# Arch Linux
sudo pacman -S go
# Verify installation
go version
# go version go1.22.3 linux/amd64
On Ubuntu LTS, apt install golang-go often gives you a Go version that's a year or more old. When you clone a project whose go.mod says go 1.22, an old toolchain fails with something like go: go.mod requires go >= 1.22. If you see that, install the tarball from go.dev/dl instead, and always check go version first.
Create a New Module
Go uses modules (introduced in Go 1.11) for dependency management. Every project starts with go mod init.
mkdir hello-go && cd hello-go
go mod init github.com/yourname/hello-go
Write and Run Your First Program
Every Go program lives in a package. The executable entry point is always package main with a main() function.
package main
import "fmt"
func main() {
fmt.Println("Hello, Go!")
fmt.Printf("Version: %s\n", "1.22")
}
# Run directly (compile + execute)
go run main.go
# Build a binary
go build -o hello-go .
./hello-go
# Output:
# Hello, Go!
# Version: 1.22
Since Go 1.11 you use Go Modules, so you can create projects anywhere on your filesystem, not just under a special GOPATH directory. The go.mod file tracks your module name and dependencies, similar to package.json in Node.js or composer.json in PHP.
Core Language Features
Variables, Types, and Constants
Every variable has a type that's known at compile time, but you won't write most of them yourself. The compiler infers types from assigned values using the := short declaration operator, so you rarely need to write explicit types.
package main
import "fmt"
func main() {
// Explicit type declaration
var name string = "Gopher"
var age int = 5
// Short declaration (type inferred)
language := "Go"
version := 1.22
// Multiple assignment
x, y := 10, 20
x, y = y, x // swap, no temp variable needed
// Constants: evaluated at compile time
const Pi = 3.14159
const MaxConn = 100
// Zero values: Go initializes all variables
var count int // 0
var enabled bool // false
var message string // ""
fmt.Printf("%s %s %.2f, age %d\n", language, name, version, age)
fmt.Printf("x=%d y=%d count=%d enabled=%v msg=%q\n",
x, y, count, enabled, message)
}
Functions and Multiple Return Values
Functions can return more than one value, and that's how Go does error handling. You return a result and an error, and the caller checks the error right there. There are no exceptions and no try/catch. It feels verbose for the first week, then you start to appreciate that every failure path is visible in the code.
package main
import (
"errors"
"fmt"
"math"
)
// Multiple return values: result + error
func divide(a, b float64) (float64, error) {
if b == 0 {
return 0, errors.New("cannot divide by zero")
}
return a / b, nil
}
// Named return values (useful for documentation)
func circleMetrics(r float64) (area, circumference float64) {
area = math.Pi * r * r
circumference = 2 * math.Pi * r
return // "naked" return uses named values
}
// Variadic function: accepts any number of int arguments
func sum(nums ...int) int {
total := 0
for _, n := range nums {
total += n
}
return total
}
func main() {
result, err := divide(10, 3)
if err != nil {
fmt.Println("Error:", err)
return
}
fmt.Printf("10 / 3 = %.4f\n", result) // 3.3333
area, circ := circleMetrics(5)
fmt.Printf("Circle r=5: area=%.2f circ=%.2f\n", area, circ)
fmt.Println("Sum:", sum(1, 2, 3, 4, 5)) // 15
}
Structs and Interfaces
There are no classes or inheritance. You get structs for data and interfaces for behavior, and that covers most of what you'd use classes for in PHP. Interface satisfaction is implicit: if a type has all the methods an interface requires, it satisfies that interface automatically. No implements keyword needed.
package main
import "fmt"
// Struct definition
type User struct {
ID int
Name string
Email string
IsActive bool
}
// Method with pointer receiver (can modify the struct)
func (u *User) Deactivate() {
u.IsActive = false
}
// Method with value receiver (read-only)
func (u User) String() string {
status := "active"
if !u.IsActive {
status = "inactive"
}
return fmt.Sprintf("User{id=%d name=%q status=%s}", u.ID, u.Name, status)
}
// Constructor function pattern
func NewUser(id int, name, email string) *User {
return &User{
ID: id,
Name: name,
Email: email,
IsActive: true,
}
}
// Interface: satisfied implicitly by any type with these methods
type Notifier interface {
Notify(message string) error
}
type EmailNotifier struct {
SMTPHost string
}
// EmailNotifier satisfies Notifier without declaring "implements"
func (e EmailNotifier) Notify(message string) error {
fmt.Printf("[Email via %s] %s\n", e.SMTPHost, message)
return nil
}
func sendAlert(n Notifier, msg string) {
if err := n.Notify(msg); err != nil {
fmt.Println("Notification failed:", err)
}
}
func main() {
u := NewUser(1, "Alice", "alice@example.com")
fmt.Println(u) // User{id=1 name="Alice" status=active}
u.Deactivate()
fmt.Println(u) // User{id=1 name="Alice" status=inactive}
notifier := EmailNotifier{SMTPHost: "smtp.example.com"}
sendAlert(notifier, "Server memory above 90%")
}
Concurrency with Goroutines and Channels
Put go in front of a function call and it runs concurrently with everything else. That's a goroutine. OS threads typically reserve around 1MB of stack each, while a goroutine starts at about 2KB and grows as needed. The Go runtime schedules them onto a small pool of real threads, so spawning hundreds of thousands in one program is fine.
Channels are how goroutines pass data to each other safely. The Go proverb for this is "Do not communicate by sharing memory; share memory by communicating."
Goroutines send results to a shared channel; main() reads them in order
package main
import (
"fmt"
"time"
)
func fetchData(url string, ch chan<- string) {
// Simulates an HTTP call
time.Sleep(100 * time.Millisecond)
ch <- fmt.Sprintf("response from %s", url)
}
func main() {
urls := []string{
"https://api.service-a.com/users",
"https://api.service-b.com/orders",
"https://api.service-c.com/products",
}
// Buffered channel: holds up to 3 messages without blocking
ch := make(chan string, len(urls))
// Launch all requests concurrently
for _, url := range urls {
go fetchData(url, ch)
}
// Collect all results (~100ms total, not ~300ms sequential)
for range urls {
fmt.Println(<-ch)
}
}
Synchronizing with WaitGroups
When you need to wait for a group of goroutines to finish without collecting return values through a channel, sync.WaitGroup is the idiomatic choice.
package main
import (
"fmt"
"sync"
"time"
)
func processItem(id int, wg *sync.WaitGroup) {
defer wg.Done() // signal completion even if function panics
time.Sleep(50 * time.Millisecond)
fmt.Printf("Processed item %d\n", id)
}
func main() {
var wg sync.WaitGroup
items := []int{1, 2, 3, 4, 5}
for _, id := range items {
wg.Add(1) // increment counter before launching
go processItem(id, &wg)
}
wg.Wait() // block until all Done() calls bring counter to 0
fmt.Println("All items processed")
}
The select Statement
select waits on several channel operations at once and runs whichever case is ready first. The most common use is a timeout, like this:
package main
import (
"fmt"
"time"
)
func slowOperation(ch chan string) {
time.Sleep(2 * time.Second)
ch <- "operation complete"
}
func main() {
ch := make(chan string)
go slowOperation(ch)
// Wait for result OR timeout after 1 second
select {
case result := <-ch:
fmt.Println("Got:", result)
case <-time.After(1 * time.Second):
fmt.Println("Operation timed out!")
}
}
A goroutine that is blocked forever waiting on a channel is a goroutine leak. It holds memory and is never garbage collected. The select example above actually has one: after the timeout, slowOperation is stuck forever on ch <- ... because nobody reads ch any more. Giving the channel a buffer of 1 fixes it. Make sure every goroutine you launch has a clear exit path. Use context.WithCancel or context.WithTimeout to propagate cancellation signals to goroutines that perform long-running or I/O-bound work.
Building a REST API
The HTTP server in net/http is the same one many Go services run in production. For small services and internal APIs you often don't need a framework. If you want nicer routing, middleware chains, or request binding, Gin or Chi add very little on top.
JSON Handling and Struct Tags
Go uses struct tags to control JSON (de)serialization. The encoding/json package uses reflection to read these tags at runtime.
package main
import (
"encoding/json"
"fmt"
)
type User struct {
ID int `json:"id"`
Name string `json:"name"`
Email string `json:"email"`
Password string `json:"-"` // omit from JSON output
CreatedAt string `json:"created_at,omitempty"` // omit if empty
}
func main() {
u := User{ID: 1, Name: "Alice", Email: "alice@example.com", Password: "secret"}
// Marshal (struct -> JSON)
data, _ := json.Marshal(u)
fmt.Println(string(data))
// {"id":1,"name":"Alice","email":"alice@example.com"}
// Note: Password is omitted, CreatedAt is omitted (empty)
// Unmarshal (JSON -> struct)
payload := `{"id":2,"name":"Bob","email":"bob@example.com"}`
var newUser User
json.Unmarshal([]byte(payload), &newUser)
fmt.Printf("Decoded: %+v\n", newUser)
}
Complete REST API Example
Here's a working in-memory REST API for a users resource with only the standard library. It handles GET /users, POST /users, and GET /users/{id}.
package main
import (
"encoding/json"
"fmt"
"log"
"net/http"
"strconv"
"strings"
"sync"
)
type User struct {
ID int `json:"id"`
Name string `json:"name"`
Email string `json:"email"`
}
// Thread-safe in-memory store
var (
mu sync.RWMutex
users = []User{
{ID: 1, Name: "Alice Johnson", Email: "alice@example.com"},
{ID: 2, Name: "Bob Smith", Email: "bob@example.com"},
}
nextID = 3
)
func respondJSON(w http.ResponseWriter, status int, v any) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(status)
json.NewEncoder(w).Encode(v)
}
// GET /users lists all users
// POST /users creates a user
func usersHandler(w http.ResponseWriter, r *http.Request) {
switch r.Method {
case http.MethodGet:
mu.RLock()
defer mu.RUnlock()
respondJSON(w, http.StatusOK, users)
case http.MethodPost:
var u User
if err := json.NewDecoder(r.Body).Decode(&u); err != nil {
respondJSON(w, http.StatusBadRequest, map[string]string{"error": "invalid JSON"})
return
}
mu.Lock()
u.ID = nextID
nextID++
users = append(users, u)
mu.Unlock()
respondJSON(w, http.StatusCreated, u)
default:
respondJSON(w, http.StatusMethodNotAllowed, map[string]string{"error": "method not allowed"})
}
}
// GET /users/{id} returns a single user by ID
func userHandler(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodGet {
respondJSON(w, http.StatusMethodNotAllowed, map[string]string{"error": "method not allowed"})
return
}
idStr := strings.TrimPrefix(r.URL.Path, "/users/")
id, err := strconv.Atoi(idStr)
if err != nil || id < 1 {
respondJSON(w, http.StatusBadRequest, map[string]string{"error": "invalid id"})
return
}
mu.RLock()
defer mu.RUnlock()
for _, u := range users {
if u.ID == id {
respondJSON(w, http.StatusOK, u)
return
}
}
respondJSON(w, http.StatusNotFound, map[string]string{"error": "user not found"})
}
func main() {
mux := http.NewServeMux()
mux.HandleFunc("/users", usersHandler)
mux.HandleFunc("/users/", userHandler)
fmt.Println("Server running at http://localhost:8080")
log.Fatal(http.ListenAndServe(":8080", mux))
}
# List all users
curl http://localhost:8080/users
# [{"id":1,"name":"Alice Johnson","email":"alice@example.com"},...]
# Get user by ID
curl http://localhost:8080/users/1
# {"id":1,"name":"Alice Johnson","email":"alice@example.com"}
# Create a new user
curl -X POST http://localhost:8080/users \
-H "Content-Type: application/json" \
-d '{"name":"Carol White","email":"carol@example.com"}'
# {"id":3,"name":"Carol White","email":"carol@example.com"}
Choosing a Web Framework
Since Go 1.22, http.ServeMux understands patterns like "GET /users/{id}" and gives you the value via r.PathValue("id"), which removes the manual TrimPrefix parsing above. That covers a lot of what people used to reach for a router for. Frameworks still help with request binding, validation, and middleware.
| Framework | GitHub Stars (approx.) | Style | Best For |
|---|---|---|---|
| net/http (stdlib) | Built-in | Minimal, explicit | Microservices, learning Go |
| Gin | 78k+ | Express-like, fast | REST APIs, high-throughput services |
| Echo | 29k+ | Middleware-centric | Complex middleware chains |
| Fiber | 33k+ | Express-inspired, very fast | High-performance edge APIs |
| Chi | 17k+ | Idiomatic Go, stdlib-compatible | Teams that value Go conventions |
Go CLI Commands You'll Use Daily
| Command | Purpose |
|---|---|
go run main.go | Compile and run a program |
go build -o app . | Build a binary |
go test ./... | Run all tests recursively |
go test -race ./... | Run tests with race detector |
go get github.com/gin-gonic/gin | Add a dependency |
go mod tidy | Remove unused dependencies |
go fmt ./... | Format all Go source files |
go vet ./... | Report suspicious code patterns |
GOOS=linux go build . | Cross-compile for Linux |
go doc fmt.Println | View documentation offline |
What to Check Before Going to Production
The API above is fine for learning, but I wouldn't deploy it as is. These are the gaps I'd close first:
Production Checklist
- Server timeouts:
http.ListenAndServehas no read or write timeouts, so slow clients can hold connections open forever. Create anhttp.Serverand setReadHeaderTimeout,ReadTimeout, andWriteTimeout - Request body size: wrap the body with
http.MaxBytesReaderbefore decoding JSON, or one large POST can eat your memory - Ignored errors: the
json.Unmarshalcall in models.go throws its error away. In real code, check it, and wrap errors withfmt.Errorf("decode user: %w", err)so logs tell you where they came from - Cancellation: pass
r.Context()into database and HTTP calls so work stops when the client disconnects - Race detector: run
go test -race ./...in CI. Shared state like theusersslice is exactly where data races hide - Graceful shutdown: catch SIGTERM and call
server.Shutdown(ctx)so in-flight requests finish during deploys
When I'd Use Go (and When I Wouldn't)
I'd pick Go for network services that spend most of their time waiting on other systems: API gateways, webhook receivers, queue workers, small internal APIs. CLI tools are another good fit, since shipping one binary to every OS beats asking people to install a runtime.
I wouldn't use it for a typical CRUD web app with an admin panel, auth, mail, and queued jobs. Laravel or Rails give you all of that out of the box, and in Go you'd be assembling and maintaining it yourself. It's also a weak choice for data science or ML work, where Python's libraries have no real equivalent. And if your team is all PHP or JavaScript and the current service isn't actually struggling, a rewrite costs more than it saves. Start with one small, well-bounded service, and keep the code flat and boring. That's what idiomatic Go looks like anyway.