Copilot instructions for idiomatic Go services with Go 1.22+ method routing, wrapped errors, slog logging and table-driven httptest tests.
.github/instructions/github-copilot-go-development.instructions.md. Downloaded files need to be placed in that repository path.---
applyTo: "**/*"
---
# Go Development Instructions
Applies to: Go services and libraries in this repository (HTTP handlers, services, repositories and their tests).
Version baseline: checked against Go 1.27 release notes (Go 1.22+ routing and loop variables, Go 1.26 `errors.AsType`). Read `go.mod` first: if its `go` directive is older, do not use features newer than that version.
## Style
- Format with `gofmt`/`goimports`; let the tools decide layout instead of hand-styling.
- Short names for short scopes (`r`, `w`, `ctx`, `err`, `i`); descriptive names for package-level identifiers.
- Every exported identifier gets a doc comment that starts with its name (`// GetUser returns ...`).
- Pass `context.Context` as the first parameter of anything that does I/O; never store it in a struct.
## HTTP handlers (net/http, Go 1.22+ patterns)
Register method and path together and read wildcards with `r.PathValue`:
```go
mux.HandleFunc("GET /users/{id}", s.HandleGetUser)
func (s *Server) HandleGetUser(w http.ResponseWriter, r *http.Request) {
id := r.PathValue("id")
user, err := s.users.GetUser(r.Context(), id)
if err != nil {
if errors.Is(err, ErrNotFound) {
http.Error(w, "user not found", http.StatusNotFound)
return
}
s.log.ErrorContext(r.Context(), "get user", "id", id, "err", err)
http.Error(w, "internal error", http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
if err := json.NewEncoder(w).Encode(user); err != nil {
s.log.ErrorContext(r.Context(), "encode user", "err", err)
}
}
```
- Map domain errors to status codes in the handler, not in the service.
- Never write internal error text into the response body; log it with `log/slog` instead.
- Set `Content-Type` before writing the body, and check the `Encode` error.
## Errors
```go
var ErrNotFound = errors.New("not found")
func (s *Service) GetUser(ctx context.Context, id string) (*User, error) {
user, err := s.repo.Find(ctx, id)
if err != nil {
return nil, fmt.Errorf("get user %s: %w", id, err)
}
return user, nil
}
```
- Wrap with `%w` and add the operation and key identifiers; compare with `errors.Is`, extract with `errors.As` (or `errors.AsType` on Go 1.26+).
- The repository translates driver errors such as `sql.ErrNoRows` into `ErrNotFound` so handlers do not depend on the database package.
- Either log an error or return it, not both.
## Tests
Use the standard `testing` package with table-driven cases and `httptest`. Use `testify` only if `go.mod` already requires it.
```go
func TestHandleGetUser(t *testing.T) {
tests := []struct {
name string
id string
want int
}{
{"found", "123", http.StatusOK},
{"missing", "404", http.StatusNotFound},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
srv := newTestServer(t) // fake repository: "123" exists, others return ErrNotFound
req := httptest.NewRequest(http.MethodGet, "/users/"+tt.id, nil)
rec := httptest.NewRecorder()
srv.mux.ServeHTTP(rec, req)
if rec.Code != tt.want {
t.Fatalf("status = %d, want %d", rec.Code, tt.want)
}
})
}
}
```
- Serve through the mux, not by calling the handler directly, so that the `{id}` pattern is covered by the test.
- Use fakes that implement the small interface the service consumes; do not mock the database driver.
## Verify before finishing
Run these when they are available in the project:
- `gofmt -l .` (expect no output) and `go vet ./...`
- `go test ./...`, plus `go test -race ./...` for code with goroutines
- `staticcheck ./...` or `golangci-lint run`, if configured
Cursor rule for FastAPI projects using Pydantic v2 schemas, SQLAlchemy 2 async_sessionmaker, lifespan cleanup, explicit commits and 409 conflict handling.
Cursor rule for Express 5 APIs in TypeScript with createApp structure, no try/catch boilerplate, Zod 4 validation into res.locals and a safe central error handler.
Cursor rule for Next.js Route Handlers with Zod 4 safeParse validation, auth and ownership checks, awaited params, bounded pagination and one consistent JSON error shape.
Copilot
backend
Illustrative input and expected result. This example is a verification guide, not a recorded model run.
Content reviewed .
A Go 1.27 service repository uses these Copilot instructions while a developer asks Copilot Chat or the cloud agent to add a read endpoint and its tests.
Add GET /users/{id} to internal/http/server.go. UserService.GetUser(ctx, id) returns ErrNotFound for unknown IDs. Write tests for found and missing users.Illustrative; not a recorded model run. A handler registered as "GET /users/{id}" that reads r.PathValue("id"), maps errors.Is(err, ErrNotFound) to 404 and other errors to a logged 500 without leaking the message, sets Content-Type before encoding JSON and checks the Encode error; a table-driven test that routes through the mux with httptest and a fake service, using only the testing package unless testify is already in go.mod.GitHub Copilot reads repository-wide custom instructions from .github/copilot-instructions.md and path-specific instructions from .github/instructions/*.instructions.md files with an applyTo glob. Copilot can also use AGENTS.md files, where the nearest file in the directory tree takes precedence. Which file types are honored depends on the surface: VS Code, Visual Studio, JetBrains, Xcode, Eclipse and GitHub.com differ.
.github/instructions/github-copilot-go-development.instructions.mdStarting point, not a tested configuration for your repository. Used for files matching applyTo on surfaces that support path-specific instructions. Review the instructions, adapt the file paths and run your project's existing checks.
---
applyTo: "**/*"
---
# Go Development Instructions
Applies to: Go services and libraries in this repository (HTTP handlers, services, repositories and their tests).
Version baseline: checked against Go 1.27 release notes (Go 1.22+ routing and loop variables, Go 1.26 `errors.AsType`). Read `go.mod` first: if its `go` directive is older, do not use features newer than that version.
## Style
- Format with `gofmt`/`goimports`; let the tools decide layout instead of hand-styling.
- Short names for short scopes (`r`, `w`, `ctx`, `err`, `i`); descriptive names for package-level identifiers.
- Every exported identifier gets a doc comment that starts with its name (`// GetUser returns ...`).
- Pass `context.Context` as the first parameter of anything that does I/O; never store it in a struct.
## HTTP handlers (net/http, Go 1.22+ patterns)
Register method and path together and read wildcards with `r.PathValue`:
```go
mux.HandleFunc("GET /users/{id}", s.HandleGetUser)
func (s *Server) HandleGetUser(w http.ResponseWriter, r *http.Request) {
id := r.PathValue("id")
user, err := s.users.GetUser(r.Context(), id)
if err != nil {
if errors.Is(err, ErrNotFound) {
http.Error(w, "user not found", http.StatusNotFound)
return
}
s.log.ErrorContext(r.Context(), "get user", "id", id, "err", err)
http.Error(w, "internal error", http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
if err := json.NewEncoder(w).Encode(user); err != nil {
s.log.ErrorContext(r.Context(), "encode user", "err", err)
}
}
```
- Map domain errors to status codes in the handler, not in the service.
- Never write internal error text into the response body; log it with `log/slog` instead.
- Set `Content-Type` before writing the body, and check the `Encode` error.
## Errors
```go
var ErrNotFound = errors.New("not found")
func (s *Service) GetUser(ctx context.Context, id string) (*User, error) {
user, err := s.repo.Find(ctx, id)
if err != nil {
return nil, fmt.Errorf("get user %s: %w", id, err)
}
return user, nil
}
```
- Wrap with `%w` and add the operation and key identifiers; compare with `errors.Is`, extract with `errors.As` (or `errors.AsType` on Go 1.26+).
- The repository translates driver errors such as `sql.ErrNoRows` into `ErrNotFound` so handlers do not depend on the database package.
- Either log an error or return it, not both.
## Tests
Use the standard `testing` package with table-driven cases and `httptest`. Use `testify` only if `go.mod` already requires it.
```go
func TestHandleGetUser(t *testing.T) {
tests := []struct {
name string
id string
want int
}{
{"found", "123", http.StatusOK},
{"missing", "404", http.StatusNotFound},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
srv := newTestServer(t) // fake repository: "123" exists, others return ErrNotFound
req := httptest.NewRequest(http.MethodGet, "/users/"+tt.id, nil)
rec := httptest.NewRecorder()
srv.mux.ServeHTTP(rec, req)
if rec.Code != tt.want {
t.Fatalf("status = %d, want %d", rec.Code, tt.want)
}
})
}
}
```
- Serve through the mux, not by calling the handler directly, so that the `{id}` pattern is covered by the test.
- Use fakes that implement the small interface the service consumes; do not mock the database driver.
## Verify before finishing
Run these when they are available in the project:
- `gofmt -l .` (expect no output) and `go vet ./...`
- `go test ./...`, plus `go test -race ./...` for code with goroutines
- `staticcheck ./...` or `golangci-lint run`, if configured
Ask for a small change to one matching file. Check the tool's loaded context or instruction view, inspect the diff for the requested convention, and run the relevant build or test. A well-formatted file does not guarantee the model follows every instruction.
Instruction support differs by surface: VS Code supports repository-wide, path-specific and AGENTS.md instructions; Visual Studio supports repository-wide and path-specific; JetBrains and Xcode use .github/copilot-instructions.md. GitHub's documentation describes AGENTS.md files stored anywhere in the repository, with the nearest file in the directory tree taking precedence, or alternatively a single CLAUDE.md or GEMINI.md in the root. Support differs by surface; GitHub's IDE page lists AGENTS.md among the instruction types for VS Code.
Documentation checked 2026-11-05: GitHub Docs: Adding repository custom instructionsGitHub Docs: Repository instructions in your IDE
Cursor rule for FastAPI projects using Pydantic v2 schemas, SQLAlchemy 2 async_sessionmaker, lifespan cleanup, explicit commits and 409 conflict handling.
Cursor rule for Express 5 APIs in TypeScript with createApp structure, no try/catch boilerplate, Zod 4 validation into res.locals and a safe central error handler.
Cursor rule for Next.js Route Handlers with Zod 4 safeParse validation, auth and ownership checks, awaited params, bounded pagination and one consistent JSON error shape.