Documentation
Languages and Frameworks/Go

Go Support

ThinkCode offers robust support for Go development, providing an integrated environment with specialized tools, intelligent code assistance, and powerful features designed to enhance productivity when working with Go projects.

Getting Started

Setup and Configuration

ThinkCode automatically detects Go projects. For optimal experience:

  1. Install Go Extension:

    • ThinkCode will prompt to install the Go extension when you open a Go file
    • Alternatively, open the Extensions view (Ctrl+Shift+X / Cmd+Shift+X) and search for "ThinkCode Go"
  2. Install Go:

    • Ensure Go is installed on your system
    • ThinkCode will detect the Go installation automatically
    • Configure Go version in settings if needed
  3. Project Configuration:

    • ThinkCode supports standard Go project structures
    • Automatically recognizes go.mod files for module support
    • Configures the Go environment variables
  4. Create a New Project:

    • Command Palette (Ctrl+Shift+P / Cmd+Shift+P)
    • Type "ThinkCode: Create New Project"
    • Select Go from template categories
    • Choose from templates:
      • Basic Go application
      • Go module
      • Web application (Gin, Echo, etc.)
      • RESTful API service
      • gRPC service

IntelliSense and Code Navigation

Code Intelligence

ThinkCode provides advanced intelligence for Go:

  • Auto-Completion: Context-aware suggestions for:
    • Functions and methods
    • Struct fields
    • Package imports
    • Variables
  • Type Information: Detailed type information with tooltips
  • Signature Help: Parameter info for functions
  • Quick Documentation: Access godoc directly in the editor

Example of Go code with intelligent assistance:

// ThinkCode provides intelligent assistance for Go
package main
 
import (
	"fmt"
	"time"
)
 
// Person represents a person with name and birth date
type Person struct {
	Name     string
	BirthDate time.Time
}
 
// Age calculates the person's age in years
func (p Person) Age() int {
	now := time.Now()
	years := now.Year() - p.BirthDate.Year()
	
	// Adjust age if birthday hasn't occurred yet this year
	birthDay := time.Date(now.Year(), p.BirthDate.Month(), p.BirthDate.Day(), 0, 0, 0, 0, time.Local)
	if now.Before(birthDay) {
		years--
	}
	
	return years
}
 
func main() {
	// ThinkCode provides intelligent completion
	person := Person{
		Name:     "John Doe",
		BirthDate: time.Date(1990, time.January, 15, 0, 0, 0, 0, time.UTC),
	}
	
	fmt.Printf("%s is %d years old\n", person.Name, person.Age())
}

Smart Navigation

Navigate your codebase efficiently:

  • Go to Definition: Jump to declarations

    • Keyboard: F12 or Ctrl+Click / Cmd+Click
    • Works across packages and dependencies
  • Find All References: Locate all usages of a symbol

    • Keyboard: Shift+F12
    • Results organized by file and location
  • Go to Implementation: Jump to implementations of interfaces

    • Keyboard: Ctrl+F12 / Cmd+F12
  • Outline View: Explore the structure of Go files

    • Keyboard: Ctrl+Shift+O / Cmd+Shift+O
    • Shows functions, types, and methods
  • Workspace Symbols: Search across all Go files

    • Keyboard: Ctrl+T / Cmd+T

Import Management

Efficient handling of Go imports:

  • Auto-Import: Automatically add missing imports
  • Optimize Imports: Remove unused imports and organize
  • Import Completion: Intelligent package suggestions
  • Vendored Dependency Support: Navigate into vendor packages

Configure import behavior:

{
  "thinkcode.go.import": {
    "autoComplete": true,
    "organize": true,
    "local": "",  // Define local packages (e.g., "company.com/project")
    "grouping": ["std", "local", "other"]  // Import grouping order
  }
}

AI-Powered Development Features

Smart Code Generation

