Reference

Programming languages

Choose TypeScript, Go, Rust or C++ and find syntax, everyday APIs, standard libraries and tools in one place.

Scope and conventions

TypeScript/Node, Go 1.23+, Rust 2024 and C++23: from a first CLI to files, JSON, HTTP, concurrency and testing. Complete programs are labeled; other examples identify their surrounding code/imports. Optional libraries and version requirements are named in each entry.

HTTP & services

Make an HTTP request and check the response

Go

The client returns a response for HTTP error statuses; check status and close the response body. Reuse an owned client/transport for repeated calls.

Reusable helper

Imports belong at file scope; getText is a reusable function for an existing Go package. Call getText("https://example.com/") and handle its returned error. io.ReadAll retains the full body; use a size-limited reader for untrusted responses.

main.go
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
import (
    "fmt"
    "io"
    "net/http"
    "time"
)

func getText(address string) (string, error) {
    client := &http.Client{Timeout: 5 * time.Second}
    response, err := client.Get(address)
    if err != nil { return "", err }
    defer response.Body.Close()

    if response.StatusCode < 200 || response.StatusCode >= 300 {
        return "", fmt.Errorf("HTTP %d", response.StatusCode)
    }
    data, err := io.ReadAll(response.Body)
    if err != nil { return "", err }
    return string(data), nil
}

Send a JSON request body

Go

Pass encoded bytes as the request body and set Content-Type. An application owns request cancellation, client timeout and response-body cleanup.

Reusable helper

Imports belong at file scope; postItem is a reusable function. Its caller supplies a context, an http.Client with an appropriate timeout, and the endpoint URL. The target must implement this endpoint.

main.go
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
import (
    "bytes"
    "context"
    "encoding/json"
    "fmt"
    "net/http"
)

func postItem(ctx context.Context, client *http.Client, address, name string) error {
    data, err := json.Marshal(map[string]string{"name": name})
    if err != nil { return err }
    request, err := http.NewRequestWithContext(ctx, "POST",
        address, bytes.NewReader(data))
    if err != nil { return err }
    request.Header.Set("Content-Type", "application/json")
    response, err := client.Do(request)
    if err != nil { return err }
    defer response.Body.Close()
    if response.StatusCode < 200 || response.StatusCode >= 300 {
        return fmt.Errorf("HTTP %d", response.StatusCode)
    }
    return nil
}

A complete small HTTP health endpoint

Go

The standard net/http package can route requests and serve them. ReadHeaderTimeout bounds how long a connection can spend supplying request headers.

Complete program

Go 1.22+ route patterns. Save as main.go in a separate module. Define body limits, other timeout policies and graceful shutdown for your actual workload.

main.go
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
package main

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

func main() {
    mux := http.NewServeMux()
    mux.HandleFunc("GET /health", func(w http.ResponseWriter, r *http.Request) {
        w.Header().Set("Content-Type", "text/plain; charset=utf-8")
        fmt.Fprintln(w, "ok")
    })
    server := &http.Server{Addr: "127.0.0.1:3000", Handler: mux,
        ReadHeaderTimeout: 5 * time.Second}
    log.Fatal(server.ListenAndServe())
}

Set timeouts and cancel HTTP requests: AbortSignal.timeout, http.Client.Timeout, reqwest, cpp-httplib

Go

http.Client.Timeout limits the whole exchange: dialing, TLS, redirects, waiting for headers and reading the body. A context deadline set with http.NewRequestWithContext limits one request, and also everything else that shares the context, such as a database call in the same handler. When both apply, the earlier one wins. The zero-value client, including http.DefaultClient and the package-level http.Get, has no timeout at all.

Complete program

Complete program. httptest.NewServer starts a local server, so it runs offline.

main.go
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
package main

import (
    "context"
    "errors"
    "fmt"
    "io"
    "net"
    "net/http"
    "net/http/httptest"
    "time"
)

