### Start Base Framework Server Source: https://github.com/base-go/base-core/blob/main/static/README.md Command to initialize the Base Framework server. ```bash base start ``` -------------------------------- ### Initialize Cache Providers Source: https://github.com/base-go/base-core/blob/main/CACHING.md Examples for creating Memory, Redis, and No-op cache instances. ```go // Create memory cache memoryCache := cache.NewMemoryCache(cache.MemoryConfig{ MaxSize: 10000, CleanupInterval: 5 * time.Minute, }) // Create Redis cache redisCache, err := cache.NewRedisCache(cache.RedisConfig{ Host: "localhost", Port: "6379", Password: "", DB: 0, Prefix: "myapp:", }) // Create no-op cache noopCache := cache.NewNoopCache() ``` -------------------------------- ### Create and Start a New Project Source: https://github.com/base-go/base-core/blob/main/README.md Workflow to initialize a new project and launch the development server. ```bash # Create a new project base new myapp cd myapp # Start the development server with hot reload base start ``` -------------------------------- ### Install Base CLI Source: https://github.com/base-go/base-core/blob/main/README.md Use the curl command to install the Base CLI tool. ```bash curl -fsSL https://get.base.al | bash ``` -------------------------------- ### Environment Configuration Source: https://github.com/base-go/base-core/blob/main/README.md Example of the .env file structure used for database, storage, and email configuration. ```bash SERVER_ADDRESS=:8100 JWT_SECRET=your_jwt_secret API_KEY=your_api_key # Database DB_HOST=localhost DB_PORT=5432 DB_NAME=myapp DB_USER=postgres DB_PASSWORD=postgres # Storage STORAGE_DRIVER=local # local, s3, r2 STORAGE_PATH=storage # Email MAIL_DRIVER=smtp # smtp, sendgrid, postmark MAIL_HOST=smtp.mailtrap.io MAIL_PORT=2525 MAIL_USERNAME=username MAIL_PASSWORD=password ``` -------------------------------- ### Implement Cache-Aside Pattern Source: https://github.com/base-go/base-core/blob/main/CACHING.md Example of checking the cache before querying the database and storing the result. ```go import ( "context" "time" ) func (s *MyService) GetUser(userID uint) (*User, error) { ctx := context.Background() cacheKey := fmt.Sprintf("user:%d", userID) // Try cache first var user User err := s.Cache.Get(ctx, cacheKey, &user) if err == nil { return &user, nil // Cache hit! } // Cache miss - query database if err := s.DB.First(&user, userID).Error; err != nil { return nil, err } // Cache the result s.Cache.Set(ctx, cacheKey, user, 15*time.Minute) return &user, nil } ``` -------------------------------- ### Model and Service Implementation Source: https://github.com/base-go/base-core/blob/main/README.md Example showing how models are defined in app/models and consumed by services to maintain clean dependencies. ```go // app/models/post.go package models type Post struct { types.Model Title string `json:"title" gorm:"not null"` Content string `json:"content" gorm:"type:text"` AuthorId uint `json:"author_id"` Author User `json:"author" gorm:"foreignKey:AuthorId"` // Can reference User model Comments []Comment `json:"comments" gorm:"foreignKey:PostId"` // Can reference Comment model } // app/posts/service.go package posts import "base/app/models" // Clean import, no circular dependency type PostService struct { db *gorm.DB emitter *emitter.Emitter } func (s *PostService) Create(post *models.Post) error { if err := s.db.Create(post).Error; err != nil { return err } s.emitter.Emit("post.created", post) return nil } ``` -------------------------------- ### WebSocket Connection Example Source: https://github.com/base-go/base-core/blob/main/static/README.md JavaScript snippet demonstrating how to connect to the WebSocket server with required query parameters. ```javascript const socket = new WebSocket('ws://localhost:8100/api/ws?id=user123&nickname=John&room=general'); ``` -------------------------------- ### Consistent Key Naming Conventions Source: https://github.com/base-go/base-core/blob/main/CACHING.md Examples of recommended versus discouraged key naming patterns. ```go // Good ✅ "user:123" "user:email:john@example.com" "user:permissions:123" // Bad ❌ "user_123" "email-john@example.com" "permissions_for_user_123" ``` -------------------------------- ### Complete ProductService Caching Implementation Source: https://github.com/base-go/base-core/blob/main/CACHING.md A comprehensive example showing how to integrate cache with a GORM-based service. It demonstrates the pattern of checking the cache before querying the database, setting cache values with TTL, and invalidating cache entries upon updates. ```go package myservice import ( "base/core/cache" "context" "fmt" "time" "gorm.io/gorm" ) type ProductService struct { DB *gorm.DB Cache cache.Cache } func NewProductService(db *gorm.DB, c cache.Cache) *ProductService { return &ProductService{DB: db, Cache: c} } func (s *ProductService) GetProduct(id uint) (*Product, error) { ctx := context.Background() cacheKey := fmt.Sprintf("product:%d", id) // Try cache var product Product err := s.Cache.Get(ctx, cacheKey, &product) if err == nil { return &product, nil } // Query DB if err := s.DB.First(&product, id).Error; err != nil { return nil, err } // Cache result s.Cache.Set(ctx, cacheKey, product, 30*time.Minute) return &product, nil } func (s *ProductService) UpdateProduct(product *Product) error { // Update DB if err := s.DB.Save(product).Error; err != nil { return err } // Invalidate cache ctx := context.Background() cacheKey := fmt.Sprintf("product:%d", product.ID) s.Cache.Delete(ctx, cacheKey) return nil } func (s *ProductService) GetProductsByCategory(categoryID uint) ([]Product, error) { ctx := context.Background() cacheKey := fmt.Sprintf("products:category:%d", categoryID) // Try cache var products []Product err := s.Cache.Get(ctx, cacheKey, &products) if err == nil { return products, nil } // Query DB if err := s.DB.Where("category_id = ?", categoryID).Find(&products).Error; err != nil { return nil, err } // Cache result (shorter TTL for lists) s.Cache.Set(ctx, cacheKey, products, 5*time.Minute) return products, nil } ``` -------------------------------- ### Complete HMVC Post module implementation Source: https://github.com/base-go/base-core/blob/main/README.md A full example demonstrating the separation of concerns across models, controllers, services, and module registration. ```go // app/models/post.go package models type Post struct { types.Model Title string `json:"title" gorm:"not null"` Content string `json:"content" gorm:"type:text"` Published bool `json:"published" gorm:"default:false"` AuthorId uint `json:"author_id"` Author User `json:"author" gorm:"foreignKey:AuthorId"` Tags []Tag `json:"tags" gorm:"many2many:post_tags;"` Comments []Comment `json:"comments" gorm:"foreignKey:PostId"` } // app/posts/controller.go package posts type PostController struct { service *PostService logger logger.Logger } func (c *PostController) Routes(router *router.RouterGroup) { router.GET("", c.List) router.GET("/:id", c.Get) router.POST("", c.Create) router.PUT("/:id", c.Update) router.DELETE("/:id", c.Delete) } // app/posts/service.go package posts type PostService struct { db *gorm.DB userService *user.Service emitter *emitter.Emitter } func (s *PostService) Create(post *models.Post) error { if err := s.db.Create(post).Error; err != nil { return err } s.emitter.Emit("post.created", post) return nil } // app/posts/module.go package posts type PostModule struct { controller *PostController service *PostService } func NewPostModule(db *gorm.DB, router *router.RouterGroup, log logger.Logger, emitter *emitter.Emitter) module.Module { service := &PostService{ db: db, emitter: emitter, } controller := &PostController{ service: service, logger: log, } return &PostModule{ controller: controller, service: service, } } ``` -------------------------------- ### HTTP Cache Middleware Setup Source: https://github.com/base-go/base-core/blob/main/CACHING.md Configures the CacheMiddleware for a specific route, defining TTL, cacheable statuses, and methods. ```go import ( "base/core/router/middleware" "time" ) // Apply to specific routes router.GET("/api/public/posts", handler, middleware.CacheMiddleware(cache, middleware.CacheMiddlewareConfig{ TTL: 5 * time.Minute, CacheableStatuses: []int{200}, CacheableMethods: []string{"GET"}, VaryByQueryParams: true, }), ) ``` -------------------------------- ### Setting Cache TTLs Source: https://github.com/base-go/base-core/blob/main/CACHING.md Examples of setting different Time-To-Live durations based on data volatility. ```go // Frequently changing data - Short TTL cache.Set(ctx, "session:"+sessionID, session, 5*time.Minute) // Rarely changing data - Long TTL cache.Set(ctx, "config:site", config, 1*time.Hour) // Static data - Very long TTL cache.Set(ctx, "metadata:app", metadata, 24*time.Hour) ``` -------------------------------- ### HTTP Cache Hit and Miss Example Source: https://github.com/base-go/base-core/blob/main/CACHING.md Demonstrates the X-Cache header behavior using curl for an initial request and a subsequent cached request. ```bash # First request - Cache miss curl -i http://localhost:8100/api/posts # X-Cache: MISS # Time: 50ms # Second request - Cache hit curl -i http://localhost:8100/api/posts # X-Cache: HIT # Time: 1ms ⚡ ``` -------------------------------- ### Get Cache Entry Source: https://github.com/base-go/base-core/blob/main/CACHING.md Retrieve a value from the cache and handle cache misses. ```go var user User err := cache.Get(ctx, "user:123", &user) if cache.IsMiss(err) { // Cache miss - fetch from DB } ``` -------------------------------- ### Authorization Service Cache Hit Example Source: https://github.com/base-go/base-core/blob/main/CACHING.md Demonstrates the performance difference between an initial cache miss and a subsequent cache hit when calling GetUserPermissions. ```go // First call - Cache miss (queries DB) perms, err := authzService.GetUserPermissions("123") // Time: ~50ms // Second call - Cache hit perms, err := authzService.GetUserPermissions("123") // Time: <1ms ⚡ ``` -------------------------------- ### Send Password Reset Email Source: https://github.com/base-go/base-core/blob/main/docs.md Example of sending a password reset email containing a dynamic link. ```go func (s *UserService) SendPasswordResetEmail(user *models.User, token string) error { resetURL := fmt.Sprintf("%s/reset-password?token=%s", config.AppURL, token) msg := email.Message{ To: []string{user.Email}, Subject: "Password Reset Request", Body: fmt.Sprintf(`
Hello %s,
We received a request to reset your password. Click the link below to proceed:
If you didn't request this, please ignore this email.
The link will expire in 1 hour.
`, user.Name, resetURL), IsHTML: true, } if err := s.Email.Send(msg); err != nil { s.Logger.Error("Failed to send password reset email", logger.String("user_email", user.Email), logger.String("error", err.Error())) return err } s.Logger.Info("Password reset email sent", logger.String("user_email", user.Email)) return nil } ``` -------------------------------- ### Get Cache Statistics in Go Source: https://github.com/base-go/base-core/blob/main/CACHING.md Retrieves and prints current cache performance metrics including hits, misses, hit rate, size, and evictions. ```go stats := cache.GetStats() fmt.Printf("Provider: %s\n", stats.Provider) fmt.Printf("Hits: %d\n", stats.Hits) fmt.Printf("Misses: %d\n", stats.Misses) fmt.Printf("Hit Rate: %.2f%%\n", float64(stats.Hits) / float64(stats.Hits + stats.Misses) * 100) fmt.Printf("Size: %d entries\n", stats.Size) fmt.Printf("Evictions: %d\n", stats.Evictions) ``` -------------------------------- ### GET /api/cache/stats Source: https://github.com/base-go/base-core/blob/main/CACHING.md Retrieves current cache statistics. ```APIDOC ## GET /api/cache/stats ### Description Retrieves the current statistics for the cache system. ### Method GET ### Endpoint /api/cache/stats ``` -------------------------------- ### Basic Event Emitter Usage Source: https://github.com/base-go/base-core/blob/main/docs.md Demonstrates initializing event listeners for user creation and updates, and emitting events within service methods. ```go type UserService struct { DB *gorm.DB Emitter *emitter.Emitter Logger logger.Logger } // Initialize event listeners func (s *UserService) Init() { // User creation events s.Emitter.On("user.created", func(data any) { if user, ok := data.(*models.User); ok { s.Logger.Info("New user registered", logger.Int("id", int(user.Id)), logger.String("email", user.Email)) } }) // User update events s.Emitter.On("user.updated", func(data any) { if user, ok := data.(*models.User); ok { s.Logger.Info("User profile updated", logger.Int("id", int(user.Id))) } }) } // Emit events in methods func (s *UserService) Create(user *models.User) error { if err := s.DB.Create(user).Error; err != nil { s.Logger.Error("Failed to create user", logger.String("error", err.Error())) return err } s.Emitter.Emit("user.created", user) return nil } ``` -------------------------------- ### Initialize and Send Basic Email Source: https://github.com/base-go/base-core/blob/main/docs.md Initialize the email system with configuration and send a simple text-based email message. ```go // Initialize email system if err := email.Initialize(cfg); err != nil { log.Fatal("Failed to initialize email system:", err) } // Send a simple text email msg := email.Message{ To: []string{"user@example.com"}, Subject: "Welcome to Base", Body: "Thank you for joining us!", IsHTML: false, } if err := email.Send(msg); err != nil { log.Error("Failed to send email:", err) } ``` -------------------------------- ### HTTP Cache Statistics Response Source: https://github.com/base-go/base-core/blob/main/CACHING.md Example JSON response returned by the /api/cache/stats endpoint. ```json { "provider": "memory", "hits": 15234, "misses": 3421, "hit_rate": 81.67, "sets": 3421, "deletes": 245, "size": 3176, "evictions": 12, "last_cleanup": "2025-01-15T10:30:00Z" } ``` -------------------------------- ### email.Initialize Source: https://github.com/base-go/base-core/blob/main/docs.md Initializes the email system with the provided configuration. ```APIDOC ## email.Initialize(cfg) ### Description Initializes the email system using the configuration provided in the application settings. ### Parameters - **cfg** (Config) - Required - The configuration object containing provider settings. ``` -------------------------------- ### HTTP Cache Statistics Endpoint Source: https://github.com/base-go/base-core/blob/main/CACHING.md Retrieves cache statistics via a GET request to the /api/cache/stats endpoint. ```bash GET /api/cache/stats ``` -------------------------------- ### Register and Emit Events in PostService Source: https://github.com/base-go/base-core/blob/main/README.md Demonstrates how to register event listeners using the Emitter and trigger events after database operations within a service. ```go // In your service type PostService struct { DB *gorm.DB Emitter *emitter.Emitter Logger logger.Logger } // Register event listeners func (s *PostService) Init() { // Listen for post creation events s.Emitter.On("post.created", func(data any) { if post, ok := data.(*models.Post); ok { s.Logger.Info("Post created", logger.Int("id", int(post.Id)), logger.String("title", post.Title)) } }) } // Emit events in your methods func (s *PostService) Create(post *models.Post) error { if err := s.DB.Create(post).Error; err != nil { s.Logger.Error("Failed to create post", logger.String("error", err.Error())) return err } // Emit event after successful creation s.Emitter.Emit("post.created", post) return nil } ``` -------------------------------- ### GET /api/cache/stats Source: https://github.com/base-go/base-core/blob/main/CACHING.md Retrieves current cache performance statistics including hit rates, size, and eviction counts. ```APIDOC ## GET /api/cache/stats ### Description Retrieves current cache performance statistics including hit rates, size, and eviction counts. ### Method GET ### Endpoint /api/cache/stats ### Response #### Success Response (200) - **provider** (string) - The cache provider name - **hits** (integer) - Number of cache hits - **misses** (integer) - Number of cache misses - **hit_rate** (float) - Percentage of requests served from cache - **sets** (integer) - Number of set operations - **deletes** (integer) - Number of delete operations - **size** (integer) - Current number of cached items - **evictions** (integer) - Number of items removed due to memory limits - **last_cleanup** (string) - Timestamp of the last cleanup operation #### Response Example { "provider": "memory", "hits": 15234, "misses": 3421, "hit_rate": 81.67, "sets": 3421, "deletes": 245, "size": 3176, "evictions": 12, "last_cleanup": "2025-01-15T10:30:00Z" } ``` -------------------------------- ### Base CLI Commands Source: https://github.com/base-go/base-core/blob/main/README.md A reference of available CLI commands for project management, module generation, and framework maintenance. ```bash # Create a new project base new myapp # Start development server with hot reload base start # Generate modules base g post title:string content:text published:bool # Generate with relationships and attachments base g post \ title:string \ content:text \ featured_image:image \ gallery:attachment \ author:belongsTo:User \ comments:hasMany:Comment # Generate with automatic relationship detection base g article \ title:string \ content:text \ category_id:uint \ # Automatically creates Category relationship author_id:uint # Automatically creates Author relationship # Generate with specialized attachments base g document \ title:string \ file:file # Document attachment with validation author:belongsTo:User # Remove modules base d post # Update framework base update # Update framework dependencies base upgrade # Upgrade to latest version # Other commands base version # Show version information base feed # Show latest updates and news ``` -------------------------------- ### Project Directory Structure Source: https://github.com/base-go/base-core/blob/main/README.md Overview of the modular file system layout in a Base project. ```text . ├── app/ │ ├── models/ # All models in one place │ │ ├── post.go # Post model with GORM tags │ │ ├── user.go # User model │ │ └── comment.go # Comment model │ ├── posts/ # Post module │ │ ├── controller.go # HTTP handlers & file upload │ │ ├── service.go # Business logic & storage │ │ ├── module.go # Module registration │ │ └── validation.go # Validation rules │ ├── users/ # User module │ │ ├── controller.go │ │ ├── service.go │ │ ├── module.go │ │ └── validation.go # Validation rules │ └── init.go # Module initialization ├── core/ # Framework core │ ├── storage/ # File storage system │ ├── logger/ # Structured logging │ └── emitter/ # Event system ├── storage/ # File storage directory ├── .env # Environment config └── main.go # Entry point ``` -------------------------------- ### Enable WebSocket in .env Source: https://github.com/base-go/base-core/blob/main/static/README.md Configuration setting to ensure WebSocket functionality is enabled. ```bash # Check .env file WS_ENABLED=true ``` -------------------------------- ### System Monitor JavaScript Logic Source: https://github.com/base-go/base-core/blob/main/static/monitor.html Handles WebSocket connections, chart initialization using Chart.js, and real-time data updates for CPU, memory, and disk usage. ```javascript const statusEl = document.getElementById('status'); const connectBtn = document.getElementById('connect-btn'); const disconnectBtn = document.getElementById('disconnect-btn'); const cpuUsageEl = document.getElementById('cpu-usage'); const memoryUsageEl = document.getElementById('memory-usage'); const diskUsageEl = document.getElementById('disk-usage'); let socket; const maxDataPoints = 20; const initialData = Array(maxDataPoints).fill(0); const labels = Array(maxDataPoints).fill(''); // CPU Chart const cpuChart = new Chart(document.getElementById('cpuChart'), { type: 'line', data: { labels: labels, datasets: [{ label: 'CPU Usage %', data: [...initialData], borderColor: '#007bff', tension: 0.4, fill: false }] }, options: { responsive: true, scales: { y: { beginAtZero: true, max: 100 } } } }); // Memory Chart const memoryChart = new Chart(document.getElementById('memoryChart'), { type: 'line', data: { labels: labels, datasets: [{ label: 'Memory Usage %', data: [...initialData], borderColor: '#28a745', tension: 0.4, fill: false }] }, options: { responsive: true, scales: { y: { beginAtZero: true, max: 100 } } } }); function updateStatus(status) { statusEl.textContent = `Status: ${status}`; } function updateCharts(data) { // Update CPU chart cpuChart.data.datasets[0].data.push(data.cpu); cpuChart.data.datasets[0].data.shift(); cpuChart.update('none'); // Update Memory chart memoryChart.data.datasets[0].data.push(data.memory); memoryChart.data.datasets[0].data.shift(); memoryChart.update('none'); // Update metrics cpuUsageEl.textContent = `${data.cpu.toFixed(1)}%`; memoryUsageEl.textContent = `${data.memory.toFixed(1)}%`; diskUsageEl.textContent = `${data.disk.toFixed(1)}%`; } function connect() { const clientId = 'monitor_' + Math.random().toString(36).substr(2, 9); socket = new WebSocket(`ws://localhost:8100/api/ws?id=${clientId}&room=system_monitor`); socket.onopen = function() { updateStatus('Connected'); connectBtn.disabled = true; disconnectBtn.disabled = false; }; socket.onmessage = function(event) { const data = JSON.parse(event.data); if (data.type === 'system_metrics') { updateCharts(data.content); } }; socket.onclose = function() { updateStatus('Disconnected'); connectBtn.disabled = false; disconnectBtn.disabled = true; }; socket.onerror = function(error) { console.error('WebSocket Error:', error); updateStatus('Error occurred'); }; } function disconnect() { if (socket) { socket.close(); } } connectBtn.addEventListener('click', connect); disconnectBtn.addEventListener('click', disconnect); // Simulate system metrics for demo purposes function simulateMetrics() { if (socket && socket.readyState === WebSocket.OPEN) { const data = { type: 'system_metrics', content: { cpu: Math.random() * 100, memory: Math.random() * 100, disk: 50 + Math.random() * 20 } }; socket.send(JSON.stringify(data)); } } // Start simulation when connected setInterval(() => { if (socket && socket.readyState === WebSocket.OPEN) { simulateMetrics(); } }, 1000); ``` -------------------------------- ### Initialize Editor and UI Helpers Source: https://github.com/base-go/base-core/blob/main/static/editor.html Sets the initial code in the editor and provides helper functions to update the connection status and the list of active users. ```javascript function greet(name) { return `Hello, ${name}!`; } console.log(greet('World'));`; editor.setValue(initialCode); function updateStatus(status) { statusEl.textContent = `Status: ${status}`; } function updateUsersList(users) { usersListEl.innerHTML = ''; users.forEach(user => { const badge = document.createElement('span'); badge.className = 'user-badge'; badge.textContent = user; usersListEl.appendChild(badge); }); } ``` -------------------------------- ### Swagger UI Initialization Source: https://github.com/base-go/base-core/blob/main/docs/index.html Initializes the Swagger UI bundle with the API specification located at /docs/swagger.json. ```javascript window.onload = function() { const ui = SwaggerUIBundle({ url: '/docs/swagger.json', dom_id: '#swagger-ui', deepLinking: true, persistAuthorization: true, presets: [ SwaggerUIBundle.presets.apis, SwaggerUIStandalonePreset ], plugins: [ SwaggerUIBundle.plugins.DownloadUrl ], layout: "StandaloneLayout" }); }; ``` -------------------------------- ### Enable Caching via .env Source: https://github.com/base-go/base-core/blob/main/CACHING.md Default configuration for the caching system using the in-memory provider. ```env # .env CACHE_ENABLED=true CACHE_PROVIDER=memory CACHE_DEFAULT_TTL=15m ``` -------------------------------- ### Generate a new module with base g Source: https://github.com/base-go/base-core/blob/main/README.md Use the base CLI to scaffold a new module. This creates the directory structure including controller, service, module registration, and validator files. ```bash # Generate a new post module base g post title:string content:text # Creates: app/ ├── models/ │ └── post.go # Model with automatic relationships └── posts/ ├── controller.go # RESTful endpoints ├── service.go # Business logic ├── module.go # Registration └── validator.go # Input validation ``` -------------------------------- ### Registering Multiple Listeners Source: https://github.com/base-go/base-core/blob/main/docs.md Demonstrates attaching multiple independent listeners to the same event type, such as sending an email and logging simultaneously. ```go type NotificationService struct { Emitter *emitter.Emitter Logger logger.Logger Email email.Sender } func (s *NotificationService) Init() { // Email notification on post creation s.Emitter.On("post.created", func(data any) { if post, ok := data.(*models.Post); ok { msg := email.Message{ To: []string{post.Author.Email}, Subject: "Post Created", Body: "Your post has been published", IsHTML: false, } if err := s.Email.Send(msg); err != nil { s.Logger.Error("Failed to send email notification", logger.String("error", err.Error())) } } }) // Log post creation s.Emitter.On("post.created", func(data any) { if post, ok := data.(*models.Post); ok { s.Logger.Info("Post published", logger.Int("id", int(post.Id)), logger.String("title", post.Title), logger.Int("author_id", int(post.AuthorId))) } }) } ``` -------------------------------- ### File Upload Event Handling Source: https://github.com/base-go/base-core/blob/main/docs.md Shows how to handle file upload and deletion events within a PostService, including storage interaction and cleanup on database errors. ```go type PostService struct { DB *gorm.DB Emitter *emitter.Emitter Logger logger.Logger Storage storage.Storage } func (s *PostService) Init() { // File upload events s.Emitter.On("post.featured_image.uploaded", func(data any) { if post, ok := data.(*models.Post); ok { s.Logger.Info("Featured image uploaded", logger.Int("post_id", int(post.Id)), logger.String("filename", post.FeaturedImage)) } }) // File deletion events s.Emitter.On("post.featured_image.deleted", func(data any) { if post, ok := data.(*models.Post); ok { s.Logger.Info("Featured image deleted", logger.Int("post_id", int(post.Id))) } }) } func (s *PostService) UploadFeaturedImage(post *models.Post, file *multipart.FileHeader) error { filename, err := s.Storage.Store(file) if err != nil { return err } post.FeaturedImage = filename if err := s.DB.Save(post).Error; err != nil { s.Storage.Delete(filename) // cleanup on error return err } s.Emitter.Emit("post.featured_image.uploaded", post) return nil } ``` -------------------------------- ### Cache Key Helpers Source: https://github.com/base-go/base-core/blob/main/CACHING.md Generate consistent cache keys for users, roles, and HTTP requests. ```go import "base/core/cache" // User keys cache.UserKey(userID) // "user:123" cache.UserEmailKey(email) // "user:email:john@example.com" cache.UserPermissionsKey(userID) // "user:permissions:123" // Role keys cache.RolePermissionsKey(roleID) // "role:permissions:1" // HTTP keys cache.HTTPResponseKey("GET", "/api/users", "page=1") // "http:GET:/api/users?page=1" ``` -------------------------------- ### Monitoring Cache Performance Source: https://github.com/base-go/base-core/blob/main/CACHING.md Calculating and logging the cache hit rate to monitor performance. ```go stats := cache.GetStats() hitRate := float64(stats.Hits) / float64(stats.Hits + stats.Misses) * 100 if hitRate < 70 { log.Warn("Low cache hit rate", "rate", hitRate) } ``` -------------------------------- ### Handle Cache Errors Source: https://github.com/base-go/base-core/blob/main/CACHING.md Demonstrates how to check for specific cache errors such as cache misses or unavailability. ```go import "base/core/cache" err := cache.Get(ctx, key, &value) // Check if error is a cache miss if cache.IsMiss(err) { // Handle cache miss } // Check if cache is unavailable if errors.Is(err, cache.ErrCacheNotAvailable) { // Handle cache unavailability } ``` -------------------------------- ### Check Cache Existence Source: https://github.com/base-go/base-core/blob/main/CACHING.md Verify if a key exists in the cache. ```go exists, err := cache.Has(ctx, "user:123") ``` -------------------------------- ### Event System Panic Recovery Source: https://github.com/base-go/base-core/blob/main/docs.md Illustrates the emitter's built-in panic recovery, ensuring that subsequent listeners continue to execute even if a previous listener panics. ```go func (s *PostService) Init() { s.Emitter.On("post.created", func(data any) { // Even if this panics, other listeners will still execute panic("something went wrong") }) s.Emitter.On("post.created", func(data any) { // This will still run if post, ok := data.(*models.Post); ok { s.Logger.Info("Post created", logger.Int("id", int(post.Id))) } }) } ``` -------------------------------- ### Development Configuration (In-Memory) Source: https://github.com/base-go/base-core/blob/main/CACHING.md Configuration for local development using the in-memory cache provider. ```env CACHE_ENABLED=true CACHE_PROVIDER=memory CACHE_DEFAULT_TTL=15m CACHE_MEMORY_MAX_SIZE=10000 ``` -------------------------------- ### Production Configuration (Redis) Source: https://github.com/base-go/base-core/blob/main/CACHING.md Configuration for production environments using Redis with fallback enabled. ```env CACHE_ENABLED=true CACHE_PROVIDER=redis CACHE_DEFAULT_TTL=15m CACHE_FALLBACK_ENABLED=true CACHE_REDIS_HOST=redis.example.com CACHE_REDIS_PORT=6379 CACHE_REDIS_PASSWORD=your_secure_password CACHE_REDIS_DB=0 CACHE_REDIS_PREFIX=myapp: ``` -------------------------------- ### Initialize CodeMirror Editor and DOM Elements Source: https://github.com/base-go/base-core/blob/main/static/editor.html Initializes the CodeMirror editor instance with specific themes and settings, and selects necessary DOM elements for editor controls. ```javascript const statusEl = document.getElementById('status'); const connectBtn = document.getElementById('connect-btn'); const disconnectBtn = document.getElementById('disconnect-btn'); const nicknameInput = document.getElementById('nickname-input'); const runBtn = document.getElementById('run-btn'); const shareBtn = document.getElementById('share-btn'); const usersListEl = document.getElementById('users-list'); const languageSelect = document.getElementById('language-select'); let socket; let editor; let isUpdating = false; let cursors = new Map(); let cursorWidgets = new Map(); let lastCursorUpdate = 0; const CURSOR_THROTTLE = 50; // ms // Initialize CodeMirror editor = CodeMirror.fromTextArea(document.getElementById('editor'), { mode: 'javascript', theme: 'monokai', lineNumbers: true, autoCloseBrackets: true, matchBrackets: true, indentUnit: 4, tabSize: 4, indentWithTabs: true, lineWrapping: true }); // Sample initial code const initialCode = `// Welcome to the collaborative code editor! // Start typing and your changes will be synced with other users. ``` -------------------------------- ### Graceful Cache Failure Handling Source: https://github.com/base-go/base-core/blob/main/CACHING.md Pattern for falling back to the database when a cache retrieval fails. ```go var user User err := cache.Get(ctx, key, &user) if err != nil { // Always fall back to DB on cache error if err := db.First(&user, id).Error; err != nil { return nil, err } // Attempt to cache (non-blocking) cache.Set(ctx, key, user, ttl) } ``` -------------------------------- ### Clear Cache Source: https://github.com/base-go/base-core/blob/main/CACHING.md Remove all entries from the cache. ```go // Clear all cache entries cache.Clear(ctx) ``` -------------------------------- ### CacheMiddlewareConfig Structure Source: https://github.com/base-go/base-core/blob/main/CACHING.md Defines the configuration fields available for the CacheMiddleware. ```go type CacheMiddlewareConfig struct { TTL time.Duration // How long to cache CacheableStatuses []int // Which statuses to cache (e.g., [200]) CacheableMethods []string // Which methods to cache (e.g., ["GET"]) SkipPaths []string // Paths to skip caching VaryByQueryParams bool // Include query params in cache key VaryByHeaders []string // Vary by specific headers } ``` -------------------------------- ### Default Cache Middleware Configuration Source: https://github.com/base-go/base-core/blob/main/CACHING.md Retrieves the default configuration settings for the cache middleware. ```go config := middleware.DefaultCacheMiddlewareConfig() // TTL: 5 minutes // Cacheable Statuses: [200] // Cacheable Methods: ["GET"] // Vary By Query Params: true ``` -------------------------------- ### Before: Direct Database Access Source: https://github.com/base-go/base-core/blob/main/CACHING.md The original implementation of GetUser that fetches data directly from the database without caching. ```go func (s *UserService) GetUser(id uint) (*User, error) { var user User if err := s.DB.First(&user, id).Error; err != nil { return nil, err } return &user, nil } ``` -------------------------------- ### Module interaction via service injection Source: https://github.com/base-go/base-core/blob/main/README.md Modules can communicate by injecting other services or using event emitters within their service layer. ```go // Post service using user service type PostService struct { userService *user.Service // Direct service injection emitter *emitter.Emitter // Event-based communication } ``` -------------------------------- ### Configure Memory Cache Source: https://github.com/base-go/base-core/blob/main/CACHING.md Environment variables for the default memory cache provider. ```env CACHE_PROVIDER=memory CACHE_MEMORY_MAX_SIZE=10000 CACHE_MEMORY_CLEANUP_INTERVAL=5m ``` -------------------------------- ### Integrate Email in UserService Source: https://github.com/base-go/base-core/blob/main/docs.md Inject the email sender into a service struct to send emails within application logic. ```go type UserService struct { DB *gorm.DB Email email.Sender Logger logger.Logger } func (s *UserService) SendWelcomeEmail(user *models.User) error { msg := email.Message{ To: []string{user.Email}, Subject: "Welcome to " + config.AppName, Body: fmt.Sprintf("Welcome %s! Thank you for joining us.", user.Name), IsHTML: false, } if err := s.Email.Send(msg); err != nil { s.Logger.Error("Failed to send welcome email", logger.String("user_email", user.Email), logger.String("error", err.Error())) return err } s.Logger.Info("Welcome email sent", logger.String("user_email", user.Email)) return nil } ``` -------------------------------- ### Configure Email Provider in .env Source: https://github.com/base-go/base-core/blob/main/docs.md Set the required environment variables to configure the email provider and its specific settings. ```env # Common Settings EMAIL_PROVIDER=smtp # smtp, sendgrid, postmark EMAIL_FROM_ADDRESS=noreply@example.com # SMTP Settings SMTP_HOST=smtp.mailtrap.io SMTP_PORT=2525 SMTP_USERNAME=your_username SMTP_PASSWORD=your_password # SendGrid Settings SENDGRID_API_KEY=your_sendgrid_api_key # Postmark Settings POSTMARK_SERVER_TOKEN=your_server_token POSTMARK_ACCOUNT_TOKEN=your_account_token ``` -------------------------------- ### Inject Cache into Service Source: https://github.com/base-go/base-core/blob/main/CACHING.md Inject the cache interface into a service using the module dependencies. ```go import "base/core/cache" type MyService struct { DB *gorm.DB Cache cache.Cache } func NewMyService(deps module.Dependencies) *MyService { return &MyService{ DB: deps.DB, Cache: deps.Cache, } } ``` -------------------------------- ### Module Generation Output Source: https://github.com/base-go/base-core/blob/main/README.md The file structure created after running the module generation command. ```bash # Generate a post module base g post title:string content:text # Creates: app/ ├── models/ │ └── post.go # Post model with GORM tags └── posts/ # Post module ├── controller.go # HTTP handlers & validation ├── service.go # Business logic ├── module.go # Module registration └── validation.go # Validation rules ``` -------------------------------- ### CSS Box Sizing and Body Styles Source: https://github.com/base-go/base-core/blob/main/docs/index.html Global CSS rules to ensure consistent box-sizing and a light gray background for the documentation page. ```css html { box-sizing: border-box; overflow: -moz-scrollbars-vertical; overflow-y: scroll; } *, *:before, *:after { box-sizing: inherit; } body { margin:0; background: #fafafa; } ``` -------------------------------- ### WebSocket Chat Client Logic Source: https://github.com/base-go/base-core/blob/main/static/chat.html This script initializes DOM elements, manages WebSocket lifecycle events, handles room switching, and processes incoming/outgoing chat messages. ```javascript const statusEl = document.getElementById('status'); const chatBoxEl = document.getElementById('chat-box'); const messageFormEl = document.getElementById('message-form'); const messageInputEl = document.getElementById('message-input'); const connectBtnEl = document.getElementById('connect-btn'); const disconnectBtnEl = document.getElementById('disconnect-btn'); const sendBtnEl = document.getElementById('send-btn'); const roomListEl = document.getElementById('room-list'); const newRoomInputEl = document.getElementById('new-room-input'); const createRoomBtnEl = document.getElementById('create-room-btn'); const nicknameInputEl = document.getElementById('nickname-input'); let socket; let currentRoom = 'general'; function updateStatus(status) { statusEl.textContent = `Status: ${status}`; } function appendMessage(message, nickname) { const messageEl = document.createElement('div'); messageEl.className = 'message'; const nicknameSpan = document.createElement('span'); nicknameSpan.className = 'nickname'; nicknameSpan.textContent = nickname + ': '; const contentSpan = document.createElement('span'); contentSpan.textContent = message; messageEl.appendChild(nicknameSpan); messageEl.appendChild(contentSpan); chatBoxEl.appendChild(messageEl); chatBoxEl.scrollTop = chatBoxEl.scrollHeight; } function updateRoomUI() { document.querySelectorAll('.room-item').forEach(item => { item.classList.toggle('active', item.dataset.room === currentRoom); }); chatBoxEl.innerHTML = ''; appendMessage(`Joined room: ${currentRoom}`); } function addRoom(roomName) { const roomEl = document.createElement('div'); roomEl.className = 'room-item'; roomEl.dataset.room = roomName.toLowerCase(); roomEl.textContent = roomName; roomListEl.appendChild(roomEl); } function connect() { const clientId = 'user_' + Math.random().toString(36).substr(2, 9); const nickname = nicknameInputEl.value.trim() || 'Guest'; socket = new WebSocket(`ws://localhost:8100/api/ws?id=${clientId}&room=${currentRoom}&nickname=${encodeURIComponent(nickname)}`); socket.onopen = function (e) { updateStatus('Connected'); messageInputEl.disabled = false; sendBtnEl.disabled = false; connectBtnEl.disabled = true; disconnectBtnEl.disabled = false; updateRoomUI(); appendMessage('You joined the chat', nicknameInputEl.value.trim() || 'Guest'); }; socket.onmessage = function (event) { const message = JSON.parse(event.data); if (message.room === currentRoom) { appendMessage(message.content, message.nickname || 'Anonymous'); } }; socket.onclose = function (event) { if (event.wasClean) { updateStatus('Disconnected'); } else { updateStatus('Connection lost'); } messageInputEl.disabled = true; sendBtnEl.disabled = true; connectBtnEl.disabled = false; disconnectBtnEl.disabled = true; appendMessage('Disconnected from the chat server.'); }; socket.onerror = function (error) { console.error('WebSocket Error:', error); updateStatus('Error occurred'); }; } function disconnect() { if (socket) { socket.close(); } } function sendMessage(message) { if (socket && socket.readyState === WebSocket.OPEN) { const data = { type: 'message', content: message, room: currentRoom, nickname: nicknameInputEl.value.trim() || 'Guest' }; socket.send(JSON.stringify(data)); } } function switchRoom(roomName) { if (socket && socket.readyState === WebSocket.OPEN) { disconnect(); } currentRoom = roomName; if (!socket || socket.readyState !== WebSocket.OPEN) { connect(); } } roomListEl.addEventListener('click', function(e) { const roomItem = e.target.closest('.room-item'); if (roomItem) { switchRoom(roomItem.dataset.room); } }); createRoomBtnEl.addEventListener('click', function() { const roomName = newRoomInputEl.value.trim(); if (roomName) { addRoom(roomName); newRoomInputEl.value = ''; switchRoom(roomName.toLowerCase()); } }); connectBtnEl.addEventListener('click', connect); disconnectBtnEl.addEventListener('click', disconnect); messageFormEl.addEventListener('submit', function (e) { e.preventDefault(); const message = messageInputEl.value.trim(); if (message) { sendMessage(message); messageInputEl.value = ''; } }); ``` -------------------------------- ### Configure Redis Cache Source: https://github.com/base-go/base-core/blob/main/CACHING.md Environment variables for the distributed Redis cache provider. ```env CACHE_PROVIDER=redis CACHE_REDIS_HOST=localhost CACHE_REDIS_PORT=6379 CACHE_REDIS_PASSWORD= CACHE_REDIS_DB=0 ``` -------------------------------- ### cache.Get Source: https://github.com/base-go/base-core/blob/main/CACHING.md Retrieves a value from the cache by key. ```APIDOC ## cache.Get(ctx, key, value) ### Description Retrieves an item from the cache and unmarshals it into the provided value pointer. ### Parameters - **ctx** (context.Context) - The request context. - **key** (string) - The cache key to retrieve. - **value** (interface{}) - A pointer to the variable where the cached data will be stored. ### Usage ```go var user User err := cache.Get(ctx, "user:123", &user) if cache.IsMiss(err) { // Cache miss - fetch from DB } ``` -------------------------------- ### Send HTML Email Source: https://github.com/base-go/base-core/blob/main/docs.md Send an email with HTML content by setting the IsHTML flag to true. ```go // Send an HTML email msg := email.Message{ To: []string{"user@example.com"}, Subject: "Welcome to Base", Body: `Thank you for joining us. Here's what you can do next: