style: Apply code formatting with go fmt

- Run 'make format' to ensure all Go code follows standard formatting
- Maintains consistent code style across the entire codebase
- No functional changes, only whitespace and formatting improvements
This commit is contained in:
Ole-Morten Duesund 2025-09-01 10:05:29 +02:00
commit 2bffa2c418
19 changed files with 543 additions and 527 deletions

View file

@ -29,5 +29,6 @@ import "embed"
// external file deployment or complicated asset management. // external file deployment or complicated asset management.
// //
// Updated to include database.html for database status page // Updated to include database.html for database status page
//
//go:embed static //go:embed static
var Static embed.FS var Static embed.FS

View file

@ -19,28 +19,28 @@ import (
// Shared configuration structures (should match main skyview) // Shared configuration structures (should match main skyview)
type Config struct { type Config struct {
Server ServerConfig `json:"server"` Server ServerConfig `json:"server"`
Sources []SourceConfig `json:"sources"` Sources []SourceConfig `json:"sources"`
Settings Settings `json:"settings"` Settings Settings `json:"settings"`
Database *database.Config `json:"database,omitempty"` Database *database.Config `json:"database,omitempty"`
Callsign *CallsignConfig `json:"callsign,omitempty"` Callsign *CallsignConfig `json:"callsign,omitempty"`
Origin OriginConfig `json:"origin"` Origin OriginConfig `json:"origin"`
} }
type CallsignConfig struct { type CallsignConfig struct {
Enabled bool `json:"enabled"` Enabled bool `json:"enabled"`
CacheHours int `json:"cache_hours"` CacheHours int `json:"cache_hours"`
PrivacyMode bool `json:"privacy_mode"` PrivacyMode bool `json:"privacy_mode"`
Sources map[string]CallsignSourceConfig `json:"sources"` Sources map[string]CallsignSourceConfig `json:"sources"`
ExternalAPIs map[string]ExternalAPIConfig `json:"external_apis,omitempty"` ExternalAPIs map[string]ExternalAPIConfig `json:"external_apis,omitempty"`
} }
type CallsignSourceConfig struct { type CallsignSourceConfig struct {
Enabled bool `json:"enabled"` Enabled bool `json:"enabled"`
Priority int `json:"priority"` Priority int `json:"priority"`
License string `json:"license"` License string `json:"license"`
RequiresConsent bool `json:"requires_consent,omitempty"` RequiresConsent bool `json:"requires_consent,omitempty"`
UserAcceptsTerms bool `json:"user_accepts_terms,omitempty"` UserAcceptsTerms bool `json:"user_accepts_terms,omitempty"`
} }
type ExternalAPIConfig struct { type ExternalAPIConfig struct {
@ -458,7 +458,9 @@ func cmdUpdate(db *database.Database, sources []string, force bool) error {
if len(result.Errors) > 0 { if len(result.Errors) > 0 {
log.Printf(" %d errors occurred during import (first few):", len(result.Errors)) log.Printf(" %d errors occurred during import (first few):", len(result.Errors))
for i, errMsg := range result.Errors { for i, errMsg := range result.Errors {
if i >= 3 { break } if i >= 3 {
break
}
log.Printf(" %s", errMsg) log.Printf(" %s", errMsg)
} }
} }
@ -683,4 +685,3 @@ func cmdOptimize(db *database.Database, force bool) error {
fmt.Println("\n✅ Database optimization completed!") fmt.Println("\n✅ Database optimization completed!")
return nil return nil
} }

View file

@ -32,24 +32,24 @@ type APIClientConfig struct {
} }
type OpenSkyFlightInfo struct { type OpenSkyFlightInfo struct {
ICAO string `json:"icao"` ICAO string `json:"icao"`
Callsign string `json:"callsign"` Callsign string `json:"callsign"`
Origin string `json:"origin"` Origin string `json:"origin"`
Destination string `json:"destination"` Destination string `json:"destination"`
FirstSeen time.Time `json:"first_seen"` FirstSeen time.Time `json:"first_seen"`
LastSeen time.Time `json:"last_seen"` LastSeen time.Time `json:"last_seen"`
AircraftType string `json:"aircraft_type"` AircraftType string `json:"aircraft_type"`
Registration string `json:"registration"` Registration string `json:"registration"`
FlightNumber string `json:"flight_number"` FlightNumber string `json:"flight_number"`
Airline string `json:"airline"` Airline string `json:"airline"`
} }
type APIError struct { type APIError struct {
Operation string Operation string
StatusCode int StatusCode int
Message string Message string
Retryable bool Retryable bool
RetryAfter time.Duration RetryAfter time.Duration
} }
func (e *APIError) Error() string { func (e *APIError) Error() string {

View file

@ -19,11 +19,11 @@ import (
// Database represents the main database connection and operations // Database represents the main database connection and operations
type Database struct { type Database struct {
conn *sql.DB conn *sql.DB
config *Config config *Config
migrator *Migrator migrator *Migrator
callsign *CallsignManager callsign *CallsignManager
history *HistoryManager history *HistoryManager
} }
// Config holds database configuration options // Config holds database configuration options
@ -32,7 +32,7 @@ type Config struct {
Path string `json:"path"` Path string `json:"path"`
// Data retention settings // Data retention settings
MaxHistoryDays int `json:"max_history_days"` // 0 = unlimited MaxHistoryDays int `json:"max_history_days"` // 0 = unlimited
BackupOnUpgrade bool `json:"backup_on_upgrade"` BackupOnUpgrade bool `json:"backup_on_upgrade"`
// Connection settings // Connection settings
@ -41,13 +41,13 @@ type Config struct {
ConnMaxLifetime time.Duration `json:"conn_max_lifetime"` // Default: 1 hour ConnMaxLifetime time.Duration `json:"conn_max_lifetime"` // Default: 1 hour
// Maintenance settings // Maintenance settings
VacuumInterval time.Duration `json:"vacuum_interval"` // Default: 24 hours VacuumInterval time.Duration `json:"vacuum_interval"` // Default: 24 hours
CleanupInterval time.Duration `json:"cleanup_interval"` // Default: 1 hour CleanupInterval time.Duration `json:"cleanup_interval"` // Default: 1 hour
// Compression settings // Compression settings
EnableCompression bool `json:"enable_compression"` // Enable automatic compression EnableCompression bool `json:"enable_compression"` // Enable automatic compression
CompressionLevel int `json:"compression_level"` // Compression level (1-9, default: 6) CompressionLevel int `json:"compression_level"` // Compression level (1-9, default: 6)
PageSize int `json:"page_size"` // SQLite page size (default: 4096) PageSize int `json:"page_size"` // SQLite page size (default: 4096)
} }
// AircraftHistoryRecord represents a stored aircraft position update // AircraftHistoryRecord represents a stored aircraft position update
@ -93,18 +93,18 @@ type AirlineRecord struct {
// AirportRecord represents embedded airport data from OpenFlights // AirportRecord represents embedded airport data from OpenFlights
type AirportRecord struct { type AirportRecord struct {
ID int `json:"id"` ID int `json:"id"`
Name string `json:"name"` Name string `json:"name"`
City string `json:"city"` City string `json:"city"`
Country string `json:"country"` Country string `json:"country"`
IATA string `json:"iata"` IATA string `json:"iata"`
ICAO string `json:"icao"` ICAO string `json:"icao"`
Latitude float64 `json:"latitude"` Latitude float64 `json:"latitude"`
Longitude float64 `json:"longitude"` Longitude float64 `json:"longitude"`
Altitude int `json:"altitude"` Altitude int `json:"altitude"`
TimezoneOffset float64 `json:"timezone_offset"` TimezoneOffset float64 `json:"timezone_offset"`
DST string `json:"dst"` DST string `json:"dst"`
Timezone string `json:"timezone"` Timezone string `json:"timezone"`
} }
// DatabaseError represents database operation errors // DatabaseError represents database operation errors
@ -240,7 +240,6 @@ func (db *Database) Health() error {
return db.conn.Ping() return db.conn.Ping()
} }
// DefaultConfig returns the default database configuration // DefaultConfig returns the default database configuration
func DefaultConfig() *Config { func DefaultConfig() *Config {
return &Config{ return &Config{

View file

@ -37,12 +37,12 @@ type DataSource struct {
// LoadResult contains the results of a data loading operation // LoadResult contains the results of a data loading operation
type LoadResult struct { type LoadResult struct {
Source string `json:"source"` Source string `json:"source"`
RecordsTotal int `json:"records_total"` RecordsTotal int `json:"records_total"`
RecordsNew int `json:"records_new"` RecordsNew int `json:"records_new"`
RecordsError int `json:"records_error"` RecordsError int `json:"records_error"`
Duration time.Duration `json:"duration"` Duration time.Duration `json:"duration"`
Errors []string `json:"errors,omitempty"` Errors []string `json:"errors,omitempty"`
} }
// NewDataLoader creates a new data loader with HTTP client // NewDataLoader creates a new data loader with HTTP client
@ -208,10 +208,18 @@ func (dl *DataLoader) loadOpenFlightsAirlines(reader io.Reader, source DataSourc
active := len(record) > 7 && strings.Trim(record[7], `"`) == "Y" active := len(record) > 7 && strings.Trim(record[7], `"`) == "Y"
// Convert \N to empty strings // Convert \N to empty strings
if alias == "\\N" { alias = "" } if alias == "\\N" {
if iata == "\\N" { iata = "" } alias = ""
if icao == "\\N" { icao = "" } }
if callsign == "\\N" { callsign = "" } if iata == "\\N" {
iata = ""
}
if icao == "\\N" {
icao = ""
}
if callsign == "\\N" {
callsign = ""
}
_, err = insertStmt.Exec(id, name, alias, iata, icao, callsign, country, active, source.Name) _, err = insertStmt.Exec(id, name, alias, iata, icao, callsign, country, active, source.Name)
if err != nil { if err != nil {
@ -298,10 +306,18 @@ func (dl *DataLoader) loadOpenFlightsAirports(reader io.Reader, source DataSourc
timezone := strings.Trim(record[11], `"`) timezone := strings.Trim(record[11], `"`)
// Convert \N to empty strings // Convert \N to empty strings
if iata == "\\N" { iata = "" } if iata == "\\N" {
if icao == "\\N" { icao = "" } iata = ""
if dst == "\\N" { dst = "" } }
if timezone == "\\N" { timezone = "" } if icao == "\\N" {
icao = ""
}
if dst == "\\N" {
dst = ""
}
if timezone == "\\N" {
timezone = ""
}
_, err = insertStmt.Exec(id, name, city, country, iata, icao, lat, lon, alt, tzOffset, dst, timezone, source.Name) _, err = insertStmt.Exec(id, name, city, country, iata, icao, lat, lon, alt, tzOffset, dst, timezone, source.Name)
if err != nil { if err != nil {
@ -497,7 +513,6 @@ func (dl *DataLoader) recordDataSource(tx *sql.Tx, source DataSource) error {
return err return err
} }
// ClearDataSource removes all data from a specific source // ClearDataSource removes all data from a specific source
func (dl *DataLoader) ClearDataSource(sourceName string) error { func (dl *DataLoader) ClearDataSource(sourceName string) error {
tx, err := dl.conn.Begin() tx, err := dl.conn.Begin()

View file

@ -34,8 +34,8 @@ func TestDataLoader_LoadOpenFlightsAirlines(t *testing.T) {
if err != nil { if err != nil {
// Network issues in tests are acceptable // Network issues in tests are acceptable
if strings.Contains(err.Error(), "connection") || if strings.Contains(err.Error(), "connection") ||
strings.Contains(err.Error(), "timeout") || strings.Contains(err.Error(), "timeout") ||
strings.Contains(err.Error(), "no such host") { strings.Contains(err.Error(), "no such host") {
t.Skipf("Skipping network test due to connectivity issue: %v", err) t.Skipf("Skipping network test due to connectivity issue: %v", err)
} }
t.Fatal("LoadDataSource failed:", err) t.Fatal("LoadDataSource failed:", err)
@ -73,8 +73,8 @@ func TestDataLoader_LoadOurAirports(t *testing.T) {
if err != nil { if err != nil {
// Network issues in tests are acceptable // Network issues in tests are acceptable
if strings.Contains(err.Error(), "connection") || if strings.Contains(err.Error(), "connection") ||
strings.Contains(err.Error(), "timeout") || strings.Contains(err.Error(), "timeout") ||
strings.Contains(err.Error(), "no such host") { strings.Contains(err.Error(), "no such host") {
t.Skipf("Skipping network test due to connectivity issue: %v", err) t.Skipf("Skipping network test due to connectivity issue: %v", err)
} }
t.Fatal("LoadDataSource failed:", err) t.Fatal("LoadDataSource failed:", err)

View file

@ -21,15 +21,15 @@ func TestCallsignManager_ParseCallsign(t *testing.T) {
manager := NewCallsignManager(db.GetConnection()) manager := NewCallsignManager(db.GetConnection())
testCases := []struct { testCases := []struct {
callsign string callsign string
expectedValid bool expectedValid bool
expectedAirline string expectedAirline string
expectedFlight string expectedFlight string
}{ }{
{"UAL123", true, "UAL", "123"}, {"UAL123", true, "UAL", "123"},
{"BA4567", true, "BA", "4567"}, {"BA4567", true, "BA", "4567"},
{"AFR89", true, "AFR", "89"}, {"AFR89", true, "AFR", "89"},
{"N123AB", false, "", ""}, // Aircraft registration, not callsign {"N123AB", false, "", ""}, // Aircraft registration, not callsign
{"INVALID", false, "", ""}, // No numbers {"INVALID", false, "", ""}, // No numbers
{"123", false, "", ""}, // Only numbers {"123", false, "", ""}, // Only numbers
{"A", false, "", ""}, // Too short {"A", false, "", ""}, // Too short

View file

@ -86,9 +86,9 @@ func (om *OptimizationManager) OptimizeDatabase() error {
fmt.Println("Optimizing database for storage efficiency...") fmt.Println("Optimizing database for storage efficiency...")
// Apply storage-friendly pragmas // Apply storage-friendly pragmas
optimizations := []struct{ optimizations := []struct {
name string name string
query string query string
description string description string
}{ }{
{"Auto VACUUM", "PRAGMA auto_vacuum = INCREMENTAL", "Enable incremental auto-vacuum"}, {"Auto VACUUM", "PRAGMA auto_vacuum = INCREMENTAL", "Enable incremental auto-vacuum"},
@ -184,13 +184,13 @@ func (om *OptimizationManager) GetOptimizationStats() (*OptimizationStats, error
// OptimizationStats holds database storage optimization statistics // OptimizationStats holds database storage optimization statistics
type OptimizationStats struct { type OptimizationStats struct {
DatabaseSize int64 `json:"database_size"` DatabaseSize int64 `json:"database_size"`
PageSize int `json:"page_size"` PageSize int `json:"page_size"`
PageCount int `json:"page_count"` PageCount int `json:"page_count"`
UsedPages int `json:"used_pages"` UsedPages int `json:"used_pages"`
FreePages int `json:"free_pages"` FreePages int `json:"free_pages"`
Efficiency float64 `json:"efficiency_percent"` Efficiency float64 `json:"efficiency_percent"`
AutoVacuumEnabled bool `json:"auto_vacuum_enabled"` AutoVacuumEnabled bool `json:"auto_vacuum_enabled"`
LastVacuum time.Time `json:"last_vacuum"` LastVacuum time.Time `json:"last_vacuum"`
} }
// getDatabaseSize returns the current database file size in bytes // getDatabaseSize returns the current database file size in bytes

View file

@ -221,13 +221,13 @@ func TestOptimizationManager_InvalidPath(t *testing.T) {
func TestOptimizationStats_JSON(t *testing.T) { func TestOptimizationStats_JSON(t *testing.T) {
stats := &OptimizationStats{ stats := &OptimizationStats{
DatabaseSize: 1024000, DatabaseSize: 1024000,
PageSize: 4096, PageSize: 4096,
PageCount: 250, PageCount: 250,
UsedPages: 200, UsedPages: 200,
FreePages: 50, FreePages: 50,
Efficiency: 80.0, Efficiency: 80.0,
AutoVacuumEnabled: true, AutoVacuumEnabled: true,
LastVacuum: time.Now(), LastVacuum: time.Now(),
} }
// Test that all fields are accessible // Test that all fields are accessible

View file

@ -55,13 +55,13 @@ type OriginConfig struct {
// - Concurrent broadcast system for WebSocket clients // - Concurrent broadcast system for WebSocket clients
// - CORS support for cross-origin web applications // - CORS support for cross-origin web applications
type Server struct { type Server struct {
host string // Bind address for HTTP server host string // Bind address for HTTP server
port int // TCP port for HTTP server port int // TCP port for HTTP server
merger *merger.Merger // Data source for aircraft information merger *merger.Merger // Data source for aircraft information
database *database.Database // Optional database for persistence database *database.Database // Optional database for persistence
staticFiles embed.FS // Embedded static web assets staticFiles embed.FS // Embedded static web assets
server *http.Server // HTTP server instance server *http.Server // HTTP server instance
origin OriginConfig // Geographic reference point origin OriginConfig // Geographic reference point
// WebSocket management // WebSocket management
wsClients map[*websocket.Conn]bool // Active WebSocket client connections wsClients map[*websocket.Conn]bool // Active WebSocket client connections
@ -1036,7 +1036,7 @@ func (s *Server) handleGetCallsignInfo(w http.ResponseWriter, r *http.Request) {
} }
response := map[string]interface{}{ response := map[string]interface{}{
"callsign": callsignInfo, "callsign": callsignInfo,
"timestamp": time.Now().Unix(), "timestamp": time.Now().Unix(),
} }