func main() {
    // A local server: /fast answers at once, /slow waits until the client gives up.
    server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        if r.URL.Path == "/slow" {
            <-r.Context().Done() // canceled when the client disconnects
            return
        }
        fmt.Fprint(w, "ok")
    }))
    defer server.Close()

    // Client.Timeout bounds the whole exchange: dial, TLS, redirects, headers and body.
    // The zero value (http.DefaultClient) has no timeout at all.
    client := &http.Client{Timeout: 200 * time.Millisecond}

    resp, err := client.Get(server.URL + "/fast")
    if err != nil {
        panic(err)
    }
    body, err := io.ReadAll(resp.Body)
    resp.Body.Close()
    if err != nil || string(body) != "ok" {
        panic(fmt.Sprint("unexpected body: ", string(body), err))
    }

    _, err = client.Get(server.URL + "/slow")
    var netErr net.Error
    if !errors.As(err, &netErr) || !netErr.Timeout() {
        panic(fmt.Sprint("expected a client timeout, got ", err))
    }
    fmt.Println("client timeout:", netErr.Timeout())

    // A context deadline bounds one call, and every other call that shares the context.
    // The earlier of Client.Timeout and the context deadline wins.
    ctx, cancel := context.WithTimeout(context.Background(), 100*time.Millisecond)
    defer cancel()
    req, err := http.NewRequestWithContext(ctx, http.MethodGet, server.URL+"/slow", nil)
    if err != nil {
        panic(err)
    }
    _, err = client.Do(req)
    if !errors.Is(err, context.DeadlineExceeded) {
        panic(fmt.Sprint("expected a deadline, got ", err))
    }
    fmt.Println("context deadline:", errors.Is(err, context.DeadlineExceeded))
}

In practice: create one client per service with a Timeout as a safety net and reuse it, and pass the incoming request's context (r.Context()) or a context.WithTimeout into outbound calls so they are canceled when the caller goes away. Check context.DeadlineExceeded or net.Error.Timeout() to classify the failure.

http.DefaultClient and http.Get never time out; a stalled server holds the goroutine forever.

Finer-grained limits live on http.Transport: DialContext (via net.Dialer.Timeout), TLSHandshakeTimeout, ResponseHeaderTimeout and IdleConnTimeout.

Always close resp.Body, even when you do not read it, or the connection cannot be reused.

Serve a small JSON API with routes and path parameters: node:http, ServeMux patterns, axum, cpp-httplib

Go

Since Go 1.22, http.ServeMux patterns take an optional method and {name} wildcards: "GET /items/{id}" matches GET (and HEAD) requests, and r.PathValue("id") returns the segment. {path...} matches the rest of the path, and the most specific pattern wins regardless of registration order. A path that matches with the wrong method gets 405 Method Not Allowed with an Allow header, automatically.

Complete program

Complete program (Go 1.22+). Serves on a free local port, calls itself and exits.

main.go
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
package main

import (
    "encoding/json"
    "fmt"
    "net"
    "net/http"
    "strconv"
    "strings"
    "sync"
)

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

type store struct {
    mu     sync.Mutex
    items  map[int]Item
    nextID int
}

func writeJSON(w http.ResponseWriter, status int, value any) {
    w.Header().Set("Content-Type", "application/json")
    w.WriteHeader(status)
    json.NewEncoder(w).Encode(value)
}

func (s *store) getItem(w http.ResponseWriter, r *http.Request) {
    id, err := strconv.Atoi(r.PathValue("id")) // the {id} wildcard from the pattern
    if err != nil {
        writeJSON(w, http.StatusBadRequest, map[string]string{"error": "id must be a number"})
        return
    }
    s.mu.Lock()
    item, ok := s.items[id]
    s.mu.Unlock()
    if !ok {
        writeJSON(w, http.StatusNotFound, map[string]string{"error": "not found"})
        return
    }
    writeJSON(w, http.StatusOK, item)
}

func (s *store) createItem(w http.ResponseWriter, r *http.Request) {
    var input struct {
        Name string `json:"name"`
    }
    r.Body = http.MaxBytesReader(w, r.Body, 64<<10)
    if err := json.NewDecoder(r.Body).Decode(&input); err != nil || input.Name == "" {
        writeJSON(w, http.StatusBadRequest, map[string]string{"error": "name is required"})
        return
    }
    s.mu.Lock()
    item := Item{ID: s.nextID, Name: input.Name}
    s.items[item.ID] = item
    s.nextID++
    s.mu.Unlock()
    writeJSON(w, http.StatusCreated, item)
}

