Learning objectives
After reading this article you will be able to:
- Write a net/http API that reads PORT and listens on 0.0.0.0
- Cross-compile a static Linux binary from any machine
- Shut down without dropping requests and keep memory use in check
On this page
- What do you need before you start?
- How do you write a production-ready Go API?
- How does graceful shutdown work in Go?
- How do you build a static binary for the server?
- How much memory does a Go API use, and how do you control it?
- How do you check that the deploy worked?
- What are the most common errors?
- How to do this on Square Cloud
- FAQs
Go is one of the most direct languages to take to production: the compiler produces a single executable, with no runtime to install on the server, and the standard library already includes a complete HTTP server. What usually goes wrong is everything around the code: the port, the network interface, the platform the binary was built for and what happens when the process gets the stop signal.
This guide builds an API with nothing but net/http, cross-compiles it for Linux, handles shutdown and shows how to verify the deploy and fix the usual errors. For the big picture of shipping any backend, see how to host an API.
What do you need before you start?#
- Go on your machine, a recent release. The
godirective ingo.modis the module's minimum version: with the defaultGOTOOLCHAIN=auto, an older toolchain downloads the requested release before building; withGOTOOLCHAIN=local, it refuses the module. - A module:
go mod init example.com/myapicreatesgo.mod, andgo.sumstores the hashes of your dependencies. Both belong in the repository. - Somewhere to run it: a Linux VPS, a container or a hosting platform. If you're still comparing, see VPS vs cloud platform.
How do you write a production-ready Go API?#
This main.go uses only the standard library. It reads the port from the environment, sets timeouts, exposes a health endpoint and shuts down cleanly when it gets the stop signal:
package main
import (
"context"
"encoding/json"
"errors"
"log"
"net/http"
"os"
"os/signal"
"syscall"
"time"
)
func main() {
port := os.Getenv("PORT")
if port == "" {
port = "8080"
}
mux := http.NewServeMux()
mux.HandleFunc("GET /health", func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(map[string]string{"status": "ok"})
})
mux.HandleFunc("GET /users/{id}", func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(map[string]string{"id": r.PathValue("id")})
})
srv := &http.Server{
Addr: "0.0.0.0:" + port,
Handler: mux,
ReadHeaderTimeout: 5 * time.Second,
ReadTimeout: 15 * time.Second,
WriteTimeout: 30 * time.Second,
IdleTimeout: 60 * time.Second,
}
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
defer stop()
go func() {
log.Printf("listening on %s", srv.Addr)
if err := srv.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) {
log.Fatalf("server: %v", err)
}
}()
<-ctx.Done()
stop()
log.Println("signal received, shutting down")
shutdownCtx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
defer cancel()
if err := srv.Shutdown(shutdownCtx); err != nil {
log.Printf("forced shutdown: %v", err)
}
log.Println("stopped")
}Test it locally on another port, the way the environment would run it:
PORT=9090 go run .
curl -i http://localhost:9090/health0.0.0.0and the port: listening onlocalhost:8080(or127.0.0.1) only accepts connections from inside the same machine or container, so the proxy in front never reaches the process. An address with no host, such as:8080, also listens on every interface;0.0.0.0just makes it explicit.PORT: the environment decides the port, and8080is only a development default. See what environment variables are.- Timeouts: an
http.Serverwithout them waits forever on slow clients.ReadHeaderTimeoutcaps how long reading the headers can take, andWriteTimeoutcuts long responses: raise it, or run a separate server, for streaming and SSE routes. /health: an endpoint that returns200without touching the database lets an uptime monitor and a load balancer know the process is up.
How does graceful shutdown work in Go?#
When a process is stopped (a restart, a new deploy, docker stop, systemctl stop), the system sends SIGTERM and, if the process doesn't exit within a grace period, SIGKILL. Without handling, the os/signal docs say SIGTERM makes a Go program exit right away, and in-flight requests get their connection cut.
In the example, signal.NotifyContext returns a context that is canceled when SIGINT or SIGTERM arrives. From there, srv.Shutdown closes the listeners, closes idle connections and waits for active ones to finish. Two details from the net/http docs matter:
- As soon as
Shutdownis called,ListenAndServereturnshttp.ErrServerClosedimmediately. That's why the code ignores that error andmainwaits forShutdownto return instead of exiting. Shutdowndoesn't close or wait for hijacked connections such as WebSockets. Notify them withsrv.RegisterOnShutdownand close them yourself.
The context.WithTimeout deadline, 20 seconds in the example, has to be shorter than the time the environment waits before SIGKILL (for docker stop, the default is 10 seconds, and it's configurable). Calling stop() right after the signal restores the default behavior: a second Ctrl+C exits at once.
How do you build a static binary for the server?#
Go cross-compiles with no extra tooling: the GOOS and GOARCH variables pick the target OS and architecture, and go tool dist list prints every supported pair.
CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -trimpath -ldflags="-s -w" -o myapi .CGO_ENABLED=0: turns cgo off. The docs say it's already off when cross-compiling, but setting it explicitly gives the same result on any machine. Without cgo, the binary doesn't depend on the system's libc and runs even on minimal images.GOARCH:amd64for most x86 servers,arm64for ARM servers. A binary for the wrong architecture fails withexec format error.-trimpathand-ldflags="-s -w": strip your machine's file paths, the symbol table and debug information from the executable, so the file is smaller.
On a VPS, the binary becomes a systemd service, which restarts it if it crashes and sends SIGTERM when stopping it.
go.mod, go.sum and vendoring#
Whatever compiles your code, on the server or in CI, downloads the dependencies listed in go.mod and checks each one against go.sum. Run go mod tidy before every commit: it adds missing requirements, removes unused ones and fixes go.sum.
If the build environment has no internet access, or you want the dependencies inside the repository, go mod vendor copies every needed package into a vendor folder. In a current module, when that folder exists, the go command uses it by default, as if you had passed -mod=vendor.
How much memory does a Go API use, and how do you control it?#
A Go process holds the live heap, plus the headroom the garbage collector lets it grow before each cycle, plus goroutine stacks. Usage depends on what each request allocates, so measure under real traffic before picking a machine size. Two environment variables tune the runtime without code changes:
GOMEMLIMIT: a soft memory limit for the runtime, with suffixes such asMiBandGiB. Near it, the GC runs more often to stay below. For a container with fixed memory, the GC guide suggests leaving 5% to 10% of headroom for memory the runtime can't see: with 512 MB, something close toGOMEMLIMIT=460MiB. It isn't a hard cap. If the live heap goes past the limit, the GC runs back-to-back cycles and the app slows down; the guide describes it as trading an out-of-memory risk for a slowdown risk.GOMAXPROCS: how many threads run Go code at once. In recent releases on Linux, the runtime already honors the container's cgroup CPU limit when picking the default, and setting the variable by hand turns that adjustment off.
To estimate how much RAM to reserve, see how to size RAM and CPU, and for what happens when it runs out, out-of-memory errors.
How do you check that the deploy worked?#
- Logs: look for the
listening on 0.0.0.0:...line with the environment's port. If it showslocalhostor127.0.0.1, outside traffic can't get in. - Health endpoint:
curl -i https://your-domain/healthshould return200and{"status":"ok"}. - Shutdown: restart the app and check that the log shows
signal received, shutting downfollowed bystopped. Without the second line, the process was killed before it finished. - Memory: watch usage after a few minutes of load, not just at boot.
What are the most common errors?#
listen tcp 0.0.0.0:8080: bind: address already in use: another process, or an old instance of your API, already holds the port. Stop the old process or use the port the environment sets inPORT(more in EADDRINUSE and 502 after a deploy).- The log says it started, but outside connections are refused: the server listens on
localhost. Use0.0.0.0inAddr. exec format error: the binary was built for anotherGOOSorGOARCH. Rebuild for the server's platform.missing go.sum entry for module providing package ...:go.sumis out of date. Rungo mod tidyand commitgo.sum.- The build rejects the module because of the Go version: the toolchain on the server or in CI is older than the
godirective ingo.modand couldn't download the requested release (withGOTOOLCHAIN=localor no network access). Upgrade the toolchain or align the directive with the release you use. - The process disappears with no error in the log: it was killed for running out of memory, usually with exit code 137. Tune
GOMEMLIMITand add RAM. - Requests cut off on every deploy: graceful shutdown is missing, or its deadline is longer than the time until
SIGKILL.
Before opening to the public, go through the API production checklist.
How to do this on Square Cloud#
On Square Cloud, you don't need this guide's cross-compile: upload the source code with go.mod and go.sum, and the platform downloads the modules and compiles the program on the server, with no manual build (using go run . when package main spans several files). You can deploy with a ZIP in the dashboard, the CLI, GitHub or the VS Code extension, and the squarecloud.app file is optional: the dashboard generates it on deploy.
The platform sets the PORT variable, and the example code already reads it and listens on 0.0.0.0. Only port 80 receives traffic, published over HTTPS on a *.squareweb.app subdomain; a custom domain is available from the Standard plan. The proxy doesn't cut long-lived connections, so WebSocket and SSE go through, as long as your own WriteTimeout doesn't cut them first.
A web app uses at least 512 MB of the plan's RAM pool, and the plan's vCPU is the ceiling for each environment. Variables such as GOMEMLIMIT live in the app's settings and apply on the next restart. If the process exits with an error, auto restart (on by default when you deploy from the dashboard) brings it back; if it runs out of memory, it stops and doesn't come back on its own: add RAM and start it again. Hobby starts at R$12.49 a month, with 1 GB.
To control your apps from your own code, there's an official Go SDK for the REST API. See the details of Go hosting.
API hosting
APIs in always-on containers, with no cold starts
FAQs
Do I need a framework like Gin or Echo for a Go API?
No. The standard library's net/http already routes by method and path, such as GET /users/{id}, and ships a complete HTTP server. Frameworks help with middleware and validation, but the deploy is the same.
Do I need Go installed on the server?
Not if you ship the compiled binary: it doesn't depend on an installed Go toolchain. Build with the server's GOOS and GOARCH and, with CGO_ENABLED=0, it doesn't depend on the system's libc either.
How much memory does a Go API use?
It depends on what each request allocates. Measure the peak under real traffic and, in a container with a fixed limit, set GOMEMLIMIT a little below it: the Go garbage collector guide suggests 5% to 10% of headroom.
Why does my binary fail with exec format error on the server?
It was built for a different OS or architecture, like a binary from an ARM Mac running on x86 Linux. Rebuild with GOOS=linux and the server's GOARCH, amd64 or arm64.
More in APIs
See all 36 articles- How to host an APIHosting an API means running its HTTP server around the clock at a public address with HTTPS. Step-by-step with Node.js and Python, testing and common errors.
- How to host a Node.js appTo host a Node.js app, prepare package.json, read the port and secrets from the environment, pick an LTS version and run it with node. Step-by-step guide.
- How much does it cost to host an API?Hosting a small API costs a few to a few dozen dollars a month. See what goes into the bill (compute, database, bandwidth, requests, logs) and how to estimate it.
- CORS error (blocked by CORS policy): cause and fixA CORS error means the API did not allow your page's origin. Learn the causes, how to fix it in Express and FastAPI, and how to test the preflight with curl.