Skip to content

Commit

Permalink
updated routing to easy implementation
Browse files Browse the repository at this point in the history
  • Loading branch information
Danushka96 committed Dec 1, 2024
1 parent d0c3f6d commit 53cde0c
Show file tree
Hide file tree
Showing 7 changed files with 363 additions and 136 deletions.
154 changes: 154 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -240,6 +240,160 @@ server.WithCORS(&config)

This gives you access to all CORS configuration options provided by gin-contrib/cors.

## Routing

GinBoot provides a flexible and intuitive routing system that follows Gin's style while adding powerful controller-based routing capabilities.

### Base Path Configuration

You can set a base path for all routes in your application:

```go
server := ginboot.New()
server.SetBasePath("/api/v1") // All routes will be prefixed with /api/v1
```

### Controller Registration

Controllers implement the `Controller` interface which requires a `Register` method:

```go
type Controller interface {
Register(group *ControllerGroup)
}
```

Example controller implementation:

```go
type UserController struct {
userService *service.UserService
}

func (c *UserController) Register(group *ginboot.ControllerGroup) {
// Public routes
group.GET("", c.ListUsers)
group.GET("/:id", c.GetUser)

// Protected routes
protected := group.Group("", middleware.Auth())
{
protected.POST("", c.CreateUser)
protected.PUT("/:id", c.UpdateUser)
protected.DELETE("/:id", c.DeleteUser)
}
}
```

### Registering Controllers

Register controllers with their base paths:

```go
// Initialize controllers
userController := NewUserController(userService)
postController := NewPostController(postService)

// Register with paths
server.RegisterController("/users", userController) // -> /api/v1/users
server.RegisterController("/posts", postController) // -> /api/v1/posts
```

### Route Groups

Create route groups with shared middleware:

```go
// Create a group with middleware
adminGroup := server.Group("/admin", middleware.Auth(), middleware.AdminOnly())
{
adminGroup.GET("/stats", adminController.GetStats)
adminGroup.POST("/settings", adminController.UpdateSettings)
}

// Nested groups
apiGroup := server.Group("/api")
v1Group := apiGroup.Group("/v1")
{
v1Group.GET("/health", healthCheck)
}
```

### HTTP Methods

GinBoot supports all standard HTTP methods:

```go
group.GET("", handler) // GET request
group.POST("", handler) // POST request
group.PUT("", handler) // PUT request
group.DELETE("", handler) // DELETE request
group.PATCH("", handler) // PATCH request
group.OPTIONS("", handler) // OPTIONS request
group.HEAD("", handler) // HEAD request
```

### Middleware

Add middleware at different levels:

```go
// Server-wide middleware
server.Use(middleware.Logger())

// Group middleware
group := server.Group("/admin", middleware.Auth())

// Route-specific middleware
group.GET("/users", middleware.Cache(), controller.ListUsers)
```

### Path Parameters

Use Gin's path parameter syntax:

```go
group.GET("/:id", controller.GetUser) // /users/123
group.GET("/:type/*path", controller.GetFile) // /files/image/avatar.png
```

### Full Example

```go
func main() {
server := ginboot.New()

// Set base path for all routes
server.SetBasePath("/api/v1")

// Global middleware
server.Use(middleware.Logger())

// Initialize controllers
userController := NewUserController(userService)
postController := NewPostController(postService)

// Register controllers
server.RegisterController("/users", userController)
server.RegisterController("/posts", postController)

// Create admin group
adminGroup := server.Group("/admin", middleware.Auth(), middleware.AdminOnly())
adminController := NewAdminController(adminService)
adminController.Register(adminGroup)

// Start server
server.Start(8080)
}
```

This setup creates a clean, maintainable API structure with routes like:
- GET /api/v1/users
- POST /api/v1/posts
- GET /api/v1/admin/stats

The routing system combines the simplicity of Gin's routing with the power of controller-based organization, making it easy to structure and maintain your API endpoints.