func main() {
    s := &store{items: map[int]Item{1: {1, "kettle"}}, nextID: 2}

    // Go 1.22+ patterns: an optional method, then a path with {name} wildcards.
    mux := http.NewServeMux()
    mux.HandleFunc("GET /items/{id}", s.getItem)
    mux.HandleFunc("POST /items", s.createItem)

    listener, err := net.Listen("tcp", "127.0.0.1:0") // port 0: any free port
    if err != nil {
        panic(err)
    }
    defer listener.Close()
    go http.Serve(listener, mux)
    base := "http://" + listener.Addr().String()

    resp, err := http.Post(base+"/items", "application/json", strings.NewReader(`{"name":"mug"}`))
    if err != nil {
        panic(err)
    }
    var created Item
    json.NewDecoder(resp.Body).Decode(&created)
    resp.Body.Close()
    if resp.StatusCode != http.StatusCreated || created != (Item{2, "mug"}) {
        panic(fmt.Sprint("create failed: ", resp.Status, created))
    }

    resp, err = http.Get(base + "/items/2")
    if err != nil {
        panic(err)
    }
    var fetched Item
    json.NewDecoder(resp.Body).Decode(&fetched)
    resp.Body.Close()
    if fetched != created {
        panic(fmt.Sprint("get returned ", fetched))
    }

    // The mux answers a known path with the wrong method itself: 405 plus an Allow header.
    req, _ := http.NewRequest(http.MethodDelete, base+"/items/2", nil)
    resp, err = http.DefaultClient.Do(req)
    if err != nil {
        panic(err)
    }
    resp.Body.Close()
    if resp.StatusCode != http.StatusMethodNotAllowed {
        panic(resp.Status)
    }
    fmt.Println("GET /items/2 ->", fetched, "| DELETE ->", resp.StatusCode, "Allow:", resp.Header.Get("Allow"))
}

In practice: the standard mux is enough for most JSON APIs; reach for chi or similar only for middleware groups. Decode bodies with json.NewDecoder over http.MaxBytesReader, and write the Content-Type header before WriteHeader.

Method patterns need Go 1.22+ and a go.mod with go 1.22 or later; with an older go line the mux keeps the old literal-path behavior (GODEBUG httpmuxgo121).

Headers must be set before WriteHeader or the first Write; later changes are ignored.

Conflicting patterns make HandleFunc panic at registration: "GET /items/{id}" and "/items/new" conflict because one is narrower on method and the other on path. Give both a method to fix it.

Stop a server cleanly: server.close, http.Server.Shutdown, with_graceful_shutdown, server.stop

Go

signal.NotifyContext returns a context that is canceled when one of the listed signals arrives. http.Server.Shutdown closes the listeners, closes idle connections and waits for active requests to finish, up to the deadline of the context you pass it; Serve returns http.ErrServerClosed as soon as Shutdown starts, which is the normal case, not an error. Server.Close is the forced version.

Complete program

Complete program (Unix: it sends itself SIGTERM with syscall.Kill).

main.go
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
package main

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

