From ef298cb112b3e048ab7a6d66d6db2b82b9fecb28 Mon Sep 17 00:00:00 2001 From: hokamsingh Date: Sat, 31 Aug 2024 23:54:01 +0530 Subject: [PATCH 1/6] feat: fixes --- pkg/lessgo/less.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pkg/lessgo/less.go b/pkg/lessgo/less.go index 5ac6f4d..5797b53 100644 --- a/pkg/lessgo/less.go +++ b/pkg/lessgo/less.go @@ -76,7 +76,7 @@ Here's an example of how to use the LessGo framework in a basic web server setup } } -For more detailed documentation and examples, please visit the [official LessGo documentation](https://yourdocumentationurl.com). +For more detailed documentation and examples, please visit the [official LessGo documentation](https://github.com/hokamsingh). # Package Structure From aa1e67919cb3c72ec396901ea2d6c1cadd91c0a6 Mon Sep 17 00:00:00 2001 From: Hokam Singh Sisodiya <148938898+hokamsingh@users.noreply.github.com> Date: Sun, 1 Sep 2024 15:13:03 +0530 Subject: [PATCH 2/6] Update README.md --- README.md | 91 +++++++++++++++++++++---------------------------------- 1 file changed, 34 insertions(+), 57 deletions(-) diff --git a/README.md b/README.md index 70746e4..0512d92 100644 --- a/README.md +++ b/README.md @@ -5,72 +5,51 @@ ![Version](https://img.shields.io/badge/version-v1.0.2-blue) [![Go Report Card](https://goreportcard.com/badge/github.com/hokamsingh/lessgo)](https://goreportcard.com/report/github.com/hokamsingh/lessgo) -## ๐Ÿ› ๏ธ LessGo Framework Release +**๐Ÿš€ LessGo v1.0.2 - The High-Performance Minimal Go Web Framework** -We are excited to announce the latest release of the **LessGo** framework! This release introduces several powerful features and enhancements to make your Go development experience even more robust and efficient. +Welcome to **LessGo** โšกโ€”a high-performance, minimal Go web framework crafted for building scalable, maintainable, and modern applications. LessGo empowers developers with advanced features like dynamic configuration management, inbuilt error handling, robust data validation, and Dependency Injection (DI). -### ๐Ÿš€ New Features +Inspired by the modular architecture of frameworks like NestJs, LessGo offers a flexible structure that allows you to build your applications your way. Whether you prefer a strict controller-service-module architecture or a more fluid design, LessGo has you covered. With built-in support for CORS, CSRF, XSS protection, logging, error handling, rate limiting, caching, and job scheduling, LessGo makes it easier to develop secure, efficient, and performant web applications. -- **Enhanced Dependency Injection (DI)**: - - **Conditional Bindings**: Register dependencies based on specific conditions. - - **Scoped Services**: Manage services with different lifetimes and scopes. - - **Named Dependencies**: Support for naming dependencies for more granular control. +### โœจ Key Features: -- **Dynamic Configuration Management**: - - **Factory Pattern**: Implement dynamic configuration management with factories to handle various application environments and requirements. +1. **๐Ÿ”„ Concurrency & Task Management** + LessGo includes a powerful task manager that allows you to run tasks in parallel or sequence, giving you full control over task management and program flow. We are committed to enhancing its robustness and extensibility. -- **Inbuilt Error Handling**: - - **Custom Error Responses**: Integrate a flexible error handling system that returns appropriate HTTP responses based on the error type. - - **Detailed Logging**: Capture detailed error logs and stack traces for better debugging. +2. **โš™๏ธ Dynamic Configuration Management** + With built-in support for multiple environments (development, production, testing), LessGo simplifies configuration management. It provides a user-friendly API for working with environment variables, offering validation and easy access to typed values like numbers and booleans. -- **Job Scheduler Integration**: - - **Built-in Scheduler**: Utilize an advanced job scheduling library for managing periodic tasks and background jobs seamlessly. +3. **๐Ÿ”ง LessGo Context** + The LessGo Context is a powerful abstraction over the request and response objects. It simplifies API development by providing methods for handling headers, cookies, query parameters, JSON parsing, and more. Error management, HTTP redirection, and file attachments are made effortless. -- **JSON Response Handling**: - - **Automatic JSON Parsing**: Simplify the process of parsing and responding with JSON data. - - **Custom JSON Encoding**: Encode and decode JSON responses with integrated error handling. +4. **๐Ÿงฉ Flexible Dependency Injection (DI)** + LessGo offers basic DI functionality that we're continuously improving. You can choose whether to bind your entire application into a single container or work with a more traditional approach, giving you flexibility in how you manage dependencies. -- **Advanced Data Validation**: - - **Strict Validation**: Ensure data integrity by validating incoming requests against predefined models. - - **Dynamic Key Checks**: Verify that all required fields are present in the request payload. +5. **๐Ÿš€ App Initialization** + The App is the core of LessGo, initializing various configurations and middleware. It exposes the main server with a simple `Listen` method to start your application. -- **๐Ÿ›ก๏ธ CSRF Protection Middleware**: - - **`LessGo.WithCsrf()`**: Integrated Cross-Site Request Forgery (CSRF) protection to safeguard your applications against unauthorized actions. +6. **โฐ Job Scheduling** + LessGo supports job scheduling, leveraging the powerful Cron package to handle recurring tasks seamlessly. -- **๐Ÿ”’ XSS Protection Middleware**: - - **`LessGo.WithXss()`**: Built-in Cross-Site Scripting (XSS) protection to prevent malicious script injections. +7. **๐Ÿ”’ Comprehensive Middleware** + LessGo comes with essential built-in middleware, including CORS, JSON parser, cookie parser, CSRF and XSS protection, caching, file uploads, and rate limiting (both in-memory and Redis-backed). -- **โšก Caching Middleware**: - - **`LessGo.WithCaching("localhost:6379", 5*time.Minute)`**: Redis-based caching middleware for improved performance with configurable cache expiration -- **Response Handling** - - Enhanced response handling to ensure multiple responses are not sent from the same context, preventing unexpected behaviors and potential crashes. - -- **Template Rendering** - - Introduced support for rendering templates dynamically from a specified directory, reducing the need to manually list each template file. +8. **๐ŸŒ Powerful Router** + The built-in router handles different HTTP methods with custom handlers, supporting method chaining, sub-routers, and custom middleware. -- **Middleware Improvements** - - Refined existing middleware to ensure seamless integration and performance. - - Addressed potential edge cases and improved overall robustness. +9. **๐Ÿ“ฆ Controller Interface** + Controllers in LessGo allow you to create dedicated routers for specific endpoints, integrating seamlessly with the service layer for efficient request handling. -## โš™๏ธ Migration Notes +10. **๐Ÿ” Service Layer** + The Service interface in LessGo is designed for encapsulating business logic. It easily binds to databases and other dependencies, streamlining the development process. -- The new security middlewares (`WithCsrf` and `WithXss`) are optional but highly recommended for applications that handle sensitive data. -- The caching middleware requires a running Redis instance. Ensure your Redis server is properly configured and accessible from your application. +11. **๐Ÿ”— Modular Design** + Modules in LessGo bring together controllers and services, managing routes and handlers in a cohesive manner. -## ๐Ÿ›ก๏ธ Security +12. **๐Ÿ’ฌ WebSocket Support (Upcoming)** + We are actively working on integrating WebSocket support to make real-time communication in your applications even easier. -- Security is a top priority for us, and this release emphasizes that with the introduction of CSRF and XSS protection middlewares. We strongly recommend enabling these features to safeguard your applications against common web vulnerabilities. - - -### ๐Ÿ“š Documentation & Examples - -- **Enhanced Documentation**: Comprehensive guides and examples to help you get started with the new features and integrations. -- **Code Examples**: Practical examples demonstrating how to use the new features in real-world applications. - -### ๐Ÿ› ๏ธ Improvements & Fixes - -- **Performance Enhancements**: Optimizations for better performance and reduced resource usage. -- **Bug Fixes**: Various bug fixes and stability improvements to ensure a smoother development experience. +--- ### ๐Ÿ“ฆ Installation & Upgrade @@ -100,14 +79,12 @@ Make sure to try out the CLI to streamline your project setup and start building We would like to thank our contributors and community for their support and feedback. Your contributions have been invaluable in shaping the LessGo framework. -## License - -This project is licensed under the MIT License - see the [LICENSE](./LICENSE) file for details. +### ๐Ÿ“œ License ---- +This project is licensed under the MIT License - see the LICENSE file for details. -For any questions, issues, or feedback, please visit our [GitHub repository](https://github.com/hokamsingh/lessgo) or join our [community discussions](#). +For any questions, issues, or feedback, please visit our [GitHub repository](https://github.com/hokamsingh/lessgo) or join our community discussions. -Happy coding! +**Happy coding!** ๐ŸŽ‰ ---- +--- From fca1a40cf0c9d3cbe5ee9510493514dc64ae966c Mon Sep 17 00:00:00 2001 From: Hokam Singh Sisodiya <148938898+hokamsingh@users.noreply.github.com> Date: Sun, 1 Sep 2024 15:19:01 +0530 Subject: [PATCH 3/6] Update README.md --- README.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/README.md b/README.md index 0512d92..bd5626a 100644 --- a/README.md +++ b/README.md @@ -50,6 +50,8 @@ Inspired by the modular architecture of frameworks like NestJs, LessGo offers a We are actively working on integrating WebSocket support to make real-time communication in your applications even easier. --- +### ๐Ÿ“œ Documentation + https://pkg.go.dev/github.com/hokamsingh/lessgo@v1.0.2/pkg/lessgo ### ๐Ÿ“ฆ Installation & Upgrade From 5b435314813cb768a8b7239a27aa7957510405d5 Mon Sep 17 00:00:00 2001 From: hokamsingh Date: Sun, 1 Sep 2024 17:46:57 +0530 Subject: [PATCH 4/6] feat: docs --- docs/config.md | 56 +++++++ docs/context.md | 350 +++++++++++++++++++++++++++++++++++++++++++ docs/controller.md | 82 ++++++++++ docs/introduction.md | 113 ++++++++++++++ docs/scheduler.md | 111 ++++++++++++++ 5 files changed, 712 insertions(+) create mode 100644 docs/config.md create mode 100644 docs/context.md create mode 100644 docs/controller.md create mode 100644 docs/introduction.md create mode 100644 docs/scheduler.md diff --git a/docs/config.md b/docs/config.md new file mode 100644 index 0000000..5949e19 --- /dev/null +++ b/docs/config.md @@ -0,0 +1,56 @@ +### `config` Package Documentation + +#### Overview: +The `config` package is responsible for loading and managing application configuration from environment variables and `.env` files. + +#### Functions: + +- **`LoadConfig()`**: Loads configuration from `.env` file (if found) and environment variables into a `Config` map. Searches for `.env` in the current or root directory. + +- **`Get()`**: Retrieves a string value from the config, with a fallback default. + +- **`GetInt()` / `GetBool()` / `GetFloat64()`**: Retrieves integer, boolean, or float64 values with fallback defaults, logging errors for invalid values. + +- **`Validate()`**: Ensures required keys are present, logging a fatal error if any are missing. + +- **`Reload()`**: Reloads the configuration, useful for dynamic environments. + +- **`MergeWithDefaults()`**: Combines the current config with defaults, prioritizing current values. + +- **`FilterByPrefix()`**: Returns a new config map with keys matching a given prefix, removing the prefix from keys. + +- **`findRootDir()`**: Locates the root directory containing the `.env` file, starting from the current directory. + +#### Usage: +1. **Loading Configuration:** + ```go + cfg := LoadConfig() + ``` + +2. **Accessing Configuration:** + ```go + port := cfg.Get("PORT", "8080") + timeout := cfg.GetInt("TIMEOUT", 30) + ``` + +3. **Validating Configuration:** + ```go + cfg.Validate("DB_HOST", "DB_USER", "DB_PASS") + ``` + +4. **Merging with Defaults:** + ```go + defaultConfig := Config{"PORT": "8080", "ENV": "development"} + cfg = cfg.MergeWithDefaults(defaultConfig) + ``` + +5. **Filtering by Prefix:** + ```go + dbConfig := cfg.FilterByPrefix("DB_") + ``` + +### Error Handling: +The package provides error logging for invalid data types and missing configurations, ensuring that the application fails gracefully. + +### Summary: +This package is a flexible, extendable configuration manager for Go applications, allowing for dynamic environment management, easy access to configuration variables, and integration of defaults and prefixes for modular setups. \ No newline at end of file diff --git a/docs/context.md b/docs/context.md new file mode 100644 index 0000000..320cbbb --- /dev/null +++ b/docs/context.md @@ -0,0 +1,350 @@ + +--- + +## Package `context` + +The `context` package provides utilities to handle HTTP requests and responses effectively. + +### Types + +#### `Context` + +A `Context` holds the HTTP request and response writer, and provides methods to manage request and response operations. + +### Methods + +#### `NewContext` + +```go +func NewContext(req *http.Request, res http.ResponseWriter) *Context +``` + +Creates a new `Context` instance with the given request and response writer. + +**Usage:** + +```go +ctx := context.NewContext(req, res) +``` + +#### `GetJSONBody` + +```go +func (c *Context) GetJSONBody() (map[string]interface{}, bool) +``` + +Retrieves the parsed JSON body from the request context. + +**Returns:** + +- The JSON body as a map and a boolean indicating if the body was found. + +**Usage:** + +```go +jsonBody, ok := ctx.GetJSONBody() +``` + +#### `JSON` + +```go +func (c *Context) JSON(status int, v interface{}) +``` + +Sends a JSON response with the given status code. + +**Parameters:** + +- `status`: HTTP status code. +- `v`: Data to encode as JSON. + +**Usage:** + +```go +ctx.JSON(http.StatusOK, map[string]string{"message": "success"}) +``` + +#### `Send` + +```go +func (c *Context) Send(v any) +``` + +Sends a plain text response. + +**Parameters:** + +- `v`: Value to send in the response. + +**Usage:** + +```go +ctx.Send("Hello, World!") +``` + +#### `Error` + +```go +func (c *Context) Error(status int, message string) +``` + +Sends an error response with the given status code and message. + +**Parameters:** + +- `status`: HTTP status code. +- `message`: Error message. + +**Usage:** + +```go +ctx.Error(http.StatusBadRequest, "Invalid request") +``` + +#### `Body` + +```go +func (c *Context) Body(v interface{}) error +``` + +Parses the JSON request body into the provided interface. + +**Parameters:** + +- `v`: Value to decode the JSON into. + +**Returns:** + +- An error if JSON decoding fails. + +**Usage:** + +```go +var data map[string]interface{} +err := ctx.Body(&data) +``` + +#### `Redirect` + +```go +func (c *Context) Redirect(status int, url string) +``` + +Sends a redirect response to the given URL. + +**Parameters:** + +- `status`: HTTP status code for the redirect. +- `url`: URL to redirect to. + +**Usage:** + +```go +ctx.Redirect(http.StatusSeeOther, "/new-url") +``` + +#### `SetCookie` + +```go +func (c *Context) SetCookie(name, value string, maxAge int, path string, httpOnly bool, secure bool, sameSite http.SameSite) +``` + +Adds a cookie to the response. + +**Parameters:** + +- `name`: Name of the cookie. +- `value`: Value of the cookie. +- `maxAge`: Maximum age of the cookie in seconds. +- `path`: Path for which the cookie is valid. +- `httpOnly`: If true, the cookie is accessible only via HTTP(S). +- `secure`: If true, the cookie is sent only over HTTPS. +- `sameSite`: SameSite attribute for the cookie. + +**Usage:** + +```go +ctx.SetCookie("auth_token", "0xc000013a", 60, "/", true, true, http.SameSiteLax) +``` + +#### `GetCookie` + +```go +func (c *Context) GetCookie(name string) (string, bool) +``` + +Retrieves a cookie value from the request. + +**Parameters:** + +- `name`: Name of the cookie to retrieve. + +**Returns:** + +- Value of the cookie and a boolean indicating if the cookie was found. + +**Usage:** + +```go +value, ok := ctx.GetCookie("session_id") +``` + +#### `GetParam` + +```go +func (c *Context) GetParam(name string) (string, bool) +``` + +Retrieves a URL parameter from the request. + +**Parameters:** + +- `name`: Name of the parameter to retrieve. + +**Returns:** + +- Value of the parameter and a boolean indicating if the parameter was found. + +**Usage:** + +```go +value, ok := ctx.GetParam("id") +``` + +#### `GetAllParams` + +```go +func (c *Context) GetAllParams() (map[string]string, bool) +``` + +Retrieves all URL parameters from the request. + +**Returns:** + +- A map of URL parameters and a boolean indicating if any parameters were found. + +**Usage:** + +```go +params, ok := ctx.GetAllParams() +``` + +#### `GetQuery` + +```go +func (c *Context) GetQuery(name string) (string, bool) +``` + +Retrieves a query parameter from the request URL. + +**Parameters:** + +- `name`: Name of the query parameter to retrieve. + +**Returns:** + +- Value of the query parameter and a boolean indicating if the parameter was found. + +**Usage:** + +```go +value, ok := ctx.GetQuery("search") +``` + +#### `GetAllQuery` + +```go +func (c *Context) GetAllQuery() (map[string]interface{}, error) +``` + +Retrieves all query parameters as a map. + +**Returns:** + +- A map of query parameters and their values, and an error if the parameters could not be retrieved. + +**Usage:** + +```go +queryParams, err := ctx.GetAllQuery() +``` + +#### `GetHeader` + +```go +func (c *Context) GetHeader(name string) string +``` + +Retrieves a header value from the request. + +**Parameters:** + +- `name`: Name of the header to retrieve. + +**Returns:** + +- Value of the header. + +**Usage:** + +```go +value := ctx.GetHeader("Authorization") +``` + +#### `SetHeader` + +```go +func (c *Context) SetHeader(name, value string) +``` + +Sets a header value for the response. + +**Parameters:** + +- `name`: Name of the header to set. +- `value`: Value of the header. + +**Usage:** + +```go +ctx.SetHeader("X-Custom-Header", "value") +``` + +#### `Status` + +```go +func (c *Context) Status(code int) +``` + +Sets the HTTP response code. + +**Parameters:** + +- `code`: HTTP status code. + +**Usage:** + +```go +ctx.Status(http.StatusNotFound) +``` + +#### `FileAttachment` + +```go +func (c *Context) FileAttachment(filepath, filename string) +``` + +Sends a file as an attachment for download. + +**Parameters:** + +- `filepath`: Path to the file. +- `filename`: Name of the file as it will appear to the client. + +**Usage:** + +```go +ctx.FileAttachment("/path/to/file.txt", "file.txt") +``` + +--- \ No newline at end of file diff --git a/docs/controller.md b/docs/controller.md new file mode 100644 index 0000000..d570a85 --- /dev/null +++ b/docs/controller.md @@ -0,0 +1,82 @@ + +--- + +## Package `controller` + +The `controller` package provides a base structure and interface for defining and registering routes in the application. + +### Types + +#### `Controller` + +The `Controller` interface defines the contract for all controllers in the application. Controllers implementing this interface must define the `RegisterRoutes` method to set up the necessary routes. + +```go +type Controller interface { + RegisterRoutes(r *router.Router) +} +``` + +#### `BaseController` + +The `BaseController` struct provides a default implementation of the `Controller` interface. It can be embedded in other controllers to inherit default behavior or overridden with custom implementations. + +```go +type BaseController struct { +} +``` + +### Methods + +#### `BaseController.RegisterRoutes` + +```go +func (bc *BaseController) RegisterRoutes(r *router.Router) +``` + +The `RegisterRoutes` method provides a default implementation of the `Controller` interface's method. It can be overridden by embedding `BaseController` in another struct and defining a custom implementation. + +**Example:** + +```go +type TestController struct { + BaseController + Path string + Service TestService +} + +func NewTestController(service *TestService, path string) *TestController { + return &TestController{ + Service: *service, + Path: path, + } +} + +func (tc *TestController) RegisterRoutes(r *router.Router) { + tr := r.SubRouter(tc.Path) + tr.Get("/ping", func(ctx *router.Context) { + ctx.Send("pong") + }) +} +``` + +#### `RegisterModuleRoutes` + +```go +func RegisterModuleRoutes(r *router.Router, m module.IModule) +``` + +The `RegisterModuleRoutes` function registers routes for a module. It iterates through the module's controllers, ensuring each controller implements the `Controller` interface and then calls `RegisterRoutes` to set up the routes. + +**Parameters:** + +- `r`: The router instance used to register the routes. +- `m`: The module containing controllers to register. + +**Usage:** + +```go +RegisterModuleRoutes(routerInstance, moduleInstance) +``` + +--- \ No newline at end of file diff --git a/docs/introduction.md b/docs/introduction.md new file mode 100644 index 0000000..70746e4 --- /dev/null +++ b/docs/introduction.md @@ -0,0 +1,113 @@ +--- +![License](https://img.shields.io/badge/license-MIT-green.svg) +[![Go Reference](https://pkg.go.dev/badge/github.com/hokamsingh/lessgo)](https://pkg.go.dev/github.com/hokamsingh/lessgo) +[![Go Version](https://img.shields.io/github/go-mod/go-version/hokamsingh/lessgo-cli)](https://golang.org/dl/) +![Version](https://img.shields.io/badge/version-v1.0.2-blue) +[![Go Report Card](https://goreportcard.com/badge/github.com/hokamsingh/lessgo)](https://goreportcard.com/report/github.com/hokamsingh/lessgo) + +## ๐Ÿ› ๏ธ LessGo Framework Release + +We are excited to announce the latest release of the **LessGo** framework! This release introduces several powerful features and enhancements to make your Go development experience even more robust and efficient. + +### ๐Ÿš€ New Features + +- **Enhanced Dependency Injection (DI)**: + - **Conditional Bindings**: Register dependencies based on specific conditions. + - **Scoped Services**: Manage services with different lifetimes and scopes. + - **Named Dependencies**: Support for naming dependencies for more granular control. + +- **Dynamic Configuration Management**: + - **Factory Pattern**: Implement dynamic configuration management with factories to handle various application environments and requirements. + +- **Inbuilt Error Handling**: + - **Custom Error Responses**: Integrate a flexible error handling system that returns appropriate HTTP responses based on the error type. + - **Detailed Logging**: Capture detailed error logs and stack traces for better debugging. + +- **Job Scheduler Integration**: + - **Built-in Scheduler**: Utilize an advanced job scheduling library for managing periodic tasks and background jobs seamlessly. + +- **JSON Response Handling**: + - **Automatic JSON Parsing**: Simplify the process of parsing and responding with JSON data. + - **Custom JSON Encoding**: Encode and decode JSON responses with integrated error handling. + +- **Advanced Data Validation**: + - **Strict Validation**: Ensure data integrity by validating incoming requests against predefined models. + - **Dynamic Key Checks**: Verify that all required fields are present in the request payload. + +- **๐Ÿ›ก๏ธ CSRF Protection Middleware**: + - **`LessGo.WithCsrf()`**: Integrated Cross-Site Request Forgery (CSRF) protection to safeguard your applications against unauthorized actions. + +- **๐Ÿ”’ XSS Protection Middleware**: + - **`LessGo.WithXss()`**: Built-in Cross-Site Scripting (XSS) protection to prevent malicious script injections. + +- **โšก Caching Middleware**: + - **`LessGo.WithCaching("localhost:6379", 5*time.Minute)`**: Redis-based caching middleware for improved performance with configurable cache expiration +- **Response Handling** + - Enhanced response handling to ensure multiple responses are not sent from the same context, preventing unexpected behaviors and potential crashes. + +- **Template Rendering** + - Introduced support for rendering templates dynamically from a specified directory, reducing the need to manually list each template file. + +- **Middleware Improvements** + - Refined existing middleware to ensure seamless integration and performance. + - Addressed potential edge cases and improved overall robustness. + +## โš™๏ธ Migration Notes + +- The new security middlewares (`WithCsrf` and `WithXss`) are optional but highly recommended for applications that handle sensitive data. +- The caching middleware requires a running Redis instance. Ensure your Redis server is properly configured and accessible from your application. + +## ๐Ÿ›ก๏ธ Security + +- Security is a top priority for us, and this release emphasizes that with the introduction of CSRF and XSS protection middlewares. We strongly recommend enabling these features to safeguard your applications against common web vulnerabilities. + + +### ๐Ÿ“š Documentation & Examples + +- **Enhanced Documentation**: Comprehensive guides and examples to help you get started with the new features and integrations. +- **Code Examples**: Practical examples demonstrating how to use the new features in real-world applications. + +### ๐Ÿ› ๏ธ Improvements & Fixes + +- **Performance Enhancements**: Optimizations for better performance and reduced resource usage. +- **Bug Fixes**: Various bug fixes and stability improvements to ensure a smoother development experience. + +### ๐Ÿ“ฆ Installation & Upgrade + +To get started with the latest version of LessGo, update your dependencies using: + +```sh +go get github.com/hokamsingh/lessgo@latest +``` + +### ๐ŸŒŸ Get Started Quickly with LessGo CLI + +We're also introducing the **LessGo CLI**, a command-line tool to help you scaffold and manage your LessGo projects with ease! With the CLI, you can: + +- **Create a New Project**: Quickly set up a new LessGo project using `lessgo-cli new myapp`. +- **Check Version**: Keep track of the CLI version with `lessgo-cli --version`. +- **Cross-Platform Support**: Works seamlessly on both Windows and Unix-based systems. + +Install the LessGo CLI with: + +```sh +go install github.com/hokamsingh/lessgo-cli@latest +``` + +Make sure to try out the CLI to streamline your project setup and start building with LessGo in no time! + +### ๐Ÿ™Œ Acknowledgments + +We would like to thank our contributors and community for their support and feedback. Your contributions have been invaluable in shaping the LessGo framework. + +## License + +This project is licensed under the MIT License - see the [LICENSE](./LICENSE) file for details. + +--- + +For any questions, issues, or feedback, please visit our [GitHub repository](https://github.com/hokamsingh/lessgo) or join our [community discussions](#). + +Happy coding! + +--- diff --git a/docs/scheduler.md b/docs/scheduler.md new file mode 100644 index 0000000..f6b5889 --- /dev/null +++ b/docs/scheduler.md @@ -0,0 +1,111 @@ + +--- + +## Package `scheduler` + +The `scheduler` package provides an interface and an implementation for scheduling recurring jobs using a cron-like syntax. + +### Types + +#### `Scheduler` + +The `Scheduler` interface defines methods for scheduling jobs. + +```go +type Scheduler interface { + AddJob(schedule string, job func()) error + Start() + Stop() +} +``` + +#### `CronScheduler` + +The `CronScheduler` struct implements the `Scheduler` interface using the `robfig/cron/v3` package for cron-based job scheduling. + +```go +type CronScheduler struct { + cron *cron.Cron +} +``` + +### Functions + +#### `NewCronScheduler` + +```go +func NewCronScheduler() *CronScheduler +``` + +Creates a new instance of `CronScheduler`. This scheduler can be used to schedule jobs with cron expressions. + +**Example:** + +```go +s := scheduler.NewCronScheduler() +err := s.AddJob("* * * * *", func() { + fmt.Println("Hello, World!") +}) +if err != nil { + log.Fatalf("Failed to add job: %v", err) +} +s.Start() +time.Sleep(10 * time.Minute) +s.Stop() +``` + +#### `AddJob` + +```go +func (s *CronScheduler) AddJob(schedule string, job func()) error +``` + +Adds a job to the scheduler with a specified cron schedule. The job will be executed according to the provided cron expression. + +**Parameters:** + +- `schedule`: The cron expression to determine the job schedule. +- `job`: The function to execute. + +**Example:** + +```go +err := s.AddJob("0 0 * * *", func() { + fmt.Println("It's midnight!") +}) +if err != nil { + log.Fatalf("Failed to add job: %v", err) +} +``` + +#### `Start` + +```go +func (s *CronScheduler) Start() +``` + +Begins the execution of scheduled jobs. This method should be called to start the scheduler after all jobs have been added. + +**Example:** + +```go +s.Start() +``` + +#### `Stop` + +```go +func (s *CronScheduler) Stop() +``` + +Halts the execution of scheduled jobs. This method stops the scheduler and prevents any further job executions. + +**Example:** + +```go +s.Start() +time.Sleep(1 * time.Hour) +s.Stop() +``` + +--- \ No newline at end of file From 2a935b6dab45db8a40c381a1b404b9e1ba5ccde8 Mon Sep 17 00:00:00 2001 From: hokamsingh Date: Sun, 1 Sep 2024 17:59:01 +0530 Subject: [PATCH 5/6] feat: docs --- docs/lessgo.md | 116 +++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 116 insertions(+) create mode 100644 docs/lessgo.md diff --git a/docs/lessgo.md b/docs/lessgo.md new file mode 100644 index 0000000..7316f1c --- /dev/null +++ b/docs/lessgo.md @@ -0,0 +1,116 @@ + +## Package Overview + +### Configuration + +- **`LessGo.LoadConfig()`**: Loads the configuration settings. Typically used to configure server parameters like port and environment. +- **`cfg.GetInt(key, default)`**: Retrieves an integer configuration value. +- **`cfg.Get(key, default)`**: Retrieves a string configuration value. + +### Middleware and Options + +- **`LessGo.NewCorsOptions(origins, methods, headers)`**: Creates new CORS options for handling cross-origin requests. +- **`LessGo.NewParserOptions(maxSize)`**: Configures options for JSON parsing, including maximum size of request bodies. +- **`LessGo.NewRedisClient(address)`**: Creates a new Redis client instance. +- **`LessGo.WithCORS(options)`**: Adds CORS middleware with the provided options. +- **`LessGo.WithJSONParser(options)`**: Adds JSON parsing middleware with specified options. +- **`LessGo.WithCookieParser()`**: Adds middleware for parsing cookies. +- **`LessGo.WithCsrf()`**: Adds CSRF protection middleware. +- **`LessGo.WithXss()`**: Adds XSS protection middleware. +- **`LessGo.WithCaching(client, duration, enable)`**: Adds caching middleware using Redis. +- **`LessGo.WithRedisRateLimiter(address, limit, duration)`**: Adds rate limiting middleware with Redis. + +### Application Initialization + +- **`LessGo.App(middlewares...)`**: Initializes a new application instance with the provided middlewares. +- **`App.ServeStatic(path, folderPath)`**: Configures the application to serve static files from a specified folder. +- **`LessGo.RegisterDependencies(dependencies)`**: Registers dependencies for dependency injection. +- **`LessGo.RegisterModules(app, modules)`**: Registers application modules with the framework. + +### Routes and Server + +- **`App.Get(route, handler)`**: Registers a GET route with a specified handler. +- **`App.Listen(address)`**: Starts the server and listens on the specified address. + +### Example Usage +```go +// main.go + +// @title My API +// @version 1.0 +// @description This is a sample server. +// @host localhost:8080 +// @BasePath / + +package main + +import ( + "log" + "time" + + "github.com/hokamsingh/lessgo/app/src" + LessGo "github.com/hokamsingh/lessgo/pkg/lessgo" +) + +func main() { + // Load Configuration + cfg := LessGo.LoadConfig() + serverPort := cfg.GetInt("SERVER_PORT", 8080) + env := cfg.Get("ENV", "development") + addr := ":" + string(rune(serverPort)) + + // CORS Options + corsOptions := LessGo.NewCorsOptions( + []string{"*"}, // Allow all origins + []string{"GET", "POST", "PUT", "DELETE", "OPTIONS"}, // Allowed methods + []string{"Content-Type", "Authorization"}, // Allowed headers + ) + + // Parser Options + size := LessGo.ConvertToBytes(int64(1024), LessGo.Kilobytes) + parserOptions := LessGo.NewParserOptions(size * 5) + + // redis client + rClient := LessGo.NewRedisClient("localhost:6379") + + // Initialize App with Middlewares + App := LessGo.App( + LessGo.WithCORS(*corsOptions), + // LessGo.WithInMemoryRateLimiter(4, 50, 1*time.Second, 5*time.Minute), // Rate limiter + // LessGo.WithRedisRateLimiter("localhost:6379", 10, time.Minute*5), + LessGo.WithJSONParser(*parserOptions), + LessGo.WithCookieParser(), // Cookie parser + LessGo.WithCsrf(), // CSRF protection middleware + LessGo.WithXss(), // XSS protection middleware + LessGo.WithCaching(rClient, 5*time.Minute, true), // Caching middleware using Redis + LessGo.WithRedisRateLimiter(rClient, 100, 1*time.Second), + // LessGo.WithFileUpload("uploads"), // Uncomment if you want to handle file uploads + ) + + // Serve Static Files + folderPath := LessGo.GetFolderPath("uploads") + App.ServeStatic("/static/", folderPath) + + // Register dependencies + dependencies := []interface{}{src.NewRootService, src.NewRootModule} + LessGo.RegisterDependencies(dependencies) + + // Root Module + rootModule := src.NewRootModule(App) + LessGo.RegisterModules(App, []LessGo.IModule{rootModule}) + + // Example Route + App.Get("/ping", func(ctx *LessGo.Context) { + ctx.Send("pong") + }) + + // Start the server + log.Printf("Starting server on port %s in %s mode", serverPort, env) + // LessGo.PProfiling() + if err := App.Listen(addr); err != nil { + log.Fatalf("Server failed: %v", err) + } +} +``` +In the example provided, the server is configured to use various middleware options, serve static files, and register dependencies and modules. The server listens on a specified port and handles requests with CSRF protection and other middleware features. +``` \ No newline at end of file From b6eb45795bf6f533b892f47ab6dfe6dc935ae419 Mon Sep 17 00:00:00 2001 From: hokamsingh Date: Sun, 1 Sep 2024 18:08:22 +0530 Subject: [PATCH 6/6] feat: docs --- docs/controller.md | 10 +++++----- docs/scheduler.md | 2 +- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/docs/controller.md b/docs/controller.md index d570a85..8e84a60 100644 --- a/docs/controller.md +++ b/docs/controller.md @@ -13,7 +13,7 @@ The `Controller` interface defines the contract for all controllers in the appli ```go type Controller interface { - RegisterRoutes(r *router.Router) + RegisterRoutes(r *LessGo.Router) } ``` @@ -31,7 +31,7 @@ type BaseController struct { #### `BaseController.RegisterRoutes` ```go -func (bc *BaseController) RegisterRoutes(r *router.Router) +func (bc *BaseController) RegisterRoutes(r *LessGo.Router) ``` The `RegisterRoutes` method provides a default implementation of the `Controller` interface's method. It can be overridden by embedding `BaseController` in another struct and defining a custom implementation. @@ -52,9 +52,9 @@ func NewTestController(service *TestService, path string) *TestController { } } -func (tc *TestController) RegisterRoutes(r *router.Router) { +func (tc *TestController) RegisterRoutes(r *LessGo.Router) { tr := r.SubRouter(tc.Path) - tr.Get("/ping", func(ctx *router.Context) { + tr.Get("/ping", func(ctx *LessGo.Context) { ctx.Send("pong") }) } @@ -63,7 +63,7 @@ func (tc *TestController) RegisterRoutes(r *router.Router) { #### `RegisterModuleRoutes` ```go -func RegisterModuleRoutes(r *router.Router, m module.IModule) +func RegisterModuleRoutes(r *LessGo.Router, m LessGo.IModule) ``` The `RegisterModuleRoutes` function registers routes for a module. It iterates through the module's controllers, ensuring each controller implements the `Controller` interface and then calls `RegisterRoutes` to set up the routes. diff --git a/docs/scheduler.md b/docs/scheduler.md index f6b5889..55b1d4a 100644 --- a/docs/scheduler.md +++ b/docs/scheduler.md @@ -42,7 +42,7 @@ Creates a new instance of `CronScheduler`. This scheduler can be used to schedul **Example:** ```go -s := scheduler.NewCronScheduler() +s := LessGo.NewCronScheduler() err := s.AddJob("* * * * *", func() { fmt.Println("Hello, World!") })