# Add CORS to a Gin API

Yes. An agent adds gin-contrib/cors to your Gin API with origins from the environment, allows the Authorization header, tests preflight, and opens a PR.

[Run this on Rush](https://cloud.getrush.ai/run/add-cors/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 requests are authenticated before it decides which headers a browser must be allowed to send. In a Gin API shaped like gothinkster/golang-gin-realworld-example-app, `go.mod` declares Go 1.21 with `gin-gonic/gin v1.10.0`, `golang-jwt/jwt/v5`, `gorm.io/gorm v1.25.12` and the SQLite driver, and nothing CORS-related. `hello.go` is the whole bootstrap: `common.Init()` opens SQLite, `Migrate(db)` runs `AutoMigrate`, `gin.Default()` builds the router with `RedirectTrailingSlash` off, and the `/api` group registers the anonymous `users` routes first, then `users.AuthMiddleware(false)` for optional auth on articles, tags and profiles, then `users.AuthMiddleware(true)` for the routes that need a user. `users/middlewares.go` reads the token from an `Authorization: Token <jwt>` header or an `access_token` query parameter.

A browser frontend on another origin, the shape `FRONTEND_INSTRUCTIONS.md` describes with the token in `localStorage`, sends a preflight `OPTIONS` for every request carrying that header, and today the router answers `404`. The agent adds `github.com/gin-contrib/cors` to `go.mod` and registers `cors.New` as the first middleware on the router in `hello.go`, before the `/api` group and before the `/api/ping` group, with `AllowOrigins` read from a comma-separated `CORS_ALLOWED_ORIGINS` variable in the way `PORT` and `DB_PATH` are read, `AllowMethods` for `GET`, `POST`, `PUT`, `DELETE` and `OPTIONS`, `AllowHeaders` including `Authorization` and `Content-Type`, and `AllowCredentials` off since the token travels in a header. An empty variable means no origin is allowed, so a deployment has to opt in.

Tests follow `common/unit_test.go` and `users/unit_test.go`: `httptest.NewRecorder`, a router built in the test, and `assert.New(t)`. A new `common/cors_test.go` builds a router with the same middleware configuration, sends an `OPTIONS /api/articles` with `Origin` and `Access-Control-Request-Headers: Authorization` from an allowed origin and asserts `204` with the matching `Access-Control-Allow-Origin` and an `Allow-Headers` value that includes `Authorization`, sends the same from a different origin and asserts no allow header, and sends a plain `GET /api/ping/` with an allowed `Origin` and asserts the echo header on the `200`. The configuration is moved into a `common.CORSConfig()` function so the test and `hello.go` share it.

Before it pushes, the agent runs what `.github/workflows/ci.yml` runs: `bash ./scripts/gofmt.sh`, `bash ./scripts/coverage.sh` for the tests, `golangci-lint run` with the `.golangci.yml` that enables `staticcheck`, `unused` and `misspell`, and `bash ./scripts/run-api-tests.sh`, which builds the binary, starts it on 8080 and runs the Realworld Postman collection with Newman, to show the API's own behaviour is unchanged. It documents `CORS_ALLOWED_ORIGINS` in `readme.md` and adds the middleware to the directory map in `AGENTS.md`.

## Start it with one API call

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

```json
{
  "agent": "codex",
  "input": "Add CORS to this Gin API and open a pull request. Read go.mod, hello.go, users/middlewares.go, users/routers.go, common/database.go, common/unit_test.go, scripts/gofmt.sh, scripts/coverage.sh, scripts/run-api-tests.sh, .golangci.yml, .github/workflows/ci.yml, readme.md and AGENTS.md first. Add github.com/gin-contrib/cors to go.mod. Add common.CORSConfig() that returns a cors.Config with AllowOrigins from a comma-separated CORS_ALLOWED_ORIGINS environment variable, no origins when it is empty, AllowMethods GET, POST, PUT, DELETE and OPTIONS, AllowHeaders including Authorization and Content-Type, and AllowCredentials false. Register cors.New(common.CORSConfig()) as the first middleware on the router in hello.go, before the /api group and the ping group. Add common/cors_test.go using httptest and testify as common/unit_test.go does: a preflight OPTIONS /api/articles from an allowed origin requesting the Authorization header answers 204 with the matching allow-origin and allow-headers, the same from another origin gets no allow-origin header, and GET /api/ping/ from an allowed origin gets the allow-origin header on its 200. Run scripts/gofmt.sh, scripts/coverage.sh, golangci-lint run and scripts/run-api-tests.sh, paste the output in the pull request, document CORS_ALLOWED_ORIGINS in readme.md and add the middleware to AGENTS.md. Do not change any route, model or the auth middleware.",
  "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 with `github.com/gin-contrib/cors` in `go.mod` and `go.sum`, `CORSConfig` in `common/`, a two-line change to `hello.go` that registers the middleware first, `common/cors_test.go`, and documentation in `readme.md` and `AGENTS.md`. The description shows a `curl -X OPTIONS` preflight from the sandbox with the response headers, and the output of `scripts/gofmt.sh`, `scripts/coverage.sh`, `golangci-lint run` and the Newman run from the branch.

The CI workflow runs the same scripts on the pull request across Go 1.21, 1.22 and 1.23, the lint job with `golangci-lint` v1.61, the `gosec` scan and the API integration job, so the new test shows up in the coverage delta and the Postman collection still passes. The agent pushes one commit for the middleware and test and one for the documentation.

A reviewer checks that the middleware runs before `AuthMiddleware` so a preflight never hits the `401` path, that the allowed origin list is read from the environment and empty by default, that `Authorization` is in the allowed headers because the frontend sends the token that way, and that `/api/ping/` and every `/api` route are unchanged. Then they set `CORS_ALLOWED_ORIGINS` to their frontend's origin in each environment.

## Run it on every new frontend origin

A team with several Go APIs behind separate frontends starts one run per repository with `POST /o/{org}/sessions`, this prompt and the repository in `resources`. The agent reads each API's own auth middleware, so an API that uses a cookie gets `AllowCredentials` on and an explicit origin list rather than a wildcard, and each run opens its own pull request.

The key's `webhook_url` receives `run.completed` for each run it starts, with a `session_url` for the result, so a script can post the pull request links to the team channel as they land.

## Why run it on Rush?

CORS mistakes are silent until a browser refuses a request, and the usual fix is a wildcard that allows everything. In a Rush sandbox the agent reads the auth middleware to learn which header the preflight has to allow, sends real preflights with `curl` from allowed and disallowed origins, and the responses are kept in the transcript beside the test output, so the pull request shows the exact headers a browser will see.

The result passes the repository's own gates, `gofmt`, the coverage script, `golangci-lint` and the Realworld Postman collection, before a reviewer opens it, and the origin list is a deployment setting rather than a constant. The same request works unchanged across every Gin service the team owns.

## Frequently asked questions

### Why not allow every origin?

Because the API authenticates with a bearer token in the `Authorization` header, and a wildcard lets any site make a browser send requests the user's token could be attached to by other code on that page. Reading `CORS_ALLOWED_ORIGINS` from the environment keeps the list explicit per deployment and empty until someone sets it.

### Why must the middleware come before AuthMiddleware?

A preflight `OPTIONS` carries no token. If `users.AuthMiddleware(true)` ran first on an authenticated route, the preflight would be rejected with `401` before the CORS handler could answer it. Registering `cors.New` on the root router in `hello.go` means every group, including `/api/ping`, is covered.

### Does it change the Postman API tests?

No. Newman sends no `Origin` header, so the middleware adds nothing to those responses, and `scripts/run-api-tests.sh` passes as before. The agent runs it in the sandbox and pastes the summary.

### Which origins should I set?

The origin of each frontend that calls the API, scheme and host, comma-separated in `CORS_ALLOWED_ORIGINS`. The pull request's `readme.md` section gives the format; a local frontend and a production one are two entries.

## More Gin jobs

- [Add Cursor Pagination to a Gin API from a Linear Issue](https://getrush.ai/run/add-cursor-pagination/gin/)
- [Add Versioned Database Migrations to a Gin App](https://getrush.ai/run/add-database-migrations/gin/)
- [Add a Feature to a Gin App from a Customer Spec](https://getrush.ai/run/add-feature-per-customer/gin/)

## The same job on other stacks

- [Add CORS to a Hono API](https://getrush.ai/run/add-cors/hono/)
- [Add CORS to a Koa App](https://getrush.ai/run/add-cors/koa/)
- [Add CORS and Rate Limiting to a Ktor Server from a Linear Issue](https://getrush.ai/run/add-cors/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/)
