Skip to content

Advanced Examples

Complex real-world scenarios showcasing goTableView's full capabilities.

Example 1: Large Dataset with Pagination

Handle thousands of rows efficiently:

go
package main

import (
    "fmt"
    "time"
    "github.com/mansoldof/goTableView"
)

type LogEntry struct {
    ID        int       `gotableview:"#"`
    Timestamp time.Time `gotableview:"Time"`
    Level     string    `gotableview:"Level"`
    Source    string    `gotableview:"Source"`
    Message   string    `gotableview:"Message"`
}

func main() {
    // Generate 5000 log entries
    logs := make([]LogEntry, 5000)
    levels := []string{"INFO", "WARN", "ERROR", "DEBUG"}
    sources := []string{"API", "Database", "Cache", "Queue", "Auth"}
    
    for i := range logs {
        logs[i] = LogEntry{
            ID:        i + 1,
            Timestamp: time.Now().Add(-time.Duration(i) * time.Minute),
            Level:     levels[i%len(levels)],
            Source:    sources[i%len(sources)],
            Message:   fmt.Sprintf("Log message #%d with detailed information", i+1),
        }
    }
    
    gotableview.FromStructsPaginated("Application Logs", logs, 100).
        SearchInColumns("Level", "Source").
        Show()
}
Screenshot: Large log viewer with 5000 entries, showing page 1 of 50, with search filtering by Level and Source

Example 2: Database Query Results

Display results from SQL queries:

go
package main

import (
    "database/sql"
    "log"
    "github.com/mansoldof/goTableView"
    _ "github.com/mattn/go-sqlite3"
)

type Customer struct {
    ID          int     `gotableview:"Customer ID"`
    Name        string  `gotableview:"Name"`
    Email       string  `gotableview:"Email"`
    TotalOrders int     `gotableview:"Orders"`
    TotalSpent  float64 `gotableview:"Total Spent"`
    JoinedDate  string  `gotableview:"Member Since"`
}

func main() {
    db, err := sql.Open("sqlite3", "./customers.db")
    if err != nil {
        log.Fatal(err)
    }
    defer db.Close()
    
    query := `
        SELECT 
            c.id, c.name, c.email, 
            COUNT(o.id) as total_orders,
            COALESCE(SUM(o.total), 0) as total_spent,
            c.created_at
        FROM customers c
        LEFT JOIN orders o ON c.id = o.customer_id
        GROUP BY c.id
        ORDER BY total_spent DESC
    `
    
    rows, err := db.Query(query)
    if err != nil {
        log.Fatal(err)
    }
    defer rows.Close()
    
    var customers []Customer
    for rows.Next() {
        var c Customer
        rows.Scan(&c.ID, &c.Name, &c.Email, &c.TotalOrders, &c.TotalSpent, &c.JoinedDate)
        customers = append(customers, c)
    }
    
    gotableview.FromStructsPaginated("Customer Analytics", customers, 50).
        WithSearch().
        Show()
}
Screenshot: Customer analytics table showing customer data with order counts and spending totals

Example 3: JSON API Response

Fetch and display API data:

go
package main

import (
    "encoding/json"
    "fmt"
    "net/http"
    "github.com/mansoldof/goTableView"
)

type Repository struct {
    Name        string `json:"name" gotableview:"Repository"`
    Description string `json:"description" gotableview:"Description"`
    Stars       int    `json:"stargazers_count" gotableview:"⭐ Stars"`
    Forks       int    `json:"forks_count" gotableview:"🔀 Forks"`
    Language    string `json:"language" gotableview:"Language"`
    OpenIssues  int    `json:"open_issues_count" gotableview:"Issues"`
}

func main() {
    // Fetch Go repositories from GitHub API
    url := "https://api.github.com/search/repositories?q=language:go&sort=stars&per_page=50"
    
    resp, err := http.Get(url)
    if err != nil {
        fmt.Println("Error:", err)
        return
    }
    defer resp.Body.Close()
    
    var result struct {
        Items []Repository `json:"items"`
    }
    
    json.NewDecoder(resp.Body).Decode(&result)
    
    gotableview.FromStructsPaginated("Top Go Repositories", result.Items, 20).
        WithColumnSelector().
        Show()
}
Screenshot: GitHub repositories table with repository names, descriptions, stars, forks, and languages

Example 4: CSV File Analyzer

Read and analyze large CSV files:

go
package main

import (
    "encoding/csv"
    "fmt"
    "os"
    "strconv"
    "github.com/mansoldof/goTableView"
)

type SalesRecord struct {
    Date     string  `gotableview:"Date"`
    Product  string  `gotableview:"Product"`
    Category string  `gotableview:"Category"`
    Quantity int     `gotableview:"Qty"`
    Revenue  float64 `gotableview:"Revenue"`
    Region   string  `gotableview:"Region"`
}

func main() {
    file, err := os.Open("sales_data.csv")
    if err != nil {
        fmt.Println("Error:", err)
        return
    }
    defer file.Close()
    
    reader := csv.NewReader(file)
    records, err := reader.ReadAll()
    if err != nil {
        fmt.Println("Error:", err)
        return
    }
    
    // Skip header row
    var sales []SalesRecord
    for _, record := range records[1:] {
        qty, _ := strconv.Atoi(record[3])
        revenue, _ := strconv.ParseFloat(record[4], 64)
        
        sales = append(sales, SalesRecord{
            Date:     record[0],
            Product:  record[1],
            Category: record[2],
            Quantity: qty,
            Revenue:  revenue,
            Region:   record[5],
        })
    }
    
    gotableview.FromStructsPaginated("Sales Data Analysis", sales, 100).
        SearchInColumns("Product", "Category", "Region").
        Show()
}
Screenshot: CSV data viewer showing sales records with filtering by Product, Category, and Region

Example 5: System Process Monitor

Display running processes:

go
package main

import (
    "fmt"
    "os/exec"
    "strings"
    "github.com/mansoldof/goTableView"
)

func main() {
    // Get process list (Windows)
    cmd := exec.Command("tasklist", "/FO", "CSV", "/NH")
    output, err := cmd.Output()
    if err != nil {
        fmt.Println("Error:", err)
        return
    }
    
    lines := strings.Split(string(output), "\n")
    
    table := gotableview.NewPaginated("Running Processes", 50)
    table.Columns("Process Name", "PID", "Session", "Memory")
    
    for _, line := range lines {
        if line == "" {
            continue
        }
        
        // Parse CSV line
        parts := strings.Split(line, "\",\"")
        if len(parts) >= 4 {
            processName := strings.Trim(parts[0], "\"")
            pid := strings.Trim(parts[1], "\"")
            session := strings.Trim(parts[2], "\"")
            memory := strings.Trim(parts[4], "\"")
            
            table.Row(processName, pid, session, memory)
        }
    }
    
    table.WithSearch().Show()
}
Screenshot: Process monitor showing running Windows processes with searchable list

Example 6: Configuration Comparison

Compare multiple configurations:

go
package main

import "github.com/mansoldof/goTableView"

type ConfigSetting struct {
    Setting     string `gotableview:"Setting"`
    Development string `gotableview:"Development"`
    Staging     string `gotableview:"Staging"`
    Production  string `gotableview:"Production"`
    Description string `gotableview:"Description"`
}

func main() {
    config := []ConfigSetting{
        {"DB_HOST", "localhost", "staging-db.internal", "prod-db.internal", "Database host"},
        {"DB_PORT", "5432", "5432", "5432", "Database port"},
        {"DEBUG", "true", "false", "false", "Debug mode"},
        {"LOG_LEVEL", "debug", "info", "warn", "Logging level"},
        {"CACHE_TTL", "60", "300", "600", "Cache TTL (seconds)"},
        {"MAX_CONNECTIONS", "10", "50", "100", "Max DB connections"},
        {"TIMEOUT", "30", "60", "120", "Request timeout (seconds)"},
    }
    
    gotableview.FromStructs("Environment Configuration", config).Show()
}
Screenshot: Configuration comparison table showing settings across three environments

Example 7: Network Scanner Results

Display network scan results:

go
package main

import (
    "fmt"
    "net"
    "time"
    "github.com/mansoldof/goTableView"
)

type HostInfo struct {
    IP       string `gotableview:"IP Address"`
    Hostname string `gotableview:"Hostname"`
    Status   string `gotableview:"Status"`
    Latency  string `gotableview:"Latency"`
}

func main() {
    subnet := "192.168.1"
    var hosts []HostInfo
    
    for i := 1; i <= 255; i++ {
        ip := fmt.Sprintf("%s.%d", subnet, i)
        
        start := time.Now()
        conn, err := net.DialTimeout("tcp", ip+":80", 100*time.Millisecond)
        latency := time.Since(start)
        
        status := "Down"
        latencyStr := "-"
        hostname := "-"
        
        if err == nil {
            status = "Up"
            latencyStr = fmt.Sprintf("%dms", latency.Milliseconds())
            conn.Close()
            
            names, _ := net.LookupAddr(ip)
            if len(names) > 0 {
                hostname = names[0]
            }
        }
        
        hosts = append(hosts, HostInfo{
            IP:       ip,
            Hostname: hostname,
            Status:   status,
            Latency:  latencyStr,
        })
    }
    
    gotableview.FromStructsPaginated("Network Scan Results", hosts, 50).
        SearchInColumns("IP Address", "Status").
        Show()
}
Screenshot: Network scanner showing IP addresses, hostnames, status, and latency for subnet scan

Example 8: Multi-source Data Aggregation

Combine data from multiple sources:

go
package main

import (
    "encoding/json"
    "os"
    "github.com/mansoldof/goTableView"
)

type Employee struct {
    ID         int     `gotableview:"ID"`
    Name       string  `gotableview:"Name"`
    Department string  `gotableview:"Department"`
    Salary     float64 `gotableview:"Salary"`
    Projects   int     `gotableview:"Active Projects"`
    Performance string  `gotableview:"Rating"`
}

func main() {
    // Load from JSON file
    file1, _ := os.Open("employees.json")
    var employeesJSON []Employee
    json.NewDecoder(file1).Decode(&employeesJSON)
    file1.Close()
    
    // Load from another JSON file
    file2, _ := os.Open("contractors.json")
    var contractorsJSON []Employee
    json.NewDecoder(file2).Decode(&contractorsJSON)
    file2.Close()
    
    // Combine all data
    allStaff := append(employeesJSON, contractorsJSON...)
    
    gotableview.FromStructsPaginated("All Staff Members", allStaff, 50).
        WithColumnSelector().
        Show()
}
Screenshot: Combined staff data from multiple sources with column selector for filtering

Example 9: Performance Metrics Dashboard

Display performance metrics:

go
package main

import (
    "fmt"
    "math/rand"
    "time"
    "github.com/mansoldof/goTableView"
)

type Metric struct {
    Timestamp string  `gotableview:"Time"`
    Endpoint  string  `gotableview:"Endpoint"`
    Requests  int     `gotableview:"Requests/min"`
    AvgTime   float64 `gotableview:"Avg Response (ms)"`
    ErrorRate float64 `gotableview:"Error Rate (%)"`
    Status    string  `gotableview:"Status"`
}

func main() {
    endpoints := []string{"/api/users", "/api/orders", "/api/products", "/api/auth", "/api/search"}
    var metrics []Metric
    
    for i := 0; i < 200; i++ {
        endpoint := endpoints[rand.Intn(len(endpoints))]
        requests := rand.Intn(1000) + 100
        avgTime := rand.Float64()*200 + 50
        errorRate := rand.Float64() * 5
        
        status := "Normal"
        if errorRate > 3 {
            status = "Warning"
        }
        if avgTime > 200 {
            status = "Slow"
        }
        
        metrics = append(metrics, Metric{
            Timestamp: time.Now().Add(-time.Duration(i) * time.Minute).Format("15:04:05"),
            Endpoint:  endpoint,
            Requests:  requests,
            AvgTime:   avgTime,
            ErrorRate: errorRate,
            Status:    status,
        })
    }
    
    gotableview.FromStructsPaginated("API Performance Metrics", metrics, 50).
        SearchInColumns("Endpoint", "Status").
        Show()
}
Screenshot: Performance dashboard showing API metrics with time, requests, response times, and status

Example 10: Data Validation Report

Validate and report data quality issues:

go
package main

import (
    "fmt"
    "github.com/mansoldof/goTableView"
)

type ValidationResult struct {
    RowNumber int    `gotableview:"Row"`
    Field     string `gotableview:"Field"`
    Value     string `gotableview:"Value"`
    Issue     string `gotableview:"Issue"`
    Severity  string `gotableview:"Severity"`
}

func main() {
    // Simulated validation results
    results := []ValidationResult{
        {1, "Email", "invalid.email", "Invalid email format", "Error"},
        {3, "Phone", "123", "Phone number too short", "Warning"},
        {5, "Age", "-5", "Age cannot be negative", "Error"},
        {7, "Salary", "", "Required field missing", "Error"},
        {9, "ZipCode", "ABCDE", "Invalid zip code format", "Warning"},
        {12, "Email", "test@", "Incomplete email address", "Error"},
        {15, "Name", "", "Required field missing", "Error"},
        {18, "Phone", "555-ABCD", "Invalid phone format", "Warning"},
    }
    
    gotableview.FromStructs("Data Validation Report", results).Show()
}
Screenshot: Validation report showing data quality issues with row numbers, fields, and severity levels

Performance Tips

1. Use Appropriate Page Sizes

go
// Small dataset (< 500 rows)
gotableview.NewPaginated("Data", 50).Rows(data).Show()

// Medium dataset (500-5000 rows)
gotableview.NewPaginated("Data", 100).Rows(data).Show()

// Large dataset (5000+ rows)
gotableview.NewPaginated("Data", 200).Rows(data).Show()

2. Limit Search Columns

go
// Slow - searches all 15 columns
gotableview.NewPaginated("Data", 100).
    Columns("Col1", "Col2", ..., "Col15").
    WithSearch().
    Show()

// Fast - searches only relevant columns
gotableview.NewPaginated("Data", 100).
    Columns("Col1", "Col2", ..., "Col15").
    SearchInColumns("Col1", "Col3").  // Only search these
    Show()

3. Pre-format Data

go
// Less efficient - formatting on demand
for _, item := range items {
    table.Row(
        fmt.Sprintf("%d", item.ID),
        item.Name,
        fmt.Sprintf("%.2f", item.Price),
    )
}

// More efficient - use FromStructs
gotableview.FromStructs("Items", items).Show()

What's Next?

Released under the MIT License.