### Start Base Framework Server Source: https://github.com/basetechstack/base/blob/main/static/README.md Command to start the Base Framework server, which is necessary to run the WebSocket examples. ```bash base start ``` -------------------------------- ### Create and Start a New Project Source: https://github.com/basetechstack/base/blob/main/README.md Commands to create a new project, navigate into it, and start the development server with hot-reloading enabled. ```bash # Create a new project base new myapp cd myapp # Start the development server with hot reload base start ``` -------------------------------- ### Base CLI: Start Development Server Source: https://github.com/basetechstack/base/blob/main/README.md Command to start the development server with hot reload functionality. ```Bash base start ``` -------------------------------- ### WebSocket Connection Example Source: https://github.com/basetechstack/base/blob/main/static/README.md JavaScript code snippet demonstrating how to establish a WebSocket connection to the Base Framework server, including necessary query parameters. ```javascript const socket = new WebSocket('ws://localhost:8100/api/ws?id=user123&nickname=John&room=general'); ``` -------------------------------- ### Base CLI Installation Source: https://github.com/basetechstack/base/blob/main/README.md Command to install the Base CLI tool using curl and bash. This tool is used for project generation and management. ```Bash curl -sSL https://raw.githubusercontent.com/base-go/cmd/main/install.sh | bash ``` -------------------------------- ### Code Editor Example Source: https://github.com/basetechstack/base/blob/main/static/index.html A real-time collaborative code editor offering syntax highlighting for multiple languages, real-time collaboration features, cursor tracking, and code execution capabilities. ```HTML Code Editor

Code Editor

Collaborative code editing with syntax highlighting.

Code Editor

Edit code together in real-time.

Try Editor Source
``` -------------------------------- ### System Monitor Example Source: https://github.com/basetechstack/base/blob/main/static/index.html A system monitor that visualizes system metrics in real-time using charts and live updates. It tracks CPU/memory usage, displays historical data, and provides interactive charts. ```HTML System Monitor

System Monitor

Real-time system metrics visualization.

System Monitor

Monitor your system's performance live.

Try Monitor Source
``` -------------------------------- ### Go Event Handling Example Source: https://github.com/basetechstack/base/blob/main/README.md Demonstrates how to use the Base framework's event emitter to listen for and emit events. It shows registering a listener for 'post.created' and emitting the event after a post is successfully created. ```Go package main import ( "github.com/base-go/cmd/emitter" "github.com/base-go/cmd/logger" "gorm.io/gorm" ) // Assuming models.Post and logger.Logger are defined elsewhere // type Post struct { ... } // type Logger interface { ... } // 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 } ``` -------------------------------- ### Go Service Implementation with Event Emission Source: https://github.com/basetechstack/base/blob/main/README.md Example of a Go service implementation for creating a post, demonstrating database interaction and emitting a 'post.created' event. ```go // app/posts/service.go package posts import "base/app/models" // Clean import, no circular dependency types 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 } ``` -------------------------------- ### Kanban Board Example Source: https://github.com/basetechstack/base/blob/main/static/index.html A real-time collaborative Kanban board designed for team task management. It supports drag-and-drop tasks, real-time updates, task assignment, multiple columns, and user tracking. ```HTML Kanban Board

Kanban Board

Collaborative task management for teams.

Kanban Board

Manage your team's tasks efficiently.

Try Kanban Source
``` -------------------------------- ### Chat Room Example Source: https://github.com/basetechstack/base/blob/main/static/index.html A real-time chat application featuring multiple rooms, user nicknames, room switching, and join/leave notifications. It demonstrates real-time message delivery. ```HTML Chat Room

Chat Room

Real-time chat with multiple rooms and user nicknames.

Chat Room

Connect and chat with others in real-time.

Try Chat Source
``` -------------------------------- ### Enable WebSocket in .env Source: https://github.com/basetechstack/base/blob/main/static/README.md Configuration setting in the .env file to ensure WebSocket functionality is enabled in the Base Framework. ```bash # Check .env file WS_ENABLED=true ``` -------------------------------- ### Spreadsheet Example Source: https://github.com/basetechstack/base/blob/main/static/index.html A real-time collaborative spreadsheet application with formula support. Key features include cell editing, a formula bar, cursor tracking, CSV export, and dynamic resizing. ```HTML Spreadsheet

Spreadsheet

Collaborative spreadsheet with formula support.

Spreadsheet

Work on spreadsheets together in real-time.

Try Spreadsheet Source
``` -------------------------------- ### Drawing Board Example Source: https://github.com/basetechstack/base/blob/main/static/index.html A collaborative drawing board allowing multiple users to draw together in real-time. Features include real-time drawing synchronization, multiple colors, adjustable brush size, cursor tracking, and canvas clearing. ```HTML Drawing Board

