# Add Prometheus Metrics to a Gin API from a Linear Issue

Yes. Label the Linear issue and an agent adds Prometheus middleware to your Gin API with counts and latency by route template, a /metrics endpoint and tests.

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

## What the agent does

The agent starts from the Linear issue and the repository in its own sandbox, and reads how the engine is built before adding middleware. In an API like gothinkster/golang-gin-realworld-example-app, `hello.go` opens the SQLite database through `common.Init`, migrates the user and article models, builds the engine with `gin.Default()`, which attaches Gin's Logger and Recovery, turns `RedirectTrailingSlash` off, and mounts groups under `/api`: `users` for registration and login, then `users.AuthMiddleware(false)` for the anonymous article, tag and profile reads, then `AuthMiddleware(true)` for the authenticated user, profile and article routes, plus a `/api/ping` group, before listening on `PORT` or `8080`. `go.mod` declares `go 1.21` with `gin v1.10.0`, `gorm.io/gorm` with the SQLite driver, `golang-jwt/jwt/v5` and `testify`; nothing from `prometheus/client_golang` is in `go.sum`. `AGENTS.md` asks for explicit error handling, GORM v2 patterns, and `go test ./...` before committing, with tests using `common.TestDBInit` and `common.TestDBFree`.

The change is a new package and two lines of wiring. The agent adds `github.com/prometheus/client_golang` with `go get` and writes `metrics/metrics.go` with a `New` function that takes a `prometheus.Registerer` and returns a `gin.HandlerFunc` plus the collectors it registered: a `CounterVec` named `http_requests_total` and a `HistogramVec` named `http_request_duration_seconds`, both labelled `method`, `route` and `status`. The middleware records the time, calls `c.Next()`, then observes with `c.FullPath()` as the `route` label, which is the template `/api/articles/:slug` rather than the slug itself, and `unmatched` when `FullPath` is empty because no route matched. A `GaugeFunc` per `sql.DBStats` field reads `OpenConnections`, `InUse` and `Idle` from the `*sql.DB` behind GORM, which `hello.go` already fetches with `db.DB()` to close it on exit. In `hello.go`, `r.Use(metrics.New(prometheus.DefaultRegisterer))` goes right after `gin.Default()`, and `r.GET("/metrics", gin.WrapH(promhttp.Handler()))` is registered on the engine itself, outside the `/api` group, so neither `AuthMiddleware` sees it. The default registry already carries the Go runtime and process collectors, so heap, goroutines and GC come free.

Tests follow the shape of `common/unit_test.go` and `articles/unit_test.go`: a `gin.New()` engine with the middleware and a route, `httptest.NewRecorder`, and `testify` assertions. `metrics/metrics_test.go` registers the collectors on a fresh `prometheus.NewRegistry()` in each test, because registering the same name twice on the default registry panics, then asserts with `testutil.ToFloat64` that the counter for `GET`, `/ping`, `200` is 1 after one request, that two requests to `/items/:id` with different ids land on one series labelled with the template, that a request to an unknown path is labelled `unmatched` with status `404`, and that `promhttp.Handler()` answers `200` with the `http_request_duration_seconds_bucket` lines. The existing `articles` and `users` tests build their own routers in `setupRouter` and are not touched; the agent runs them anyway, because `AGENTS.md` says to.

Verification follows `.github/workflows/ci.yml`: a `go` matrix of 1.21, 1.22 and 1.23 with `go mod download` and `go mod verify`, `bash ./scripts/gofmt.sh`, which fails on any unformatted file, and `bash ./scripts/coverage.sh`, which runs `go test -coverprofile` package by package and merges the output, plus a lint job with `golangci-lint` configured in `.golangci.yml` to run `staticcheck`, `unused` and `misspell` with a US locale. The agent runs `go build ./...`, `go test ./...`, the format script and `golangci-lint run` on Go 1.21, the lowest in the matrix, so a newer standard library call cannot slip in, then starts the server with `go run hello.go`, requests `/api/tags` and `/metrics`, and keeps the scrape output for the pull request. A short `Metrics` section in `readme.md` names the endpoint and the meters.

## Start it with one API call

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

```json
{
  "agent": "claude",
  "input": "A Linear issue labelled agent says: \"Add Prometheus metrics to the Gin API: request count and latency by route, database pool stats, and a /metrics endpoint that does not require a token.\" Do the work in this repository. Read go.mod, hello.go, common/database.go, users/middlewares.go, articles/routers.go, common/unit_test.go, articles/unit_test.go, scripts/gofmt.sh, scripts/coverage.sh, .golangci.yml, AGENTS.md and .github/workflows/ci.yml first. Add github.com/prometheus/client_golang and write a metrics package whose New function takes a prometheus.Registerer and returns a gin.HandlerFunc that records http_requests_total and http_request_duration_seconds labelled method, route and status, using c.FullPath() for the route so ids and slugs never appear in a label, and unmatched when no route matched; add GaugeFunc collectors for the sql.DBStats open, in-use and idle counts from the *sql.DB behind GORM. In hello.go, register the middleware on the engine right after gin.Default() and mount GET /metrics with promhttp.Handler() on the engine itself, outside the /api group and both AuthMiddleware calls. Write tests in the style of common/unit_test.go on a fresh prometheus.NewRegistry() per test, covering the counter value after one request, two ids collapsing to one template series, the unmatched label on a 404, and the /metrics response. Run go build ./..., go test ./..., bash scripts/gofmt.sh and golangci-lint run on Go 1.21, start the server, read /metrics once, add a Metrics section to readme.md, and open a pull request that links the issue, lists the meters and labels, and quotes the test, format and lint output with the first lines of the scrape.",
  "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 adds `metrics/metrics.go` and `metrics/metrics_test.go`, changes `hello.go` by two lines and an import, updates `go.mod` and `go.sum` with `client_golang` and its transitive modules, and adds a section to `readme.md`. The body links the Linear issue, lists the meters with their labels and says which come from the default registry's runtime collectors, and quotes `go test ./...`, the format script, `golangci-lint run` and the first lines of the scrape from the running server.

The transcript keeps every command with its output: the module download, the build, the test run before the package existed and after, the format and lint checks, and the request to `/metrics`. If the repository's `CI` workflow runs on pull requests from the branch, its matrix and lint jobs appear as checks as well.

Before merging, a reviewer checks that the `route` label is `c.FullPath()` everywhere and that no handler path leaks a slug or an id, that the middleware is registered before the `/api` group so every route is measured, that `/metrics` sits outside both `AuthMiddleware` calls and is therefore reachable without a token, and that the new transitive dependencies in `go.sum` are acceptable. Whether `/metrics` should be reachable from the public internet is a deployment decision, and the README section the agent adds says so.

## Run it on every Linear issue labelled agent

In the console, an automation with a `linear` trigger on `linear.issue.labeled` and the label `agent` starts one run per labelled issue in the Project's repository. The trigger adds the issue's text after the saved prompt and fills in no placeholder, so each issue carries its own wording, such as which labels to use or whether to measure the database pool. Only a change by someone in your Rush org fires it, changes made by an app integration never do, and the automation's `max_runs_per_hour` bounds how many runs a burst of labelling starts.

From your own server, the same run is one `POST /o/{org}/sessions` per issue: put the repository in `resources`, and add the issue's `https://linear.app/<workspace>/issue/<ID>` URL there too so Rush reads it through your Linear connection into the prompt. A `webhook_url` on that key posts `run.completed` or `run.failed` when the turn finishes, with `data.session_url` to read the pull request.

## Why run it on Rush?

Metrics middleware is judged by its labels, and the wrong label is only visible once real traffic has produced ten thousand series. The agent reads `articles/routers.go` and `users/routers.go` to see that every path carries a `:slug` or `:username`, writes the test that sends two ids and expects one series, and runs it in its own sandbox on the Go version the matrix starts at, with the module cache clean, so the first scrape a reviewer sees already has template labels.

A label in Linear becomes a pull request with its proof attached: the test output, the format and lint checks and a real scrape are in the transcript, and the issue links to the work. Several labelled Go issues run at once, each in its own sandbox with its own branch, and a follow-up asking for a histogram on the GORM query time wakes the same sandbox with the module cache still warm.

## Frequently asked questions

### Does /metrics need a JWT like the rest of the API?

No. It is mounted on the engine itself, outside the `/api` group, and `AuthMiddleware` is attached to that group, not the engine, so the route is reachable without a token. The issue asked for exactly that; if your scraper can send a token, say so in the issue and the agent mounts it behind the middleware instead.

### Why c.FullPath() rather than the request path?

Because `c.Request.URL.Path` would make one series per article slug and per username, which grows without bound. `c.FullPath()` returns the route template Gin matched, `/api/articles/:slug`, and is empty when nothing matched, which the middleware maps to `unmatched`. The test that sends two ids to one route asserts the single series.

### Will it keep gin.Default()'s logger and recovery?

Yes. The metrics middleware is added with `r.Use` after `gin.Default()` and runs alongside Logger and Recovery, so a panic is still recovered and still counted with status 500. Switching to structured logging is a separate job.

### Why does each test create its own registry?

Registering a collector with the same name twice on the default registry panics, and `go test` runs every test in a package in one process. A `prometheus.NewRegistry()` per test keeps them independent, and the `New` function takes a `Registerer` for that reason, with `hello.go` passing the default one.

## More Gin jobs

- [Add Rate Limiting to a Gin API](https://getrush.ai/run/add-rate-limiting/gin/)
- [Add Refresh Tokens to a Gin JWT API](https://getrush.ai/run/add-refresh-tokens/gin/)
- [Add Request IDs and Structured Logging to a Gin API from a Linear Issue](https://getrush.ai/run/add-request-id-logging/gin/)

## The same job on other stacks

- [Add Prometheus Metrics to a GORM Service from a Linear Issue](https://getrush.ai/run/add-prometheus-metrics/gorm/)
- [Add Prometheus Metrics to a Koa API](https://getrush.ai/run/add-prometheus-metrics/koa/)
- [Add Prometheus Metrics to a Ktor Server](https://getrush.ai/run/add-prometheus-metrics/ktor/)

## 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/)