Generate Go code with natural language prompts:

  1. Function Generation:

    • Add a comment describing function purpose
    • Press Alt+I / Option+I for AI implementation

    Example:

    // Generate a function that returns paginated results from a slice
    // Press Alt+I here and ThinkCode generates the implementation
    func paginate[T any](items []T, page, pageSize int) []T {
        if page < 1 || pageSize < 1 {
            return []T{}
        }
        
        startIndex := (page - 1) * pageSize
        if startIndex >= len(items) {
            return []T{}
        }
        
        endIndex := startIndex + pageSize
        if endIndex > len(items) {
            endIndex = len(items)
        }
        
        return items[startIndex:endIndex]
    }
  2. Struct Generation:

    • Describe struct purpose in a comment
    • ThinkCode generates a complete type with fields and methods
  3. Test Generation:

    • Select function to test
    • Right-click and select "Generate Test"
    • ThinkCode generates table-driven tests for the function

Code Refactoring

AI-assisted refactoring capabilities:

  • Extract Function: Extract code into a new function
  • Rename Symbol: Intelligently rename variables, functions, and types
  • Convert to Interface: Extract interface from concrete type
  • Fill Struct: Complete struct initialization
  • Generate Constructor: Create constructor functions

Access refactoring tools:

  1. Right-click in editor
  2. Select "Refactor" menu
  3. Choose desired refactoring operation

Documentation Assistant

Generate and maintain Go documentation:

  • Comment Generation: Auto-generate godoc-style comments
  • Example Code: Generate example usage code
  • README Creation: Generate project documentation
  • API Documentation: Create API reference documentation

Example of AI-assisted documentation:

// Place cursor here and use Command Palette > "Generate Documentation"
// ProcessItems takes a collection of items and processes them according to the provided options.
// It applies the transformer function to each item that passes the filter check.
// If parallel is true, processing will be distributed across multiple goroutines.
//
// The function returns:
//  - A slice of transformed items that passed the filter
//  - An error if any individual transformation fails
//
// Processing stops on the first error encountered. If you need to collect all errors,
// use ProcessItemsCollectErrors instead.
//
// Example usage:
//
//     items := []int{1, 2, 3, 4, 5}
//     filter := func(i int) bool { return i%2 == 0 }
//     transformer := func(i int) (string, error) { return fmt.Sprintf("Value: %d", i*i), nil }
//     
//     results, err := ProcessItems(items, filter, transformer, true)
//     if err != nil {
//         log.Fatalf("Processing failed: %v", err)
//     }
//     
//     // results contains: ["Value: 4", "Value: 16"]
func ProcessItems[T any, R any](
    items []T,
    filter func(T) bool,
    transformer func(T) (R, error),
    parallel bool,
) ([]R, error) {
    // Implementation...
}

Project Management

Package Management

Efficient handling of Go modules and dependencies:

  • Module Explorer: View and navigate module dependencies
  • Dependency Graph: Visualize dependency relationships
  • Version Management: Update and manage dependency versions
  • Vulnerability Scanning: Identify security issues in dependencies

Access module tools:

  1. Open the Go Module view
  2. Right-click on dependencies to manage them
  3. Use "Add Dependency" to add new dependencies

Project Structure

Manage Go project organization:

  • Project Templates: Standard layout for new projects
  • Refactoring Tools: Reorganize packages and files
  • Go Workspaces: Support for Go workspace mode (multiple modules)
  • Monorepo Support: Work efficiently with monorepo structures

Debugging and Testing

Debugging

Powerful Go debugging capabilities:

  • Integrated Debugger: Debug Go applications directly in ThinkCode
  • Breakpoints:
    • Condition breakpoints
    • Hit count breakpoints
    • Logpoints (print without stopping)
  • Variable Inspection: Examine variables and complex data structures
  • Goroutine Inspection: View and navigate goroutines
  • Remote Debugging: Debug applications on remote machines

Example launch configuration:

// .vscode/launch.json
{
  "version": "0.2.0",
  "configurations": [
    {
      "name": "Launch Go Program",
      "type": "thinkcode-go",
      "request": "launch",
      "mode": "auto",
      "program": "${workspaceFolder}/cmd/main.go",
      "env": {
        "ENV_VAR": "value"
      },
      "args": ["-config", "config.json"]
    }
  ]
}