Drawing Board

Collaborative drawing in real-time.

Drawing Board

Draw together with friends in real-time.

Try Drawing Source
``` -------------------------------- ### Go Module Communication Example Source: https://github.com/basetechstack/base/blob/main/README.md Illustrates how modules can communicate using direct service calls and an event emitter within a Go service structure. ```go // Post service using user service type PostService struct { userService *user.Service // Direct service injection emitter *emitter.Emitter // Event-based communication } ``` -------------------------------- ### Go Model Definition with GORM Tags Source: https://github.com/basetechstack/base/blob/main/README.md Example of a Go model definition for a Post, including GORM tags for database mapping and foreign key relationships to User and Comment models. ```go // app/models/post.go package models 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 ``` -------------------------------- ### Send Password Reset Email Source: https://github.com/basetechstack/base/blob/main/docs.md Provides an example of sending a password reset email to a user. The email contains a unique reset link and instructions. It includes error handling and logging for the email sending process. ```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(`

Password Reset Request

Hello %s,

We received a request to reset your password. Click the link below to proceed:

Reset Password

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 } ``` -------------------------------- ### Post Service Event Error Handling Source: https://github.com/basetechstack/base/blob/main/docs.md Shows the Base framework's event emitter's built-in panic recovery. This example demonstrates that even if one listener panics during an event, other listeners for the same event will still execute. This ensures robustness in event handling. ```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))) } }) } ``` -------------------------------- ### HMVC Post Module - Model Definition Source: https://github.com/basetechstack/base/blob/main/README.md Defines the 'Post' model for the HMVC example, including fields like title, content, published status, author, tags, and comments, with GORM and JSON tags. ```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" } ``` -------------------------------- ### Notification Service Multiple Event Listeners Source: https://github.com/basetechstack/base/blob/main/docs.md Demonstrates how to attach multiple listeners to the same event in the Base framework's NotificationService. This example shows sending an email notification and logging a post creation event when the 'post.created' event is emitted. Dependencies include emitter, logger, and email sender. ```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))) } }) } ``` -------------------------------- ### Handling Task Drag Start in JavaScript Source: https://github.com/basetechstack/base/blob/main/static/kanban.html This function is an event listener for the `dragstart` event on a task element. It stores a reference to the dragged task in `draggedTask` and applies a 'dragging' CSS class to the element, providing visual indication that it's being dragged. ```JavaScript function handleDragStart(e) { draggedTask = e.target; e.target.classList.add('dragging'); } ``` -------------------------------- ### Base CLI: Create New Project Source: https://github.com/basetechstack/base/blob/main/README.md Command to create a new project using the Base CLI. ```Bash base new myapp ``` -------------------------------- ### Base Project Structure Overview Source: https://github.com/basetechstack/base/blob/main/README.md Illustrates the typical directory structure of a Base project, highlighting the modular architecture and placement of models, modules, and core components. ```bash . ├── 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 ``` -------------------------------- ### Initialize and Send Basic Email Source: https://github.com/basetechstack/base/blob/main/docs.md Demonstrates the initialization of the email system with a given configuration and sending a simple plain text email. It includes error handling for the initialization and sending processes. ```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) } ``` -------------------------------- ### HMVC Post Module - Module Initialization Source: https://github.com/basetechstack/base/blob/main/README.md Initializes the 'PostModule', setting up the 'PostService' and 'PostController' with necessary dependencies like the database, router, logger, and emitter. ```go // 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, } } ``` -------------------------------- ### Start Cell Editing Source: https://github.com/basetechstack/base/blob/main/static/spreadsheet.html This function handles the start of cell editing. It sets the focus to the input field within the cell, updates the formula input, and sends a cursor update via WebSocket. It also listens for input changes to update the cell content and send cell updates. ```javascript function startEditing(cell) { if (currentCell) { currentCell.classList.remove('editing'); } currentCell = cell; cell.classList.add('editing'); const input = cell.querySelector('.cell-input'); const content = cell.querySelector('.cell-content'); input.value = content.textContent; input.focus(); selectedCellEl.textContent = getColumnLabel(parseInt(cell.dataset.col)) + (parseInt(cell.dataset.row) + 1); formulaInput.value = content.textContent; sendCursorUpdate(cell); // Listen for input changes input.oninput = () => { content.textContent = input.value; sendCellUpdate(cell, input.value); formulaInput.value = input.value; }; } ``` -------------------------------- ### Service Integration for Sending Welcome Email Source: https://github.com/basetechstack/base/blob/main/docs.md Illustrates how to integrate email sending into a service, specifically for sending a welcome email to a new user. It utilizes a UserService struct that has an email.Sender dependency and logs the outcome. ```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 } ``` -------------------------------- ### Base Framework Commands Source: https://github.com/basetechstack/base/blob/main/README.md Core commands for managing the Base framework, including updating, upgrading, and checking the version. ```bash base update # Update framework dependencies base upgrade # Upgrade to latest version base version # Show version information base feed # Show latest updates and news ``` -------------------------------- ### Get Column Label Source: https://github.com/basetechstack/base/blob/main/static/spreadsheet.html This function converts a column index to its corresponding label (e.g., 0 -> A, 1 -> B, 26 -> AA). ```javascript function getColumnLabel(index) { let label = ''; while (index >= 0) { label = String.fromCharCode(65 + (index % 26)) + label; index = Math.floor(index / 26) - 1; } return label; } ``` -------------------------------- ### User Service Event Handling Source: https://github.com/basetechstack/base/blob/main/docs.md Demonstrates how to use the Base framework's event system within a UserService. It shows how to register listeners for user creation and update events and emit these events from service methods. Dependencies include gorm for database operations, emitter for event handling, and logger for logging. ```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 } ``` -------------------------------- ### HMVC Post Module - Service Implementation Source: https://github.com/basetechstack/base/blob/main/README.md Provides the 'PostService' implementation, handling post creation and emitting a 'post.created' event upon successful creation. ```go // 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 } ``` -------------------------------- ### Base Framework Configuration (.env) Source: https://github.com/basetechstack/base/blob/main/README.md Environment variables used for configuring the Base framework, including server address, JWT secrets, API keys, database settings, storage, and email. ```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 ``` -------------------------------- ### Generate a New Module Source: https://github.com/basetechstack/base/blob/main/README.md Command to generate a new module, including its model, controller, service, and validation files, with specified fields for the model. ```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 ``` -------------------------------- ### Generate Module with Multiple Relationships Source: https://github.com/basetechstack/base/blob/main/README.md Command to generate a new module (e.g., 'article') with fields that automatically establish relationships based on `_id` suffixes. ```bash # This command: base g article title:string content:text category_id:uint author_id:uint ``` -------------------------------- ### Base CLI: Generate Module Source: https://github.com/basetechstack/base/blob/main/README.md Command to generate a new module with specified fields and types. ```Bash base g post title:string content:text published:bool ``` -------------------------------- ### Post Service File Upload Events Source: https://github.com/basetechstack/base/blob/main/docs.md Illustrates file upload and deletion event handling in the Base framework's PostService. It shows how to register listeners for featured image uploads and deletions, and emit these events after storage operations. Dependencies include gorm, emitter, logger, and storage. ```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 } ``` -------------------------------- ### Base CLI: Generate Module with Relationships and Attachments Source: https://github.com/basetechstack/base/blob/main/README.md Command to generate a module including relationships (belongsTo, hasMany) and attachments (image, attachment). ```Bash base g post \ title:string \ content:text \ featured_image:image \ gallery:attachment \ author:belongsTo:User \ comments:hasMany:Comment ``` -------------------------------- ### HMVC Post Module - Controller Implementation Source: https://github.com/basetechstack/base/blob/main/README.md Implements the 'PostController' for the HMVC pattern, defining routes for listing, retrieving, creating, updating, and deleting posts. ```go // 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) } ``` -------------------------------- ### Base CLI: Generate Module with Specialized Attachments Source: https://github.com/basetechstack/base/blob/main/README.md Command to generate a module with specialized file attachments, like 'document'. ```Bash base g document \ title:string \ file:file \ author:belongsTo:User ``` -------------------------------- ### Configure Email Provider Source: https://github.com/basetechstack/base/blob/main/docs.md Configuration settings for various email providers (SMTP, SendGrid, Postmark) are managed in the .env file. This includes common settings like the provider and sender address, as well as provider-specific credentials. ```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 ``` -------------------------------- ### Base CLI: Generate Module with Automatic Relationship Detection Source: https://github.com/basetechstack/base/blob/main/README.md Command to generate a module where relationships are automatically detected based on fields ending with '_id'. ```Bash base g article \ title:string \ content:text \ category_id:uint \ author_id:uint ``` -------------------------------- ### Go Struct for Article with GORM Tags Source: https://github.com/basetechstack/base/blob/main/README.md Defines the 'Article' struct with GORM tags for database mapping, including primary key, relationships, and JSON serialization. ```go type Article struct { Id uint `json:"id" gorm:"primarykey" Title string `json:"title" Content string `json:"content" CategoryId uint `json:"category_id" Category Category `json:"category,omitempty" gorm:"foreignKey:CategoryId" AuthorId uint `json:"author_id" Author Author `json:"author,omitempty" gorm:"foreignKey:AuthorId" } ```