## Server Configuration

GinBoot provides a flexible server configuration that supports both HTTP and AWS Lambda runtimes.
Expand Down
42 changes: 14 additions & 28 deletions example/cmd/main.go
Original file line number Diff line number Diff line change
@@ -1,64 +1,50 @@
package main

import (
"context"
"log"
"time"

"github.com/gin-gonic/gin"
"github.com/klass-lk/ginboot"
"github.com/klass-lk/ginboot/example/internal/controller"
"github.com/klass-lk/ginboot/example/internal/middleware"
"github.com/klass-lk/ginboot/example/internal/repository"
"github.com/klass-lk/ginboot/example/internal/service"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
)

func main() {
// Connect to MongoDB
client, err := mongo.Connect(context.Background(), options.Client().ApplyURI("mongodb://localhost:27017"))
// Initialize MongoDB client
client, err := mongo.Connect(nil, options.Client().ApplyURI("mongodb://localhost:27017"))
if err != nil {
log.Fatal(err)
}
defer client.Disconnect(context.Background())

db := client.Database("blog")
defer client.Disconnect(nil)

// Initialize repositories
postRepo := repository.NewPostRepository(db)
postRepo := repository.NewPostRepository(client.Database("example"))

// Initialize services
postService := service.NewPostService(postRepo)

// Initialize controllers
postController := controller.NewPostController(postService)

// Create a new server instance
// Initialize server
server := ginboot.New()

// Set base path for all routes
server.SetBasePath("/api/v1")

// Configure CORS with custom settings
server.CustomCORS(
[]string{"http://localhost:3000", "https://yourdomain.com"}, // Allow specific origins
[]string{"GET", "POST", "PUT", "DELETE", "OPTIONS"}, // Allow specific methods
[]string{"http://localhost:3000", "https://yourdomain.com"}, // Allow specific origins
[]string{"GET", "POST", "PUT", "DELETE", "OPTIONS"}, // Allow specific methods
[]string{"Origin", "Content-Type", "Authorization", "Accept"}, // Allow specific headers
24*time.Hour, // Max age of preflight requests
24*time.Hour, // Max age of preflight requests
)

// Register controllers with their base paths
server.RegisterControllers(postController)

apiGroup := ginboot.RouterGroup{
Path: "/api/v1",
Middleware: []gin.HandlerFunc{middleware.AuthMiddleware()},
Controllers: []ginboot.Controller{
&controller.PostController{},
},
}
// Initialize and register controllers
postController := controller.NewPostController(postService)

server.RegisterGroups(apiGroup)
server.RegisterController("/posts", postController)

// Start server
if err := server.Start(8080); err != nil {
log.Fatal(err)
}
Expand Down
3 changes: 2 additions & 1 deletion example/go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@ require (
github.com/cloudwego/iasm v0.2.0 // indirect
github.com/dgrijalva/jwt-go v3.2.0+incompatible // indirect
github.com/gabriel-vasile/mimetype v1.4.3 // indirect
github.com/gin-contrib/cors v1.7.2 // indirect
github.com/gin-contrib/sse v0.1.0 // indirect
github.com/go-playground/locales v0.14.1 // indirect
github.com/go-playground/universal-translator v0.18.1 // indirect
Expand All @@ -61,7 +62,7 @@ require (
github.com/youmark/pkcs8 v0.0.0-20240726163527-a2c0da244d78 // indirect
golang.org/x/arch v0.8.0 // indirect
golang.org/x/crypto v0.26.0 // indirect
golang.org/x/net v0.25.0 // indirect
golang.org/x/net v0.26.0 // indirect
golang.org/x/sync v0.8.0 // indirect
golang.org/x/sys v0.23.0 // indirect
golang.org/x/text v0.17.0 // indirect
Expand Down
Loading

0 comments on commit 53cde0c

Please sign in to comment.