func main() {
    // ctx is canceled when SIGINT (Ctrl-C) or SIGTERM arrives.
    ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
    defer stop()

    started := make(chan struct{})
    mux := http.NewServeMux()
    mux.HandleFunc("GET /", func(w http.ResponseWriter, r *http.Request) {
        close(started)
        time.Sleep(300 * time.Millisecond) // still running when the signal arrives
        fmt.Fprint(w, "finished")
    })
    server := &http.Server{Handler: mux, ReadHeaderTimeout: 5 * time.Second}

    listener, err := net.Listen("tcp", "127.0.0.1:0")
    if err != nil {
        panic(err)
    }
    serveErr := make(chan error, 1)
    go func() { serveErr <- server.Serve(listener) }()

    // A client request that is in flight during shutdown.
    reply := make(chan string, 1)
    go func() {
        resp, err := http.Get("http://" + listener.Addr().String() + "/")
        if err != nil {
            reply <- err.Error()
            return
        }
        defer resp.Body.Close()
        body, _ := io.ReadAll(resp.Body)
        reply <- string(body)
    }()

    // For the demo, send ourselves SIGTERM, as a process manager or Kubernetes would (Unix).
    <-started
    syscall.Kill(os.Getpid(), syscall.SIGTERM)

    <-ctx.Done()
    stop() // restore default handling: a second Ctrl-C now kills the process
    fmt.Println("signal received, draining")

    // Shutdown closes the listener, then waits for active requests up to the deadline.
    shutdownCtx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
    defer cancel()
    if err := server.Shutdown(shutdownCtx); err != nil {
        fmt.Println("forced shutdown:", err)
        server.Close()
    }
    // Serve returns ErrServerClosed as soon as Shutdown starts; that is the normal case.
    if err := <-serveErr; !errors.Is(err, http.ErrServerClosed) {
        panic(err)
    }
    if got := <-reply; got != "finished" {
        panic("in-flight request was cut off: " + got)
    }
    fmt.Println("in-flight request completed; exiting")
}

In practice: run Serve in a goroutine, wait for the signal context, call stop() so a second Ctrl-C kills the process, then Shutdown with a timeout and fall back to Close if it expires. Use RegisterOnShutdown or your own cleanup for hijacked or WebSocket connections, which Shutdown does not track.

Do not exit main while Shutdown is still waiting: once main returns, in-flight requests are killed with it.

Handlers should watch r.Context(); BaseContext lets you derive request contexts from one that you cancel during shutdown.

syscall.Kill is Unix-only; on Windows, os.Interrupt is the signal you can receive.

Build URLs and query strings safely: URLSearchParams, url.Values, the url crate, Boost.URL

Go

url.Values (a map[string][]string) builds a query: Set replaces, Add appends a repeated key, and Encode escapes everything and sorts by key. url.URL assembles scheme, host, path and RawQuery; url.PathEscape encodes one path segment and url.QueryEscape one query value. Parse and Query decode again.

Complete program

Complete program.

main.go
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
package main

import (
    "fmt"
    "net/url"
)

func main() {
    term, userName := "rock & roll", "ann/marie"

    // url.Values is map[string][]string; Encode escapes keys and values and sorts by key.
    query := url.Values{}
    query.Set("q", term)
    query.Add("tag", "a+b")
    query.Add("tag", "c d")
    query.Set("page", "2")

    u := url.URL{
        Scheme:   "https",
        Host:     "api.example.com",
        // Path is the decoded form; RawPath keeps the '/' in the name encoded as %2F.
        Path:     "/v1/users/" + userName + "/search",
        RawPath:  "/v1/users/" + url.PathEscape(userName) + "/search",
        RawQuery: query.Encode(),
    }
    want := "https://api.example.com/v1/users/ann%2Fmarie/search?page=2&q=rock+%26+roll&tag=a%2Bb&tag=c+d"
    if u.String() != want {
        panic(u.String())
    }

    // Parsing decodes again.
    parsed, err := url.Parse(u.String())
    if err != nil {
        panic(err)
    }
    values := parsed.Query()
    if values.Get("q") != term || len(values["tag"]) != 2 || values["tag"][0] != "a+b" {
        panic(fmt.Sprint(values))
    }

    // QueryEscape is form encoding (space -> '+'); PathEscape uses %20.
    fmt.Println(url.QueryEscape("c d"), url.PathEscape("c d"))
    fmt.Println(u.String())
}

In practice: build the query with url.Values and assign Encode() to RawQuery, rather than formatting strings. For a segment that may contain /, set both Path (decoded) and RawPath (escaped), or call url.JoinPath(base, url.PathEscape(segment)): JoinPath expects elements that are already escaped and returns an error for a stray %. It also cleans . and .. elements (PathEscape leaves them as they are), so reject those segments first or set Path and RawPath as the program does.

Values.Encode sorts keys; if an API needs a specific parameter order, build RawQuery yourself from escaped pairs.

QueryEscape turns a space into +, PathEscape into %20. Using QueryEscape for a path segment produces a literal + in the path.

u.Query() returns a fresh copy: changing it does nothing until you assign u.RawQuery = q.Encode().