Square CloudSquare Cloud

How to host a Go API

To host a Go API, read the port from the PORT variable, listen on 0.0.0.0 and build a binary for the server's operating system. Handle SIGTERM with a graceful shutdown so in-flight requests aren't cut off.

Updated 8 min read

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

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 go directive in go.mod is the module's minimum version: with the default GOTOOLCHAIN=auto, an older toolchain downloads the requested release before building; with GOTOOLCHAIN=local, it refuses the module.
  • A module: go mod init example.com/myapi creates go.mod, and go.sum stores 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:

go
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:

bash
PORT=9090 go run .
curl -i http://localhost:9090/health
  • 0.0.0.0 and the port: listening on localhost:8080 (or 127.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.0 just makes it explicit.
  • PORT: the environment decides the port, and 8080 is only a development default. See what environment variables are.
  • Timeouts: an http.Server without them waits forever on slow clients. ReadHeaderTimeout caps how long reading the headers can take, and WriteTimeout cuts long responses: raise it, or run a separate server, for streaming and SSE routes.
  • /health: an endpoint that returns 200 without 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 Shutdown is called, ListenAndServe returns http.ErrServerClosed immediately. That's why the code ignores that error and main waits for Shutdown to return instead of exiting.
  • Shutdown doesn't close or wait for hijacked connections such as WebSockets. Notify them with srv.RegisterOnShutdown and 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.

bash
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: amd64 for most x86 servers, arm64 for ARM servers. A binary for the wrong architecture fails with exec format error.
  • -trimpath and -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 as MiB and GiB. 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 to GOMEMLIMIT=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?#

  1. Logs: look for the listening on 0.0.0.0:... line with the environment's port. If it shows localhost or 127.0.0.1, outside traffic can't get in.
  2. Health endpoint: curl -i https://your-domain/health should return 200 and {"status":"ok"}.
  3. Shutdown: restart the app and check that the log shows signal received, shutting down followed by stopped. Without the second line, the process was killed before it finished.
  4. 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 in PORT (more in EADDRINUSE and 502 after a deploy).
  • The log says it started, but outside connections are refused: the server listens on localhost. Use 0.0.0.0 in Addr.
  • exec format error: the binary was built for another GOOS or GOARCH. Rebuild for the server's platform.
  • missing go.sum entry for module providing package ...: go.sum is out of date. Run go mod tidy and commit go.sum.
  • The build rejects the module because of the Go version: the toolchain on the server or in CI is older than the go directive in go.mod and couldn't download the requested release (with GOTOOLCHAIN=local or 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 GOMEMLIMIT and 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

Go hosting

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.

Next articleHow to host a Ruby on Rails applicationTo host a Rails app, use RAILS_ENV=production, pass the secret key through an env variable, tune Puma, precompile the assets and run the migrations. Step by step.