# Add Graceful Shutdown to a Gin API

Yes. An agent replaces r.Run in your Gin API with an http.Server that drains in-flight requests on SIGTERM, closes the database, adds a test for it and opens a PR.

[Run this on Rush](https://cloud.getrush.ai/run/add-graceful-shutdown/gin/). Opens the console with this prompt ready to send, in a Project that has your repository.

## What the agent does

The agent reads how the process starts and stops today. In a Gin API like gothinkster/golang-gin-realworld-example-app, `hello.go` is the whole entry point: `common.Init()` opens the GORM SQLite database at `DB_PATH` or `./data/gorm.db`, `Migrate` runs `AutoMigrate` for the user, article, tag, favorite and comment models, `sqlDB.Close()` is deferred, `gin.Default()` builds the router with the `/api` group, the two `AuthMiddleware` layers and the `/api/ping` route, and the last line is `r.Run(":" + port)` with `PORT` from the environment. `r.Run` blocks in `http.ListenAndServe`, so a `SIGTERM` from a container runtime or a deploy kills the process mid-request, the deferred close never runs, and a client gets a reset connection instead of a response.

`go.mod` pins Go 1.21 with `gin-gonic/gin` 1.10, `gorm.io/gorm` 1.25 and `gorm.io/driver/sqlite` 1.5, which needs cgo; `.github/workflows/ci.yml` tests on Go 1.21, 1.22 and 1.23, runs `scripts/gofmt.sh`, `scripts/coverage.sh` (a `go test -coverprofile` loop over every package directory), `golangci-lint` v1.61 with `staticcheck`, `unused` and `misspell` from `.golangci.yml`, `gosec`, and `scripts/run-api-tests.sh`, which builds the binary, starts it with `PORT=8080`, waits on `/api/ping`, runs the RealWorld Postman collection with Newman and kills the server on exit. `AGENTS.md` asks that every error be handled explicitly and that tests use `common.TestDBInit()` and `common.TestDBFree()`.

The change keeps the router and adds a server around it. `hello.go` gains a `newServer(r *gin.Engine, addr string) *http.Server` with `ReadHeaderTimeout` set, and `main` becomes: start `srv.ListenAndServe` in a goroutine, wait on a `signal.NotifyContext` for `SIGINT` and `SIGTERM`, then call `srv.Shutdown` with a context bounded by `SHUTDOWN_TIMEOUT` from the environment, defaulting to a value named in the pull request, then close the `*sql.DB` from `db.DB()` once the server has stopped. Routes do not change, `gin.Default()` stays, and `scripts/run-api-tests.sh` keeps working because `kill $SERVER_PID` now sends the `SIGTERM` the server handles instead of one it ignores. The agent also adds a `run()` function that returns an error so `main` can `log.Fatal` once, which `AGENTS.md`'s error rule asks for and which makes the behaviour testable.

The test proves the drain rather than describing it. A new `hello_test.go` starts the server on a free port with a handler that sleeps briefly, opens a request, sends the shutdown, and asserts that the in-flight request completes with its response, that a new connection after shutdown is refused, and that `Shutdown` returns `context.DeadlineExceeded` when a handler outlasts the timeout. It runs under `go test -race ./...`, through `bash ./scripts/coverage.sh` and `bash ./scripts/gofmt.sh`, and `golangci-lint run`, then through `scripts/run-api-tests.sh` end to end so the Newman collection still passes against the new entry point.

## Start it with one API call

`POST https://api.phoenix.so/o/{org}/sessions`

```json
{
  "agent": "claude",
  "input": "Add graceful shutdown to this Gin API. Read hello.go, common/database.go, go.mod, AGENTS.md, .github/workflows/ci.yml, .golangci.yml and scripts/run-api-tests.sh first. Replace r.Run with an http.Server built around the existing router, with ReadHeaderTimeout set: serve in a goroutine, wait on signal.NotifyContext for SIGINT and SIGTERM, call Shutdown with a context bounded by a SHUTDOWN_TIMEOUT environment variable with a stated default, and close the database from db.DB() after the server stops. Keep every route and middleware as it is. Move the body of main into a run function that returns an error so main calls log.Fatal once. Document SHUTDOWN_TIMEOUT in .env.example. Add hello_test.go that starts the server on a free port with a slow handler, sends a request, triggers shutdown, and asserts the in-flight request completes, a new connection is refused afterwards, and Shutdown returns context.DeadlineExceeded when a handler outlasts the timeout; use common.TestDBInit and common.TestDBFree if the test needs the database. Run go test -race ./..., bash ./scripts/gofmt.sh, bash ./scripts/coverage.sh, golangci-lint run and bash ./scripts/run-api-tests.sh, and fix what they report. Do not change go.mod, the CI workflow or any route. Open a pull request with the files, the default timeout and why, the test output and the Newman summary.",
  "resources": [
    {
      "url": "https://github.com/your-org/your-app"
    }
  ]
}
```

1. **Get an API key.** In the console, open Settings, then API keys, and create a key for your org. Send it in the Authorization header as a Bearer token.
2. **Send the request.** POST the body in request.json to https://api.phoenix.so/o/{org}/sessions, with your repository as the resources URL. The run starts in its own cloud sandbox.
3. **Read what came back.** Follow the run on its live stream or wait for the run.completed webhook, then read the result and its trajectory.

## What comes back

What comes back is a pull request on its own branch that changes `hello.go` and adds `hello_test.go` and one line in `.env.example`. In `hello.go` the router setup is unchanged; `main` now builds an `http.Server`, serves it in a goroutine, waits for a signal, drains with a bounded context and closes the SQLite handle after the listener stops. `go.mod`, `go.sum`, the three packages under `users`, `articles` and `common`, and `.github/workflows/ci.yml` are untouched.

The description names the default `SHUTDOWN_TIMEOUT` and the reason for it, quotes the `go test -race ./...` output with the three new assertions, the `gofmt`, coverage script and `golangci-lint` results, and the Newman summary from `scripts/run-api-tests.sh`, which now stops the server through the signal path rather than killing it mid-request.

A reviewer reads the new `main` and `run` against their deployment's stop timeout, checks that the database close happens after `Shutdown` returns, and merges when the four CI jobs pass. The transcript holds every command, including the end-to-end script's server log.

## Run it on every Go service that still calls r.Run

This is a one-time change per service, usually started by hand: `POST /o/{org}/sessions` with this prompt in `input` and the repository in `resources`, once per Gin service, each in its own sandbox. The sandbox parks when the turn ends, so a follow-up such as adding a readiness endpoint that reports draining wakes the same checkout.

A saved agent holding the prompt as `instructions` turns each call into `{"agent": "<agent id>", "input": "<repository notes>"}` with the repository in `resources`; a key with a `webhook_url` gets `run.completed` with `data.session_url`, where the pull request URL is read.

## Why run it on Rush?

Graceful shutdown is easy to write and hard to be sure of: the proof is a request in flight while the signal arrives, a connection attempted after it, and a handler that overruns the deadline, all timed. The sandbox runs that test under the race detector, then the repository's own coverage, lint and Newman scripts, and keeps the output, so the pull request shows the drain working rather than asserting it.

The change is small and local to the entry point, so the pull request is quick to read, and a reviewer who wants a different default timeout changes one constant. The same prompt on another Gin service reads that service's entry point and scripts instead of assuming this one's.

## Frequently asked questions

### Why not keep r.Run and trap the signal around it?

Because `r.Run` is `http.ListenAndServe` with no handle to call `Shutdown` on; the only way to drain is to own the `http.Server`. Gin's own documentation shows the same structure, and the router, middleware and routes are passed to the server unchanged.

### What timeout does it pick?

One it states and justifies in the pull request, read from `SHUTDOWN_TIMEOUT` so a deployment can match it to its own stop grace period. The test does not depend on the default: it passes a short timeout of its own to assert the `DeadlineExceeded` case.

### Does the Newman script still work?

Yes, and better. `scripts/run-api-tests.sh` starts the binary and ends with `kill $SERVER_PID`, which sends `SIGTERM`; before the change that aborted the process, after it the server drains and exits cleanly, and the script's cleanup trap removes the binary as before. The agent runs the script to show the collection still passes.

### Will the SQLite file be closed properly?

Yes. The deferred `sqlDB.Close()` in today's `main` never runs on a signal because the process is killed; the new `run` closes the `*sql.DB` after `Shutdown` returns, so no handler is still using it, and reports the close error if there is one, as `AGENTS.md` requires.

## More Gin jobs

- [Add Health Check Endpoints to a Gin App](https://getrush.ai/run/add-health-checks/gin/)
- [Add OpenAPI Docs to a Gin API](https://getrush.ai/run/add-openapi-docs/gin/)
- [Add OpenTelemetry Tracing to a Gin API](https://getrush.ai/run/add-opentelemetry/gin/)

## The same job on other stacks

- [Add Graceful Shutdown to a Go Service from a Linear Issue](https://getrush.ai/run/add-graceful-shutdown/go/)
- [Add Graceful Shutdown to a grammY Bot](https://getrush.ai/run/add-graceful-shutdown/grammy/)
- [Add Graceful Shutdown to a Koa API](https://getrush.ai/run/add-graceful-shutdown/koa/)

## Keep reading

- [How a Rush run works on your repository, from request to pull request](https://getrush.ai/cloud/)
- [Compare cloud agents, agent sandboxes and AI code review](https://getrush.ai/compare/)
- [Rush pricing: Free, Pro and Max](https://getrush.ai/pricing/)