Testing

Integrated support for Go testing:

  • Test Explorer: View and run tests with visual UI
  • Coverage Visualization: Highlight code coverage in editor
  • Test Generation: AI-assisted test creation
  • Benchmark Tools: Run and analyze benchmarks

Run tests with:

  1. Click on test gutter icons
  2. Right-click on test function
  3. Use Test Explorer view

Configure testing behavior:

{
  "thinkcode.go.testing": {
    "enabled": true,
    "coverage": true,
    "buildFlags": [],
    "coverageDecorator": {
      "type": "highlight",
      "coveredHighlightColor": "rgba(64, 128, 128, 0.2)",
      "uncoveredHighlightColor": "rgba(128, 64, 64, 0.2)"
    }
  }
}

Code Quality and Analysis

Linting and Formatting

Integrated code quality tools:

  • Go Fmt: Automatic code formatting
  • Staticcheck: Advanced static analysis
  • Golint: Style checking
  • Go Vet: Correctness checking

Configure linting and formatting:

{
  "thinkcode.go.linting": {
    "enabled": true,
    "linters": {
      "staticcheck": true,
      "golint": true,
      "govet": true,
      "gofmt": true,
      "golangci-lint": true
    },
    "formatOnSave": true,
    "lint": {
      "all": true,
      "composites": true,
      "assignments": true
    }
  }
}

Code Analysis

Advanced code analysis features:

  • Dead Code Detection: Identify unused code
  • Complexity Analysis: Measure cyclomatic complexity
  • Race Condition Detection: Find potential concurrency issues
  • Error Handling Analysis: Verify proper error handling

Access analysis tools:

  1. Command Palette
  2. Type "ThinkCode: Analyze Go Code"
  3. Select analysis type

Security Analysis

Go-specific security scanning:

  • Vulnerability Checking: Detect common vulnerabilities
  • Dependency Scanning: Check for CVEs in dependencies
  • Secret Detection: Find hardcoded secrets
  • Input Validation: Verify proper input handling

Performance Tools

Performance Analysis

Identify and fix Go performance issues:

  • CPU Profiling: Find CPU-intensive code
  • Memory Profiling: Track allocations and heap usage
  • Goroutine Analysis: Detect goroutine leaks
  • Benchmarking Tools: Measure and compare code performance

Access performance tools:

  1. Command Palette
  2. Type "ThinkCode: Profile Go Code"
  3. Select profiling type

Example benchmarking integration:

// ThinkCode provides intelligent performance analysis
func BenchmarkSort(b *testing.B) {
    for i := 0; i < b.N; i++ {
        data := generateRandomData(1000)
        sort.Slice(data, func(i, j int) bool {
            return data[i] < data[j]
        })
    }
    // ThinkCode shows performance metrics and suggestions
}

Optimization Suggestions

Get intelligent suggestions for improving performance:

  • Allocation Reduction: Minimize memory allocations
  • Concurrency Improvements: Better goroutine usage
  • Algorithm Selection: More efficient algorithms
  • I/O Optimization: Improve file and network operations

Framework Integration

ThinkCode provides specialized support for popular Go frameworks:

Web Frameworks

Support for common Go web frameworks:

  • Gin: Route completion and handler navigation
  • Echo: Middleware and context assistance
  • Fiber: API completion and documentation
  • Gorilla: Router and session management tools

gRPC Support

Enhanced support for gRPC development:

  • Protocol Buffer Integration: Syntax highlighting and validation
  • Service Navigation: Jump between service definitions and implementations
  • Client Generation: Generate and manage gRPC clients
  • Testing Tools: Test gRPC services

Database Access

Support for database interactions:

  • SQL Queries: Validation and formatting
  • ORM Support: GORM, SQLx intelligence
  • Migration Tools: Database schema management
  • Query Visualization: Visualize query execution plans

