Cursor IDE untuk Golang: Setup .cursorrules, Composer, dan Agent Mode
Panduan lengkap menggunakan Cursor IDE untuk Golang development. Setup .cursorrules yang optimal, Composer multi-file editing, Agent Mode, dan workflow harian untuk Go developer.
Cursor untuk Golang: Composer, Agent Mode, dan .cursorrules
Melakukan setup Cursor IDE untuk Golang dengan benar mengubah cara developer berinteraksi dengan AI — bukan sebagai chat assistant di samping editor, tapi sebagai native part dari IDE itu sendiri. Fork dari VS Code yang sangat mature, Cursor menambahkan lapisan AI yang sangat terintegrasi. Untuk Go developer yang tidak mau keluar dari IDE workflow, Cursor adalah pilihan yang sangat compelling.
06.1 Apa yang Membuat Cursor Unik
Cursor bukan VS Code dengan Copilot — ia adalah re-architecture dari VS Code dengan AI sebagai first-class citizen. Perbandingan berikut menegaskan perbedaan fundamental antara menambahkan plugin AI dan mendesain ulang IDE di sekitar AI.
1VS Code + Copilot:
2 IDE yang ada → tambahkan plugin AI
3 AI bekerja di "side channel" — suggestions, chat window terpisah
4 Context sangat terbatas (hanya file yang sedang dibuka)
5
6Cursor:
7 IDE yang dirancang ulang dengan AI native
8 Composer: AI bisa edit SELURUH project sekaligus
9 Context: seluruh codebase via RAG indexing
10 .cursorrules: persistent project memory
11 Agent Mode: AI yang bisa run commands, browse docs, iteratePerbedaan arsitektural inilah yang membuat Cursor terasa berbeda dalam praktik daily Go development: AI-nya punya konteks seluruh codebase, bukan sekadar file yang sedang terbuka.
06.2 Setup Cursor untuk Go Project
Sebelum produktif, Cursor perlu di-setup dengan Go tooling yang benar. Langkah-langkah berikut menuntun dari instalasi binary hingga verifikasi bahwa gopls sudah bekerja.
1# Install Cursor dari cursor.sh
2# Cursor adalah binary standalone, tidak butuh VS Code terinstall
3
4# Open project Go:
5cursor /path/to/santekno-shop
6
7# Cursor otomatis detect:
8# - go.mod (Go project)
9# - Install Go extension recommendations
10# - Index codebase untuk RAG
11
12# Setup Go language server:
13# Cmd+Shift+P → "Go: Install/Update Tools" → install gopls, dlv, dll
14
15# Verify Go support:
16# Buka file .go → hover variable → type info muncul = gopls workingVerifikasi terakhir — hover variable memunculkan type info — memastikan gopls aktif; tanpa ini, fitur navigasi dan suggestion Cursor tidak akan optimal.
06.3 .cursorrules: Project Memory di Cursor
.cursorrules adalah CLAUDE.md-equivalent di Cursor, diletakkan di root project sebagai memori yang dibaca AI di setiap interaksi. Template berikut menunjukkan isi .cursorrules yang komprehensif untuk proyek Go — arsitektur, error handling, tipe, dependency, hingga daftar larangan.
1# .cursorrules — Santekno Shop Go Project
2
3## Project Overview
4E-commerce B2C Santekno Indonesia.
5Stack: Go 1.22 | Echo v4 | PostgreSQL (pgx/v5) | Redis | Kafka
6
7## Architecture (STRICT — never violate)
8Clean Architecture layers:
9 handler → usecase → repository → domain
10
11Layer rules:
12- handler: only import usecase interfaces
13- usecase: only import domain + repository interfaces
14- repository: implement interfaces, only import domain + DB drivers
15- domain: zero external imports
16
17```go
18// WRONG — layer violation:
19// In usecase file:
20import "github.com/santekno/santekno-shop/internal/repository/postgres" // FORBIDDEN
21
22// CORRECT — interface at consumer side:
23// In usecase package:
24type OrderRepository interface {
25 GetByIDAndUserID(ctx context.Context, id, userID uuid.UUID) (*Order, error)
26}
27```
28
29## Error Handling (FOLLOW EXACTLY)
30
31```go
32// Repository not-found → return nil, nil:
33if err == pgx.ErrNoRows {
34 return nil, nil // NEVER return error for not-found
35}
36
37// Error wrapping:
38if err != nil {
39 return nil, fmt.Errorf("packageName.FunctionName: %w", err)
40 // Include both package AND function name
41}
42
43// Usecase not-found handling:
44if order == nil {
45 return ErrOrderNotFound // domain error, NOT wrapped
46}
47```
48
49## Types (CRITICAL)
50
51```go
52// Monetary: int64 cents ONLY
53type Order struct {
54 TotalIDR int64 // 50000 = Rp 500.00
55}
56// NEVER: float64, decimal, float32
57
58// IDs: uuid.UUID
59type Order struct {
60 ID uuid.UUID
61}
62// NEVER: string IDs
63
64// Context: always first parameter
65func Execute(ctx context.Context, input Input) error
66```
67
68## External Dependencies (exact import paths)
69
70```
71github.com/jackc/pgx/v5 # PostgreSQL
72github.com/redis/go-redis/v9 # Redis
73github.com/labstack/echo/v4 # HTTP
74go.uber.org/mock/gomock # Mocking
75github.com/stretchr/testify/suite # Test suites
76github.com/google/uuid # UUIDs
77github.com/confluentinc/confluent-kafka-go/v2 # Kafka
78```
79
80## Testing Standards
81
82```go
83// Suite structure:
84type CancelOrderSuite struct {
85 suite.Suite
86 ctrl *gomock.Controller
87 mockRepo *mock.MockOrderRepository
88 uc *usecase.CancelOrderUseCase
89}
90
91// Test naming: TestSubject_Scenario_ExpectedResult
92// Example: TestCancelOrder_PendingWithinWindow_Success
93```
94
95## NEVER do these
96
97```go
98result, _ := op() // NEVER ignore error
99return err // NEVER no-context return
100var price float64 // NEVER float for money
101func f(id string) // NEVER string for UUID IDs
102```
103
104## Go 1.22 Only
105No features from Go 1.23+: no range-over-func, no iter.Seq, no slices.CollectSemakin konkret contoh WRONG/CORRECT di .cursorrules, semakin konsisten Cursor mengikuti konvensi tim — file ini adalah investasi sekali tulis yang berdampak di setiap sesi Composer.
06.4 Composer: Fitur Utama Cursor untuk Go
Composer (Cmd+I atau Ctrl+I) adalah superpower Cursor: AI yang bisa mengedit puluhan file sekaligus. Prompt berikut menunjukkan use case pertama — implement satu fitur lengkap dengan mendaftar semua file yang harus dibuat atau diubah.
1Composer prompt:
2──────────────────────────────────────────
3Implement CancelOrder feature di Santekno Shop.
4
5Spec (AC yang harus terpenuhi):
6- DELETE /orders/:id dengan JWT auth
7- Hanya order PENDING bisa di-cancel
8- Cancel window: 30 menit
9- Restore stock atomically dalam transaction
10- Response: 204 No Content
11- Error codes: ORDER_NOT_FOUND, ORDER_NOT_CANCELLABLE, CANCEL_WINDOW_EXPIRED
12
13Files yang perlu dibuat/dimodifikasi:
141. internal/domain/order/entity.go — tambah CanBeCancelled() method
152. internal/domain/order/errors.go — tambah ErrCancelWindowExpired jika belum ada
163. internal/usecase/order/cancel_order.go — buat baru
174. internal/usecase/order/cancel_order_test.go — buat baru dengan testify/suite
185. internal/repository/postgres/order_repository.go — tambah CancelWithStockRestore
196. internal/delivery/http/handler/order_handler.go — tambah CancelOrder handler
207. internal/delivery/http/router/router.go — tambah route
21
22Follow patterns dari create_order.go yang sudah ada.
23──────────────────────────────────────────Kunci prompt yang efektif adalah mendaftar file secara eksplisit dan merujuk pattern yang sudah ada — Cursor lalu menghasilkan unified diff untuk ketujuh file yang bisa kamu review per file. Use case kedua adalah refactoring lintas codebase; prompt berikut mengubah pola error handling di seluruh direktori usecase.
1Composer prompt:
2──────────────────────────────────────────
3Refactoring: Update semua error handling di internal/usecase/
4dari pattern lama ke pattern baru.
5
6Pattern LAMA (ubah ini):
7 return err
8 return nil, err
9
10Pattern BARU (jadikan ini):
11 return fmt.Errorf("usecaseName.methodName: %w", err)
12 return nil, fmt.Errorf("usecaseName.methodName: %w", err)
13
14Rules:
15- Gunakan actual package name (cancelOrder, createOrder, dll)
16- Gunakan actual method name (Execute, Validate, dll)
17- Jangan ubah test files
18- Jangan ubah repository layer (pattern berbeda di sana)
19──────────────────────────────────────────Menyertakan rule eksplisit tentang apa yang tidak boleh diubah (test files, repository layer) mencegah Composer melakukan perubahan berlebihan. Use case ketiga adalah generate boilerplate dari pattern yang ada; prompt berikut mereplikasi struktur domain Order untuk domain Product.
1Composer prompt:
2──────────────────────────────────────────
3Generate CRUD usecase untuk Product domain.
4Follow PERSIS pola dari Order domain yang sudah ada.
5
6Order domain reference files:
7- internal/domain/order/entity.go
8- internal/usecase/order/create_order.go
9- internal/usecase/order/get_order.go
10- internal/repository/postgres/order_repository.go
11
12Product domain specs:
13- Product entity: ID, SKU, Name, Price (int64 cents), Stock (int), CategoryID
14- Use cases: CreateProduct, GetProduct, ListProducts, UpdateProduct
15- Repository: Create, GetByID, GetBySKU, List (with pagination), Update
16──────────────────────────────────────────Dengan menunjuk file referensi yang konkret, Cursor menghasilkan domain baru yang konsisten dengan konvensi proyek alih-alih menebak struktur dari nol.
06.5 Agent Mode: Autonomous Task Execution
Agent Mode memberi Cursor kemampuan browsing dokumentasi, menjalankan terminal command, dan mengambil keputusan berdasarkan output. Urutan berikut menggambarkan bagaimana Agent Mode menutup loop implement-build-test-fix secara mandiri.
1// Agent Mode example: Implement dan test feature
2
3// Prompt di Agent Mode:
4// "Implement CancelOrder dan verifikasi dengan tests"
5
6// Agent sequence:
7// 1. Read existing code untuk understand patterns
8// 2. Write implementation
9// 3. Run: go build ./... → check compile errors
10// 4. Fix compile errors
11// 5. Run: go test ./internal/usecase/order/... -v
12// 6. Fix failing tests
13// 7. Run: go test -race ./internal/usecase/order/...
14// 8. Fix race conditions jika ada
15// 9. Report: "Implementation complete, all tests pass"Kemampuan menjalankan command dan beriterasi dari output-nya membuat Agent Mode cocok untuk task yang well-defined. Contoh lain adalah upgrade dependency; alur berikut menunjukkan Agent menelusuri changelog sampai memverifikasi build.
1Agent Mode:
2"Upgrade pgx dari v5.5.0 ke v5.7.0"
3
4Agent:
51. Browse: github.com/jackc/pgx/releases (check changelog)
62. Identify breaking changes (misalnya: method signatures yang berubah)
73. Update go.mod
84. Run: go mod tidy
95. Run: go build ./... → find compile errors
106. Fix each compile error
117. Run: go test ./...
128. Report summaryAgent Mode paling aman untuk task dengan kriteria selesai yang jelas seperti upgrade dependency, di mana keberhasilan bisa diverifikasi otomatis lewat build dan test.
06.6 Inline Chat (Cmd+K): Quick In-Place Edits
Untuk edit yang lebih focused tanpa membuka Composer, Inline Chat (Cmd+K) mengedit langsung kode yang di-select. Contoh berikut memperlihatkan bagaimana satu fungsi repository diperbaiki di tempat.
1// Select function → Cmd+K:
2
3func (r *orderRepository) GetByIDAndUserID(
4 ctx context.Context,
5 orderID uuid.UUID,
6 userID uuid.UUID,
7) (*domain.Order, error) {
8 // ... existing implementation
9}
10
11// Inline prompt:
12// "Add context timeout 5 seconds and improve error messages"
13
14// Cursor edit in-place, no need to open ComposerInline Chat ideal untuk perubahan bedah pada satu fungsi — lebih cepat dari Composer ketika scope-nya hanya blok yang sedang kamu sorot.
06.7 RAG dan @Mentions
Cursor mengindeks seluruh codebase via RAG, tapi kamu bisa mengarahkan konteks lebih presisi dengan @mentions. Daftar berikut merangkum sintaks referensi yang paling berguna dalam workflow Go.
1# @file — reference specific file
2"Implement GetProductBySKU mengikuti pattern di @order_repository.go"
3
4# @folder — reference directory
5"Review semua files di @internal/usecase/order/ untuk error handling consistency"
6
7# @docs — reference documentation
8"Implement dengan mengikuti @docs/architecture.md guidelines"
9
10# @web — browse external documentation
11"Implement pgx v5 batch insert mengikuti @web docs"
12
13# Codebase search
14"Find semua places yang menggunakan float64 untuk monetary values"Referensi eksplisit dengan @file atau @folder jauh lebih andal daripada mengandalkan RAG untuk menebak konteks yang relevan — gunakan ketika akurasi penting.
06.8 .cursorignore: Optimize RAG
Kualitas RAG bergantung pada apa yang diindeks. File .cursorignore berikut mengecualikan artifact dan generated files agar retrieval fokus ke production code.
1# .cursorignore — exclude files dari indexing
2
3# Build artifacts
4**/bin/
5**/dist/
6**/.idea/
7**/.vscode/
8
9# Generated files (jangan index, pollute RAG)
10**/*.pb.go
11**/mock_*.go
12**/*_gen.go
13
14# Test fixtures dan testdata
15**/testdata/
16**/fixtures/
17
18# Vendor
19**/vendor/
20
21# CI/CD artifacts
22**/coverage.out
23**/coverage.htmlMengecualikan generated files (mock, proto) dari RAG indexing membuat code retrieval lebih akurat untuk production code, karena AI tidak lagi terganggu oleh kode boilerplate yang di-generate mesin.
06.9 Cursor Settings untuk Go Development
Pengaturan workspace yang tepat membuat Cursor berperilaku idiomatik untuk Go. Konfigurasi berikut mengatur lint, format, test flags, hingga model default.
1// .cursor/settings.json
2{
3 "cursor.general.gitIgnorePatterns": true,
4 "cursor.composer.context": "smart",
5
6 // Go-specific
7 "go.lintTool": "golangci-lint",
8 "go.lintOnSave": "workspace",
9 "go.formatTool": "goimports",
10 "go.testFlags": ["-v", "-race"],
11 "go.coverageDecorator": {
12 "type": "highlight"
13 },
14
15 // AI model preference
16 "cursor.general.defaultModel": "claude-3-5-sonnet-20241022"
17}Menyetel go.testFlags dengan -race dan go.formatTool ke goimports memastikan setiap simpan otomatis menegakkan standar yang sama dengan CI, sehingga output AI langsung selaras dengan konvensi proyek.
06.10 Cursor Model Selection: Pilih yang Tepat
Cursor mendukung banyak model, dan memilih yang tepat per task menghemat waktu sekaligus biaya. Panduan berikut memetakan setiap model ke jenis pekerjaan yang paling cocok.
1claude-3-5-sonnet:
2 Best untuk: complex features, architecture decisions, debugging
3 Speed: moderate
4 Cost: moderate (included di Cursor Pro)
5
6claude-3-haiku:
7 Best untuk: simple tasks, quick edits, test generation dari template
8 Speed: fast
9 Cost: low
10
11gpt-4o:
12 Best untuk: general coding, documentation
13 Speed: fast
14
15cursor-1 (Cursor's own model):
16 Best untuk: autocomplete, inline suggestions
17 Speed: very fast
18 Trained specifically on coding tasksGunakan Sonnet untuk task kompleks dan cursor-1/Haiku untuk autocomplete serta edit ringan — mencocokkan model dengan kompleksitas task adalah cara termudah menjaga responsivitas.
06.11 Cursor Workflow untuk Daily Go Development
Cursor paling produktif ketika dipakai dengan ritme harian yang jelas. Cuplikan berikut menggambarkan sesi pagi: planning dan implementasi kompleks lewat Composer.
1# Buka Cursor, buka project
2# Read .specify/features/ atau backlog
3# Open Composer (Cmd+I):
4
5"Hari ini saya akan implement GetOrdersByCustomer endpoint.
6Read spec di .specify/features/get-orders-by-customer/spec.md
7dan buat implementation plan sebelum kita mulai code.
8List semua files yang akan terpengaruh."
9
10# Composer: buat plan
11# Review plan
12# Approve dan executeMemulai hari dengan planning berbasis spec memastikan implementasi terarah. Beranjak siang, ritme bergeser ke iterasi dan verifikasi seperti berikut.
1# Composer atau inline chat untuk refinement:
2Cmd+K → "Add error handling untuk case product tidak aktif lagi"
3
4# Agent Mode untuk verification:
5"Run tests dan fix semua failing tests"
6
7# Check test coverage:
8# Cmd+Shift+P → "Go: Toggle Test Coverage"Siang hari adalah waktu iterasi cepat: edit fokus dengan Cmd+K dan verifikasi otomatis dengan Agent Mode. Menjelang sore, fokus berpindah ke review dan konsistensi seperti cuplikan berikut.
1# Inline chat untuk cleanup:
2# Select code → Cmd+K → "Improve comments, add godoc for exported functions"
3
4# Composer untuk consistency check:
5"Review semua files yang diubah hari ini untuk:
61. Error handling consistency
72. Test coverage gaps
83. CLAUDE.md compliance"Menutup hari dengan consistency check lewat Composer memastikan semua perubahan hari itu seragam sebelum masuk PR.
06.12 Cursor untuk Go Testing: Tips Khusus
Cursor sangat kuat untuk generate test. Prompt berikut menghasilkan test suite komprehensif dengan testify/suite dan gomock, memetakan setiap AC ke test case.
1Composer:
2"Generate complete test suite untuk CancelOrderUseCase menggunakan testify/suite + gomock.
3
4Cover:
5AC1: Happy path — PENDING order dalam 30 menit
6AC2: Order not found atau bukan milik user
7AC3: Order bukan PENDING
8AC4: Cancel window expired (> 30 menit)
9AC5: Atomic cancel fail (simulated DB error)
10EC1: Concurrent cancel (mock behavior)
11
12Gunakan table-driven tests untuk ACs yang memiliki similar setup.
13Refer ke create_order_test.go untuk suite structure pattern."Memetakan setiap AC ke test case secara eksplisit membuat Cursor menghasilkan coverage yang lengkap, bukan sekadar happy path. Untuk skenario konkuren, prompt berikut mengarahkan Cursor menulis integration test race.
1// Cursor sangat baik untuk generate race condition tests:
2// "Tulis integration test (//go:build integration) yang verify
3// bahwa concurrent cancel request pada order yang sama hanya
4// menghasilkan satu success. Gunakan sync.WaitGroup untuk
5// simulate concurrent requests."Test konkuren seperti ini penting untuk memvalidasi atomicity, dan Cursor dengan .cursorrules yang menyertakan concurrency rules menghasilkan kerangka yang layak. Terakhir, benchmark test membantu mengukur performa; prompt berikut memintanya.
1// "Generate benchmark test untuk CancelOrderUseCase.Execute:
2// - BenchmarkCancelOrder_Happy path
3// - BenchmarkCancelOrder_WithDBLatency (simulate 10ms latency)
4// Gunakan testing.B yang proper, dengan b.ResetTimer() setelah setup."Benchmark dengan b.ResetTimer() setelah setup memastikan pengukuran hanya mencakup kode yang diuji, bukan biaya persiapan — detail yang sering dilupakan tapi diingat Cursor bila diminta eksplisit.
06.13 Kekuatan dan Kelemahan: Ringkasan
Setelah membedah fitur-fiturnya, penting menimbang Cursor secara jujur. Kekuatan utamanya untuk Go development:
✅ Visual diff yang excellent — lihat persis apa yang berubah sebelum approve
✅ Composer untuk multi-file — implement feature yang touch 7 file dalam satu operation
✅ RAG yang solid — context-aware suggestions berdasarkan seluruh codebase
✅ IDE experience yang familiar — VSCode compatible, semua extension bekerja
✅ Flat-rate pricing — $20/bulan tanpa worry soal token usage
✅ Model switching — ganti model sesuai task tanpa restart IDE
Di sisi lain, ada kelemahan yang perlu kamu sadari:
❌ Context retention — .cursorrules kadang “dilupakan” di session panjang, lebih inconsistent dari CLAUDE.md
❌ Go idiom quality — sesekali generate kode yang perlu cleanup (float64 untuk monetary, error tanpa wrap)
❌ No native SDD — tidak ada spec-first workflow built-in (perlu manual dengan Composer prompts)
❌ Resource intensive — Cursor lebih berat dari VS Code, butuh RAM lebih banyak
Ringkasnya, Cursor menang di pengalaman visual dan multi-file editing, tapi kalah dari Claude Code di konsistensi konteks dan kualitas idiom Go — trade-off yang menentukan kapan memakai masing-masing.
06.14 Cursor vs Claude Code: Kapan Gunakan Masing-Masing
Karena keduanya sering dipakai bersama, penting tahu kapan memilih yang mana. Panduan berikut memisahkan tugas yang paling cocok untuk Cursor dari yang paling cocok untuk Claude Code.
1Gunakan Cursor untuk:
2✅ Implement feature yang menyentuh banyak file (Composer)
3✅ Visual review perubahan sebelum apply
4✅ Refactoring yang scope-nya jelas
5✅ Daily coding di dalam IDE
6✅ Budget yang predictable (flat-rate)
7
8Gunakan Claude Code untuk:
9✅ Complex planning dan reasoning
10✅ Deep debugging (race conditions, deadlocks)
11✅ SDD workflow (baca spec, plan, implement, verify)
12✅ Architecture discussions
13✅ Long autonomous sessions dengan verification
14
15Strategi terbaik: Cursor untuk 80% daily coding + Claude Code untuk 20% complex tasksPembagian 80/20 ini adalah pola yang banyak dipakai: Cursor menangani mayoritas coding harian, sementara Claude Code disimpan untuk task yang butuh penalaran mendalam.
06.15 Tips & Gotchas
💡 Tip 1: Always commit sebelum large Composer operations. Checkpoint membuat eksperimen bebas risiko.
1git add -A
2git commit -m "checkpoint before AI refactoring"
3# Sekarang Composer bisa bereksperimen bebas
4# Jika hasil tidak memuaskan: git reset --hardDengan checkpoint commit, operasi Composer skala besar menjadi reversible — hasil buruk cukup di-reset tanpa kehilangan pekerjaan.
💡 Tip 2: Gunakan “Accept” secara selective, bukan “Accept All”. Untuk perubahan di banyak file, review setiap file sebelum accept; Cursor menunjukkan diff per file — manfaatkan ini.
💡 Tip 3: @-mention untuk context yang lebih precise. Mereferensikan baris spesifik jauh lebih efektif daripada “follow existing patterns” yang ambigu, misalnya: "Implement cancellation logic mengikuti pola di @create_order.go baris 45-80".
💡 Tip 4: Gunakan YOLO mode dengan sangat hati-hati. YOLO mode (auto-execute tanpa confirmation) cocok untuk test environment yang bisa di-reset, task yang clear dan reversible, serta developer yang sudah sangat familiar dengan output AI. Jangan gunakan di production-adjacent tasks.
⚠️ Gotcha 1: .cursorrules scope. .cursorrules di root directory hanya berlaku untuk project tersebut; jika kamu buka folder berbeda, .cursorrules tidak terbawa. Pastikan file ini selalu ada di root project yang sedang dikerjakan.
⚠️ Gotcha 2: Composer context bisa miss file penting. Composer tidak selalu meng-include semua file relevan; jika output kurang akurat, sebutkan file konteks secara eksplisit seperti "Implement X. Gunakan ini sebagai referensi: @internal/usecase/order/create_order.go".
⚠️ Gotcha 3: Model billing di Cursor Pro. Cursor Pro ($20/bulan) meng-include usage “unlimited” tapi ada fair-use policy; untuk sangat heavy usage (>100 Composer requests/hari) mungkin ada throttling, dan Business plan ($40) ditujukan untuk heavy enterprise usage.
⚠️ Gotcha 4: RAG indexing butuh waktu untuk codebase besar. Codebase di atas 100K baris bisa butuh 5-15 menit untuk initial indexing; selama proses ini RAG suggestions kurang akurat, jadi tunggu indexing selesai sebelum mulai sesi intensif.
06.16 Cursor untuk Skenario Go yang Sering Terjadi
Teori menjadi jelas lewat contoh konkret. Skenario pertama adalah implement repository dengan pgx/v5; prompt berikut meminta operasi atomic cancel-plus-restore-stock dalam satu transaksi.
1Composer prompt:
2"Implement PostgreSQL repository untuk CancelOrder.
3Gunakan pgx/v5 pool (bukan pgxpool secara terpisah).
4Pattern dari @order_repository.go GetByID sebagai template.
5Harus support atomic operation: cancel order + restore stock dalam satu transaction.
6
7Signature yang dibutuhkan:
8CancelWithStockRestore(ctx context.Context, orderID uuid.UUID) error
9
10Transaction pattern: begin → cancel order → restore stock per item → commit
11Rollback jika salah satu step gagal."Dengan prompt yang menentukan signature dan pola transaksi, Cursor menghasilkan implementasi berikut — perhatikan defer rollback dan error wrapping yang konsisten.
1func (r *orderRepository) CancelWithStockRestore(
2 ctx context.Context,
3 orderID uuid.UUID,
4) error {
5 tx, err := r.pool.Begin(ctx)
6 if err != nil {
7 return fmt.Errorf("orderRepo.CancelWithStockRestore: begin tx: %w", err)
8 }
9 defer tx.Rollback(ctx) // no-op setelah commit
10
11 // Step 1: Update order status ke CANCELLED
12 cancelledAt := time.Now().UTC()
13 tag, err := tx.Exec(ctx, `
14 UPDATE orders
15 SET status = 'cancelled', cancelled_at = $1, updated_at = $1
16 WHERE id = $2 AND status = 'pending'
17 `, cancelledAt, orderID)
18 if err != nil {
19 return fmt.Errorf("orderRepo.CancelWithStockRestore: update order: %w", err)
20 }
21 if tag.RowsAffected() == 0 {
22 return fmt.Errorf("orderRepo.CancelWithStockRestore: order not found or not pending")
23 }
24
25 // Step 2: Restore stock untuk setiap item
26 rows, err := tx.Query(ctx, `
27 SELECT product_id, quantity FROM order_items WHERE order_id = $1
28 `, orderID)
29 if err != nil {
30 return fmt.Errorf("orderRepo.CancelWithStockRestore: query items: %w", err)
31 }
32 defer rows.Close()
33
34 for rows.Next() {
35 var productID uuid.UUID
36 var quantity int
37 if err := rows.Scan(&productID, &quantity); err != nil {
38 return fmt.Errorf("orderRepo.CancelWithStockRestore: scan item: %w", err)
39 }
40 if _, err := tx.Exec(ctx, `
41 UPDATE products SET stock = stock + $1 WHERE id = $2
42 `, quantity, productID); err != nil {
43 return fmt.Errorf("orderRepo.CancelWithStockRestore: restore stock: %w", err)
44 }
45 }
46 if err := rows.Err(); err != nil {
47 return fmt.Errorf("orderRepo.CancelWithStockRestore: rows: %w", err)
48 }
49
50 if err := tx.Commit(ctx); err != nil {
51 return fmt.Errorf("orderRepo.CancelWithStockRestore: commit: %w", err)
52 }
53 return nil
54}Output ini menunjukkan pola yang benar: defer rollback yang jadi no-op setelah commit, transaksi step-by-step, error wrapping penuh, dan cek RowsAffected untuk memastikan hanya order pending yang dibatalkan. Skenario kedua adalah generate middleware; prompt berikut meminta JWT auth middleware untuk Echo.
1Composer:
2"Implement JWT auth middleware untuk Echo v4.
3Gunakan github.com/golang-jwt/jwt/v5.
4Set user_id (uuid.UUID) ke echo context.
5Return 401 dengan {"error": "UNAUTHORIZED"} jika token invalid.
6Pattern error response dari @order_handler.go."Mereferensikan pattern error response yang sudah ada memastikan middleware baru konsisten dengan sisa handler. Skenario ketiga adalah generate table-driven test; prompt berikut mendefinisikan input dan kasus yang harus dicakup.
1Composer:
2"Generate table-driven test untuk ValidateOrderInput.
3Test dengan testify/suite.
4Cover: valid input, empty fields, invalid UUID, negative price.
5
6Input struct:
7type CreateOrderInput struct {
8 CustomerID uuid.UUID
9 Items []OrderItem
10 AddressID uuid.UUID
11}
12
13Gunakan subtests: s.Run(tc.name, func() { ... })"Menentukan kasus uji dan struktur subtests secara eksplisit membuat Cursor menghasilkan test yang terorganisir dan mudah diperluas.
06.17 Cursor Keyboard Shortcuts untuk Go Developer
Menguasai shortcut mempercepat workflow secara signifikan. Daftar berikut merangkum shortcut Cursor dan gopls yang paling sering dipakai dalam pengembangan Go.
1Cmd+I (Ctrl+I) → Buka Composer (primary AI interface)
2Cmd+K (Ctrl+K) → Inline edit (edit kode yang di-select)
3Cmd+L (Ctrl+L) → Buka Chat (tanya tanpa edit file)
4Cmd+Shift+P → Command palette (semua VS Code commands)
5
6Go-specific (via gopls):
7F12 → Go to definition
8Shift+F12 → Find all references
9Cmd+Shift+I → Implement interface (jika interface di-cursor)
10Cmd+. → Quick fix (auto-import, dll)
11Alt+Shift+F → Format file (go fmt via goimports)
12
13Test running:
14Cmd+Shift+T → Run test di file saat ini
15Cmd+Shift+R → Run test di cursor
16F5 → Start debugging (Delve)
17
18Navigation:
19Cmd+P → File search
20Cmd+Shift+F → Global search (search di semua file)
21Cmd+G → Go to lineTiga shortcut AI inti — Cmd+I (Composer), Cmd+K (inline), Cmd+L (chat) — adalah yang paling sering dipakai; menghafalnya saja sudah mempercepat mayoritas interaksi harian dengan Cursor.
06.18 Integrasi Cursor dengan Git Workflow
Cursor berpadu erat dengan git untuk membuat sesi AI aman dan terlacak. Alur berikut menunjukkan pola checkpoint sebelum, review selama, dan verifikasi setelah sesi Composer.
1# Pre-Composer: selalu checkpoint
2git add -A && git stash
3# Atau:
4git add -A && git commit -m "checkpoint before AI session $(date)"
5
6# Selama Composer session:
7# Cursor menunjukkan unified diff sebelum apply
8# Review setiap file → Accept atau Reject per-file
9
10# Post-Composer verification:
11go build ./...
12go test -race ./...
13git diff HEAD # lihat semua perubahan setelah accept all
14
15# Jika result tidak memuaskan:
16git reset --hard HEAD # back to checkpoint
17# Atau:
18git stash pop # restore stash
19
20# Branch strategy yang bagus untuk AI sessions:
21git checkout -b feat/cancel-order
22# Semua AI changes masuk ke branch ini
23# PR ke main dengan review yang properMenjalankan semua perubahan AI di branch terpisah dengan checkpoint di awal membuat setiap sesi Composer sepenuhnya reversible dan siap di-review lewat PR yang proper.
06.19 Cursor Composer: Pattern yang Paling Efektif untuk Go
Setelah pemakaian intensif, beberapa pola Composer terbukti paling konsisten menghasilkan output terbaik untuk Go. Pola pertama adalah template-based generation, yang jauh lebih efektif dari sekadar “implement CRUD”.
1"Generate [NewDomain] domain mengikuti PERSIS pattern dari [ExistingDomain].
2Files yang perlu dibuat:
31. internal/domain/[newdomain]/entity.go — copy structure dari order/entity.go
42. internal/domain/[newdomain]/errors.go — copy structure dari order/errors.go
53. internal/usecase/[newdomain]/create_[newdomain].go — dari create_order.go
64. [dst]
7
8Reference file: [src file list]"Memberi Cursor template eksplisit dari domain yang sudah ada mengurangi tebakan dan menjaga konsistensi struktur. Pola kedua adalah layer-by-layer dengan verification, di mana Cursor berhenti dan menampilkan diff setiap layer.
1Composer session:
2
3"Implement CancelOrder feature. Kerjakan layer by layer:
4
5Step 1: internal/domain/order/entity.go — add CanBeCancelled() method
6[selesai, user review diff]
7
8Step 2: internal/usecase/order/cancel_order.go — implement usecase
9[selesai, user review diff]
10
11Step 3: internal/repository/postgres/order_repository.go — add CancelWithStockRestore
12[selesai, user review diff]
13
14Step 4: internal/delivery/http/handler/order_handler.go — add handler
15Step 5: router update
16
17After each step, show me only that step's changes before proceeding."Memaksa review per layer mencegah perubahan menumpuk menjadi diff raksasa yang sulit diverifikasi. Pola ketiga adalah constraint-first, yang secara eksplisit membatasi apa yang boleh diubah.
1"Implement CancelOrder dengan constraint berikut (sangat penting):
2- JANGAN ubah files selain yang di-list
3- JANGAN tambahkan error handling yang tidak ada di spec
4- JANGAN ubah test files
5- Gunakan PERSIS package paths dari .cursorrules
6
7Files yang boleh diubah: [list]"Menyatakan batasan di depan adalah cara paling andal mencegah Composer melakukan perubahan berlebihan di luar scope yang kamu inginkan.
06.20 .cursorrules: Perbedaan dengan CLAUDE.md
Meski fungsinya sama, .cursorrules dan CLAUDE.md efektif dengan gaya penulisan yang berbeda. Perbandingan berikut menunjukkan konten yang sama diekspresikan dalam dua gaya.
1CLAUDE.md style (lebih structured):
2
3## Error Handling
4Repository not-found: return nil, nil
5Error wrap: fmt.Errorf("pkg.Method: %w", err)
6
7.cursorrules style (lebih conversational, karena LLM membaca ini differently):
8
9When implementing error handling in Go:
10- Repository not-found ALWAYS returns (nil, nil) — never an error
11- All error wraps MUST use fmt.Errorf("package.Method: %w", err) pattern
12- Example:
13 ```go
14 if errors.Is(err, pgx.ErrNoRows) {
15 return nil, nil
16 }
17 return nil, fmt.Errorf("orderRepo.GetByID: %w", err)1Intinya: .cursorrules lebih efektif dengan prosa plus contoh, sedangkan CLAUDE.md lebih efektif dengan header terstruktur — sesuaikan gaya dengan tool, bukan sekadar menyalin isi yang sama.
2
3---
4
5## 06.21 Cursor Agent Mode: Best Practices
6
7Agent Mode berbeda dari Composer karena fully autonomous. Panduan berikut merangkum perbedaannya sekaligus best practice memakainya dengan aman di proyek Go.Composer: Multi-file editing yang di-approve per step Agent Mode: Fully autonomous, bisa:
- Browse web untuk docs
- Run terminal commands
- Iterate berdasarkan error
- Edit multiple files tanpa approval
Best practices untuk Agent Mode di Go project:
Gunakan HANYA untuk well-defined tasks: “Implement dan test CancelOrder, semua layers” Bukan: “Improve codebase quality”
Set explicit constraints: “Hanya ubah internal/usecase/order/ dan internal/domain/order/”
Selalu review hasil setelah selesai: git diff → review semua perubahan go test ./… → verify masih pass
YOLO mode dengan sangat hati-hati: Hanya untuk low-risk tasks (dokumentasi, test generation) Tidak untuk business logic production code
1Kunci memakai Agent Mode dengan aman adalah task yang well-defined, constraint file yang eksplisit, dan review wajib dengan `git diff` plus `go test` setelah selesai.
2
3---
4
5## 06.22 Cursor untuk Go Monorepo
6
7Cursor bekerja baik untuk Go monorepo dengan beberapa teknik pengaturan. Panduan berikut merangkum setup .cursorrules berlapis, .cursorignore, dan referensi cross-service.Setup untuk monorepo:
Root .cursorrules dengan universal rules
Per-service .cursorrules (di subfolder) untuk service-specific (Cursor baca yang paling local dulu)
.cursorignore untuk exclude files dari indexing: **/vendor/ **/.pb.go ← generated proto files **/mock_.go ← generated mocks
Explicit @file untuk cross-service context: “@file order-service/internal/domain/order/entity.go @file notification-service/internal/consumer/order_consumer.go Verify event contract compatibility antara keduanya”
Workspace settings (cursor settings per workspace): { “cursor.indexingOptions”: { “excludePatterns”: ["/testdata/", “/*.sql”], “maxFileSizeKB”: 500 } }
1Kombinasi .cursorrules berlapis (universal di root, spesifik per service) dan @file eksplisit untuk konteks lintas service adalah cara efektif menjaga Cursor tetap akurat di monorepo besar.
2
3---
4
5## 06.23 Debugging dengan Cursor
6
7Cursor menyediakan beberapa alur debugging yang bisa dipilih sesuai situasi. Daftar berikut merangkum tiga flow utama beserta catatan untuk race condition di Go.Flow 1: Error-driven (paling common)
- Paste error ke Composer/Chat
- “@workspace bagaimana menyelesaikan ini?”
- Cursor analyze + propose fix + apply
Flow 2: Test-first debugging
- Write test yang failing
- “Make this test pass: @internal/usecase/order/cancel_order_test.go”
- Cursor implement
Flow 3: Trace-based
- “Trace this request dari handler ke database: POST /orders/:id/cancel”
- Cursor generate sequence diagram (mental) dan trace code
- Identify di mana issue terjadi
Untuk race conditions di Go: “Ini output dari go test -race: [paste output] @file [relevant files] Analyze dan fix race condition” Cursor + .cursorrules yang include concurrency rules = hasil yang decent tapi tidak sebaik Claude Code
1Untuk sebagian besar bug, flow error-driven sudah cukup; tapi untuk race condition yang rumit, Cursor memberi hasil decent sementara Claude Code tetap lebih unggul dalam kedalaman analisis.
2
3---
4
5## 06.24 Cost Analysis Cursor untuk Tim
6
7Biaya adalah pertimbangan nyata saat mengadopsi Cursor untuk tim. Rincian berikut membandingkan pricing Cursor per individu dan tim terhadap Claude Code.Cursor pricing breakdown untuk Go team:
Individual developer: Cursor Pro: $20/bulan Include: 500 fast requests/bulan (Claude Sonnet) Unlimited slow requests (slower model)
Team of 5: Cursor Business: $40/dev/bulan = $200/bulan total Include: admin controls, usage tracking
vs Claude Code untuk tim sama: Moderate usage: $50/dev = $250/bulan Heavy usage: $80/dev = $400/bulan
Cursor advantage: predictable dan lebih murah untuk medium-heavy users
Cursor limitation: tidak ada per-project billing Jika satu project besar dan banyak Composer session = bisa hit limit
1Keunggulan Cursor adalah biaya flat yang predictable dan lebih murah untuk pemakaian medium-heavy, dengan trade-off tidak adanya per-project billing yang bisa jadi kendala pada proyek sangat intensif.
2
3---
4
5## 06.25 Perbandingan: Cursor vs Tools Lain untuk Go
6
7Untuk menutup evaluasi, tabel berikut menyandingkan Cursor dengan Claude Code dan Copilot per jenis task, lengkap dengan pemenang tiap baris.
8
9| Task | Cursor | Claude Code | Copilot | Winner |
10|------|--------|-------------|---------|--------|
11| Multi-file implement | ⭐⭐⭐⭐⭐ | ⭐⭐⭐⭐ | ⭐⭐⭐ | Cursor |
12| Go idiom quality | ⭐⭐⭐⭐ | ⭐⭐⭐⭐⭐ | ⭐⭐⭐ | Claude |
13| Visual diff | ⭐⭐⭐⭐⭐ | ❌ | ❌ | Cursor |
14| Context retention | ⭐⭐⭐⭐ | ⭐⭐⭐⭐⭐ | ⭐⭐⭐ | Claude |
15| Inline suggestions | ⭐⭐⭐⭐ | ❌ | ⭐⭐⭐⭐⭐ | Copilot |
16| PR review automation | ❌ | ❌ | ⭐⭐⭐⭐⭐ | Copilot |
17| Cost predictability | ✅ $20 flat | ❌ Variable | ✅ $10 flat | Copilot |
18| Large refactoring | ⭐⭐⭐⭐⭐ | ⭐⭐⭐⭐ | ⭐⭐⭐ | Cursor |
19| SDD workflow | ⭐⭐⭐ | ⭐⭐⭐⭐⭐ | ⭐⭐ | Claude |
20
21Tabel ini menegaskan tidak ada pemenang tunggal: Cursor unggul di multi-file dan visual diff, Claude Code di idiom Go dan SDD, Copilot di inline suggestion dan PR automation — konfirmasi bahwa multi-tool strategy sering jadi jawaban terbaik.
22
23---
24
25## 06.26 Ringkasan
26
27Cursor adalah pilihan terbaik untuk Go developer yang nyaman dengan VSCode-based IDE, sering melakukan multi-file editing, butuh visual diff sebelum apply perubahan, dan menginginkan flat-rate pricing yang predictable. Familiaritas IDE juga membuat adopsi tim lebih mudah dibanding CLI.
28
29Kelemahan utamanya — context retention yang kalah dari CLAUDE.md dan SDD workflow yang lebih manual — bisa di-mitigasi dengan .cursorrules yang sangat baik (referensi ke existing patterns), pairing dengan Claude Code untuk planning dan spec work, serta @file references yang eksplisit untuk konteks penting.
30
31Untuk best of both worlds, jadikan Cursor primary IDE untuk 80% daily coding dan Claude Code untuk 20% task yang butuh deep reasoning. Di artikel berikutnya kita bahas tool ketiga yang punya kekuatan sangat berbeda: GitHub Copilot dengan Chat, Completions, dan Workspace.
32
33
Danger