---
title: "Go Style Guide"
description: "Go coding standards (if Go components exist)"
keywords: [go, golang, style, coding standards]
---

# Go Style Guide

Go coding standards for TraceRTM (if Go components are used).

## Formatting

### gofmt

Always format code with `gofmt`:

```bash
# Format code
gofmt -w .

# Check formatting
gofmt -d .
```

### goimports

Use `goimports` for import management:

```bash
# Install
go install golang.org/x/tools/cmd/goimports@latest

# Format with imports
goimports -w .
```

## Naming Conventions

### Packages

```go
// Package names are lowercase, single word
package tracertm

// Avoid underscores, hyphens, or mixed case
// Bad: package tracertm_api
// Good: package tracertm
```

### Exported Names

```go
// Exported names start with capital letter
type Item struct {
    ID    string
    Title string
}

// Unexported names start with lowercase
type itemRepository struct {
    db *sql.DB
}
```

### Interfaces

```go
// Interface names often end with -er
type Reader interface {
    Read([]byte) (int, error)
}

type ItemRepository interface {
    GetByID(id string) (*Item, error)
}
```

## Code Organization

### File Structure

```go
package tracertm

// 1. Package declaration
// 2. Imports
import (
    "fmt"
    "net/http"
)

// 3. Constants
const (
    DefaultLimit = 100
    MaxLimit     = 1000
)

// 4. Variables
var (
    apiURL = "https://api.tracertm.dev"
)

// 5. Types
type Item struct {
    ID    string
    Title string
}

// 6. Functions
func GetItem(id string) (*Item, error) {
    // ...
}
```

## Error Handling

### Return Errors

```go
// Always return errors explicitly
func GetItem(id string) (*Item, error) {
    if id == "" {
        return nil, fmt.Errorf("id cannot be empty")
    }
    // ...
    return item, nil
}
```

### Error Wrapping

```go
import "errors"

func ProcessItem(id string) error {
    item, err := GetItem(id)
    if err != nil {
        return fmt.Errorf("failed to get item: %w", err)
    }
    // ...
    return nil
}
```

## Best Practices

### 1. Use Context

```go
import "context"

func GetItem(ctx context.Context, id string) (*Item, error) {
    // Use context for cancellation, timeouts
    select {
    case <-ctx.Done():
        return nil, ctx.Err()
    default:
        // Continue
    }
    // ...
}
```

### 2. Avoid Panics

```go
// Bad - panic in library code
func GetItem(id string) *Item {
    if id == "" {
        panic("id cannot be empty")
    }
    // ...
}

// Good - return error
func GetItem(id string) (*Item, error) {
    if id == "" {
        return nil, fmt.Errorf("id cannot be empty")
    }
    // ...
}
```

### 3. Document Exported Functions

```go
// GetItem retrieves an item by ID.
//
// Returns an error if the item is not found or if there's
// a database error.
func GetItem(id string) (*Item, error) {
    // ...
}
```

## Related Documentation

- [Code Style](./01-code-style) - General code style