Containerization and Deployment

Docker Integration

Develop containerized Go applications:

  • Dockerfile Generation: Create optimized Dockerfiles for Go
  • Multi-stage Build Support: Create efficient container images
  • Container Debugging: Debug Go code inside containers
  • Docker Compose: Manage multi-container environments

Example Dockerfile generation:

# ThinkCode generates optimized Dockerfiles for Go
FROM golang:1.20-alpine AS build
 
WORKDIR /app
COPY go.mod go.sum ./
RUN go mod download
 
COPY . .
RUN CGO_ENABLED=0 GOOS=linux go build -o /app/service ./cmd/main.go
 
FROM alpine:3.17
RUN apk --no-cache add ca-certificates
WORKDIR /app
COPY --from=build /app/service /app/service
COPY --from=build /app/configs /app/configs
 
EXPOSE 8080
CMD ["/app/service"]

Kubernetes Integration

Deploy Go applications to Kubernetes:

  • Manifest Generation: Create Kubernetes manifests
  • Resource Visualization: View and manage K8s resources
  • Helm Chart Support: Work with Helm charts
  • Deployment Tools: Deploy and monitor applications

Cloud Platform Support

Deploy Go applications to cloud platforms:

  • AWS Lambda: Develop and deploy serverless functions
  • Google Cloud Run: Container deployment tools
  • Azure Functions: Function app development
  • Heroku: One-click deployment

Customization

Extension Points

Extend ThinkCode's Go support:

  • Custom Linters: Integrate specialized linting rules
  • Code Generators: Implement custom code generators
  • Analysis Tools: Add custom analysis capabilities
  • Build Tasks: Configure custom build workflows

Configuration Options

Comprehensive configuration for Go development:

{
  "thinkcode.go": {
    "gopath": "",
    "goroot": "",
    "toolsGopath": "",
    "languageServer": {
      "enabled": true,
      "flags": [],
      "diagnosticsEnabled": true,
      "watchFileChanges": true,
      "maxNumberOfProblems": 100
    },
    "format": {
      "tool": "gofmt", // Options: "gofmt", "goimports", "goreturns"
      "options": {},
      "formatOnSave": true
    },
    "buildFlags": [],
    "lintFlags": [],
    "vetFlags": [],
    "coverMode": "atomic", // Options: "set", "count", "atomic"
    "coverageOptions": "showBothCoveredAndUncoveredCode",
    "testTimeout": "30s",
    "testFlags": []
  }
}

Resources and Learning

Learning Paths

Integrated learning resources:

  • Interactive Tutorials: Learn Go concepts
  • Code Challenges: Practice with hands-on exercises
  • Sample Projects: Explore and learn from example projects
  • Best Practice Guides: Context-sensitive coding guidelines

Access learning resources:

  1. Command Palette
  2. Type "ThinkCode: Open Learning Hub"
  3. Select Go category

Community Integration

Connect with the Go community:

  • Documentation: Access Go documentation inline
  • Package Discovery: Find and explore Go packages
  • Stack Overflow: Search solutions directly from ThinkCode
  • Go Playground: Share code via the Go Playground

Common Go Development Scenarios

Web Service Development

Specialized tools for building web services:

  • API Blueprint: Design and document REST APIs
  • Middleware Support: Manage request pipeline
  • Authentication: Common auth pattern implementations
  • OpenAPI Integration: Generate and consume OpenAPI specs

Microservices Architecture

Support for microservice development:

  • Service Templates: Standard microservice layouts
  • Service Discovery: Tools for connecting services
  • Configuration Management: Environment and config tools
  • Resilience Patterns: Circuit breaker, retry, timeout implementations

Command Line Applications

Tools for building CLI applications:

  • CLI Frameworks: Support for Cobra, Urfave/CLI
  • Argument Parsing: Intelligent completion for flag packages
  • Terminal UI: Tools for building TUI applications
  • Progress Reporting: Implement progress indicators

Further Information