supergin

package module
v0.0.0-...-2032b30 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jun 21, 2025 License: GPL-3.0 Imports: 19 Imported by: 0

README

SuperGin 🚀

An enhanced Gin framework for Go that provides Rails-like conventions, dependency injection, input/output validation, WebSocket support, and gRPC-HTTP bridging. SuperGin wraps the powerful Gin HTTP framework while adding modern web development features.

✨ Features

  • 📛 Named Routes - Route registry with name-based URL generation
  • 📦 Input/Output Validation - Automatic JSON binding and validation
  • 🏗️ Dependency Injection - Global DI container with singleton, request, and transient scopes
  • 🛤️ Rails-like REST Resources - Convention over configuration for CRUD operations
  • 📎 Route Metadata & Annotations - Rich route documentation and tagging
  • 📄 Automatic API Documentation - Built-in endpoint for API introspection
  • 🔌 WebSocket Support - Real-time bidirectional communication with connection management
  • 🌉 gRPC-HTTP Bridge - Automatic conversion between gRPC and HTTP with protobuf support
  • 🧪 Testable Route Registry - Easy testing and route verification
  • 🔧 Fluent API - Chainable, readable route definitions

🚀 Quick Start

Installation
go get github.com/supergin/supergin
Basic Usage
package main

import (
    "github.com/supergin/supergin"
    "github.com/gin-gonic/gin"
)

type CreateUserRequest struct {
    Name  string `json:"name" validate:"required,min=2"`
    Email string `json:"email" validate:"required,email"`
    Age   int    `json:"age" validate:"gte=0,lte=130"`
}

type UserResponse struct {
    ID    int    `json:"id"`
    Name  string `json:"name"`
    Email string `json:"email"`
    Age   int    `json:"age"`
}

func main() {
    // Create SuperGin engine
    app := supergin.New()

    // Traditional route with validation
    app.Named("create_user").
        POST("/users").
        WithIO(CreateUserRequest{}, UserResponse{}).
        WithDescription("Create a new user").
        WithTags("users", "create").
        Handler(func(c *gin.Context) {
            if input, exists := supergin.GetValidatedInput(c); exists {
                req := input.(*CreateUserRequest)
                // Handle validated request...
                response := User                response := UserResponse{
                    ID:    123,
                    Name:  req.Name,
                    Email: req.Email,
                    Age:   req.Age,
                }
                c.JSON(201, response)
            }
        })

    app.Run(":8080")
}

🏗️ Dependency Injection

SuperGin provides a powerful global DI container that eliminates context passing:

// Setup DI
supergin.RegisterSingleton("database", func(config *DatabaseConfig) Database {
    return &PostgresDB{config: config}
}, "dbConfig")

supergin.RegisterRequest("userService", func(repo UserRepository) UserService {
    return &UserServiceImpl{repo: repo}
}, "userRepository")

// Use in handlers without context passing
func (uc *UserController) Create(c *gin.Context) {
    // Resolve service directly - no dependency drilling!
    userService := supergin.Resolve[UserService]("userService")
    
    user, err := userService.CreateUser(req)
    // ...
}
DI Scopes
  • Singleton: One instance for entire application
  • Request: One instance per HTTP request (thread-safe)
  • Transient: New instance every time

🛤️ Rails-like REST Resources

Generate full CRUD routes with convention over configuration:

// Implement the CRUD interface
type UserController struct{}

func (uc *UserController) Create(c *gin.Context) { /* ... */ }
func (uc *UserController) Read(c *gin.Context)   { /* ... */ }
func (uc *UserController) Update(c *gin.Context) { /* ... */ }
func (uc *UserController) Delete(c *gin.Context) { /* ... */ }
func (uc *UserController) List(c *gin.Context)   { /* ... */ }
func (uc *UserController) Search(c *gin.Context) { /* ... */ }

// Generate REST routes
userRoutes := app.Resource("User", &UserController{}).
    WithModel(CreateUserRequest{}, UserResponse{}, UserSearchRequest{}).
    WithTags("api", "v1").
    WithMiddleware(authMiddleware).
    // Add custom routes
    Member("activate", "POST", "/activate", activateHandler).
    Collection("export", "GET", "/export", exportHandler).
    Build()

This generates:

  • GET /users → List users
  • POST /users → Create user
  • GET /users/:id → Get user
  • PUT /users/:id → Update user
  • DELETE /users/:id → Delete user
  • GET /users/search → Search users
  • POST /users/:id/activate → Custom member route
  • GET /users/export → Custom collection route

🔌 WebSocket Support

Real-time bidirectional communication with connection management:

// Implement WebSocket handler
type ChatHandler struct{}

func (h *ChatHandler) OnConnect(conn *supergin.WebSocketConnection) {
    log.Printf("Client connected: %s", conn.ID)
    conn.Send("welcome", map[string]interface{}{
        "message": "Welcome to the chat!",
    })
}

func (h *ChatHandler) OnMessage(conn *supergin.WebSocketConnection, messageType string, data interface{}) {
    // Handle different message types
    switch messageType {
    case "chat_message":
        // Broadcast to all connections
        conn.Hub.Broadcast("new_message", data)
    case "ping":
        conn.Send("pong", map[string]interface{}{"timestamp": time.Now()})
    }
}

// Register WebSocket endpoint
chatHub := app.WebSocket("chat", "/ws/chat", &ChatHandler{})

// Broadcast from anywhere in your application
chatHub.Broadcast("notification", map[string]interface{}{
    "type": "system",
    "message": "Server maintenance in 5 minutes",
})
WebSocket Features
  • Connection Management: Automatic connection tracking and cleanup
  • Message Broadcasting: Send to all connections or specific ones
  • Connection Metadata: Store user sessions and custom data
  • Event Handlers: OnConnect, OnDisconnect, OnMessage, OnError
  • Hub Management: Centralized connection management

🌉 gRPC-HTTP Bridge

Automatic bidirectional conversion between gRPC and HTTP:

// Define your HTTP and gRPC types
type CreateUserRequest struct {
    Name  string `json:"name"`
    Email string `json:"email"`
    Age   int    `json:"age"`
}

type CreateUserGrpcRequest struct {
    Name  string `protobuf:"bytes,1,opt,name=name"`
    Email string `protobuf:"bytes,2,opt,name=email"`
    Age   int32  `protobuf:"varint,3,opt,name=age"`
}

// Implement custom conversion (optional)
func (req *CreateUserRequest) ToGrpc() (proto.Message, error) {
    return &CreateUserGrpcRequest{
        Name:  req.Name,
        Email: req.Email,
        Age:   int32(req.Age),
    }, nil
}

// Register gRPC service
bridge := app.GrpcBridge()
bridge.RegisterGrpcService("userService", "localhost:9090", "user.UserService")

// Create bidirectional bridge
app.BidirectionalGrpcHttp("user_create",
    "/api/users/grpc",           // HTTP endpoint
    "userService", "CreateUser", // gRPC service and method
    CreateUserRequest{}, UserResponse{},           // HTTP types
    &CreateUserGrpcRequest{}, &UserGrpcResponse{}) // gRPC types

This creates:

  • HTTP → gRPC: POST /api/users/grpc forwards to gRPC service
  • gRPC → HTTP: POST /grpc/users/grpc accepts gRPC and converts to HTTP
gRPC Bridge Features
  • Automatic Conversion: JSON ↔ Protobuf conversion
  • Custom Converters: Implement GrpcConverter interface for custom logic
  • Bidirectional: Both HTTP→gRPC and gRPC→HTTP
  • Type Safety: Compile-time type checking
  • Metadata Handling: HTTP headers ↔ gRPC metadata

📦 Input/Output Validation

Automatic validation using struct tags:

type CreateUserRequest struct {
    Name  string `json:"name" validate:"required,min=2"`
    Email string `json:"email" validate:"required,email"`
    Age   int    `json:"age" validate:"gte=0,lte=130"`
}

app.Named("create_user").
    POST("/users").
    WithInput(CreateUserRequest{}).  // Automatic validation
    Handler(func(c *gin.Context) {
        // Input is pre-validated and available
        if input, exists := supergin.GetValidatedInput(c); exists {
            req := input.(*CreateUserRequest)
            // req is guaranteed to be valid
        }
    })

📛 Named Routes & URL Generation

// Define named routes
app.Named("show_user").GET("/users/:id").Handler(handler)

// Generate URLs
url, _ := app.URLFor("show_user", "id", "123")
// Returns: "/users/123"

// Access route metadata
route, exists := app.GetRoute("show_user")
if exists {
    fmt.Printf("Route: %s %s", route.Method, route.Path)
}

📄 API Documentation

Built-in documentation endpoint:

# View all routes, DI services, and WebSocket endpoints
curl http://localhost:8080/docs

# Returns:
{
  "routes": {
    "create_user": {
      "method": "POST",
      "path": "/users",
      "description": "Create a new user",
      "tags": ["users", "create"]
    }
  },
  "di_services": {
    "userService": {
      "type": "UserService",
      "scope": "request",
      "dependencies": ["userRepository"]
    }
  }
}

🧪 Testing

SuperGin makes testing easy with route registry and DI:

func TestUserRoutes(t *testing.T) {
    app := supergin.New()
    
    // Setup test routes
    setupRoutes(app)
    
    // Verify routes exist
    assert.True(t, app.HasRoute("create_user"))
    
    // Test route metadata
    route, _ := app.GetRoute("create_user")
    assert.Equal(t, "POST", route.Method)
    assert.Equal(t, "/users", route.Path)
    
    // Test DI services
    services := app.DI().ListServices()
    assert.Contains(t, services, "userService")
    
    // Test WebSocket functionality
    hub := app.GetWebSocketHub("chat")
    assert.NotNil(t, hub)
}

🔧 Configuration

app := supergin.New(supergin.Config{
    EnableDocs:     true,          // Enable /docs endpoint
    ValidateInput:  true,          // Enable input validation
    ValidateOutput: false,         // Enable output validation
    DocsPath:       "/api/docs",   // Custom docs path
})

📂 Project Structure

github.com/supergin/supergin/
├── go.mod                 # Go module with dependencies
├── supergin.go           # Main engine and core types
├── route_builder.go      # Fluent route building API
├── di.go                 # Dependency injection system
├── resource.go           # Rails-like REST resources
├── websocket.go          # WebSocket connection management
├── grpc_bridge.go        # gRPC-HTTP bidirectional bridge
├── errors.go             # Error types and handling
├── examples/
│   ├── basic/main.go     # Basic HTTP API example
│   └── advanced/main.go  # Advanced example with WebSocket + gRPC
├── Makefile              # Build and development tasks
└── README.md             # This file

🛠️ Development

# Run basic example
make run-example

# Run advanced example with WebSocket and gRPC
cd examples/advanced && go run main.go

# Run tests
make test

# Format and lint
make fmt vet

# Build for release
make build-release

📚 Examples

Basic Example

See examples/basic/main.go for HTTP API with DI.

Advanced Example

See examples/advanced/main.go for a complete application featuring:

  • ✅ HTTP API with dependency injection
  • ✅ Real-time WebSocket chat with connection management
  • ✅ gRPC-HTTP bidirectional bridge
  • ✅ Custom type conversion
  • ✅ Interactive chat demo webpage
  • ✅ REST resource generation
  • ✅ Input/output validation
  • ✅ Route introspection
# Run the advanced example
cd examples/advanced
go run main.go

# Visit the chat demo
open http://localhost:8080/chat

🚀 Quick Start with All Features

package main

import "github.com/supergin/supergin"

func main() {
    app := supergin.New()
    
    // Dependency Injection
    supergin.RegisterSingleton("service", func() MyService {
        return &MyServiceImpl{}
    })
    
    // REST Resources  
    app.Resource("User", &UserController{}).
        WithModel(CreateUserRequest{}, UserResponse{}, UserSearchRequest{}).
        Build()
    
    // WebSocket
    app.WebSocket("chat", "/ws/chat", &ChatHandler{})
    
    // gRPC Bridge
    app.BidirectionalGrpcHttp("grpc_endpoint",
        "/api/grpc", "service", "method",
        HTTPInput{}, HTTPOutput{},
        &GrpcInput{}, &GrpcOutput{})
    
    app.Run(":8080")
}

🤝 Contributing

Contributions welcome! Please feel free to submit a Pull Request.

📄 License

This project is licensed under the MIT License.

🙏 Acknowledgments


SuperGin - The complete Go web framework for modern applications! 🚀Response{ ID: 123, Name: req.Name, Email: req.Email, Age: req.Age, } c.JSON(201, response) } })

app.Run(":8080")

}


## 🏗️ Dependency Injection

SuperGin provides a powerful global DI container that eliminates context passing:

```go
// Setup DI
supergin.RegisterSingleton("database", func(config *DatabaseConfig) Database {
    return &PostgresDB{config: config}
}, "dbConfig")

supergin.RegisterRequest("userService", func(repo UserRepository) UserService {
    return &UserServiceImpl{repo: repo}
}, "userRepository")

// Use in handlers without context passing
func (uc *UserController) Create(c *gin.Context) {
    // Resolve service directly - no dependency drilling!
    userService := supergin.Resolve[UserService]("userService")
    
    user, err := userService.CreateUser(req)
    // ...
}
DI Scopes
  • Singleton: One instance for entire application
  • Request: One instance per HTTP request (thread-safe)
  • Transient: New instance every time

🛤️ Rails-like REST Resources

Generate full CRUD routes with convention over configuration:

// Implement the CRUD interface
type UserController struct{}

func (uc *UserController) Create(c *gin.Context) { /* ... */ }
func (uc *UserController) Read(c *gin.Context)   { /* ... */ }
func (uc *UserController) Update(c *gin.Context) { /* ... */ }
func (uc *UserController) Delete(c *gin.Context) { /* ... */ }
func (uc *UserController) List(c *gin.Context)   { /* ... */ }
func (uc *UserController) Search(c *gin.Context) { /* ... */ }

// Generate REST routes
userRoutes := app.Resource("User", &UserController{}).
    WithModel(CreateUserRequest{}, UserResponse{}, UserSearchRequest{}).
    WithTags("api", "v1").
    WithMiddleware(authMiddleware).
    // Add custom routes
    Member("activate", "POST", "/activate", activateHandler).
    Collection("export", "GET", "/export", exportHandler).
    Build()

This generates:

  • GET /users → List users
  • POST /users → Create user
  • GET /users/:id → Get user
  • PUT /users/:id → Update user
  • DELETE /users/:id → Delete user
  • GET /users/search → Search users
  • POST /users/:id/activate → Custom member route
  • GET /users/export → Custom collection route

📦 Input/Output Validation

Automatic validation using struct tags:

type CreateUserRequest struct {
    Name  string `json:"name" validate:"required,min=2"`
    Email string `json:"email" validate:"required,email"`
    Age   int    `json:"age" validate:"gte=0,lte=130"`
}

app.Named("create_user").
    POST("/users").
    WithInput(CreateUserRequest{}).  // Automatic validation
    Handler(func(c *gin.Context) {
        // Input is pre-validated and available
        if input, exists := supergin.GetValidatedInput(c); exists {
            req := input.(*CreateUserRequest)
            // req is guaranteed to be valid
        }
    })

📛 Named Routes & URL Generation

// Define named routes
app.Named("show_user").GET("/users/:id").Handler(handler)

// Generate URLs
url, _ := app.URLFor("show_user", "id", "123")
// Returns: "/users/123"

// Access route metadata
route, exists := app.GetRoute("show_user")
if exists {
    fmt.Printf("Route: %s %s", route.Method, route.Path)
}

📄 API Documentation

Built-in documentation endpoint:

# View all routes and DI services
curl http://localhost:8080/docs

# Returns:
{
  "routes": {
    "create_user": {
      "method": "POST",
      "path": "/users",
      "description": "Create a new user",
      "tags": ["users", "create"]
    }
  },
  "di_services": {
    "userService": {
      "type": "UserService",
      "scope": "request",
      "dependencies": ["userRepository"]
    }
  }
}

🧪 Testing

SuperGin makes testing easy with route registry and DI:

func TestUserRoutes(t *testing.T) {
    app := supergin.New()
    
    // Setup test routes
    setupRoutes(app)
    
    // Verify routes exist
    assert.True(t, app.HasRoute("create_user"))
    
    // Test route metadata
    route, _ := app.GetRoute("create_user")
    assert.Equal(t, "POST", route.Method)
    assert.Equal(t, "/users", route.Path)
    
    // Test DI services
    services := app.DI().ListServices()
    assert.Contains(t, services, "userService")
}

🔧 Configuration

app := supergin.New(supergin.Config{
    EnableDocs:     true,          // Enable /docs endpoint
    ValidateInput:  true,          // Enable input validation
    ValidateOutput: false,         // Enable output validation
    DocsPath:       "/api/docs",   // Custom docs path
})

📂 Project Structure

github.com/supergin/supergin/
├── go.mod                 # Go module definition
├── supergin.go           # Main engine and core types
├── route_builder.go      # Fluent route building API
├── di.go                 # Dependency injection system
├── resource.go           # Rails-like REST resources
├── errors.go             # Error types and handling
├── examples/
│   └── basic/
│       └── main.go       # Complete working example
├── Makefile              # Build and development tasks
└── README.md             # This file

🛠️ Development

# Run basic example
make run-example

# Run tests
make test

# Format and lint
make fmt vet

# Build for release
make build-release

# Create new project
make init-project

📚 Examples

See the examples/basic/main.go for a complete working application demonstrating:

  • ✅ Dependency injection setup
  • ✅ REST resource generation
  • ✅ Custom routes and middleware
  • ✅ Input/output validation
  • ✅ Route introspection
  • ✅ Error handling

🤝 Contributing

Contributions welcome! Please feel free to submit a Pull Request.

📄 License

This project is licensed under the MIT License - see the LICENSE file for details.

🙏 Acknowledgments

  • Built on top of the excellent Gin framework
  • Inspired by Rails conventions and Django patterns
  • Validation powered by go-playground/validator

SuperGin - Making Go web development more productive! 🚀

Documentation

Overview

Package supergin provides an enhanced Gin framework with named routes, input/output validation, dependency injection, and Rails-like REST resources.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Get

func Get(name string) interface{}

func GetFromContext

func GetFromContext(ctx context.Context, name string) interface{}

func GetFromContextT

func GetFromContextT[T any](ctx context.Context, name string) T

GetFromContextT returns a typed service instance with context

func GetT

func GetT[T any](name string) T

GetT returns a typed service instance

func GetValidatedInput

func GetValidatedInput(c *gin.Context) (interface{}, bool)

GetValidatedInput retrieves validated input from context

func IsErrorCode

func IsErrorCode(err error, code ErrorCode) bool

IsErrorCode checks if an error is a SuperGin error with specific code

func Resolve

func Resolve[T any](name string) T

Service resolver that works without context in handlers

Types

type CRUDController

type CRUDController interface {
	Create(c *gin.Context)
	Read(c *gin.Context)
	Update(c *gin.Context)
	Delete(c *gin.Context)
	List(c *gin.Context)
	Search(c *gin.Context)
}

CRUDController interface for REST operations

type Config

type Config struct {
	EnableDocs     bool
	ValidateInput  bool
	ValidateOutput bool
	DocsPath       string
}

Config holds configuration for SuperGin

type CustomRoute

type CustomRoute struct {
	Method      string
	Path        string
	Handler     gin.HandlerFunc
	Name        string
	Description string
	InputType   reflect.Type
	OutputType  reflect.Type
}

CustomRoute defines additional routes for a model

type DIContainer

type DIContainer struct {
	// contains filtered or unexported fields
}

DIContainer manages dependency injection

func GetDI

func GetDI() *DIContainer

GetDI returns the global DI container

func Register

func Register(name string, factory interface{}, scope DIScope, dependencies ...string) *DIContainer

Global convenience functions

func RegisterInstance

func RegisterInstance(name string, instance interface{}) *DIContainer

func RegisterRequest

func RegisterRequest(name string, factory interface{}, dependencies ...string) *DIContainer

func RegisterSingleton

func RegisterSingleton(name string, factory interface{}, dependencies ...string) *DIContainer

func RegisterTransient

func RegisterTransient(name string, factory interface{}, dependencies ...string) *DIContainer

func (*DIContainer) Get

func (di *DIContainer) Get(name string) interface{}

Get resolves and returns a service instance

func (*DIContainer) GetFromContext

func (di *DIContainer) GetFromContext(ctx context.Context, name string) interface{}

GetFromContext resolves a service with request context

func (*DIContainer) ListServices

func (di *DIContainer) ListServices() map[string]*ServiceDefinition

ListServices returns all registered services

func (*DIContainer) Middleware

func (di *DIContainer) Middleware() gin.HandlerFunc

Middleware for DI integration

func (*DIContainer) Register

func (di *DIContainer) Register(name string, factory interface{}, scope DIScope, dependencies ...string) *DIContainer

Register registers a service with the DI container

func (*DIContainer) RegisterInstance

func (di *DIContainer) RegisterInstance(name string, instance interface{}) *DIContainer

RegisterInstance registers a pre-created instance as a singleton

func (*DIContainer) RegisterRequest

func (di *DIContainer) RegisterRequest(name string, factory interface{}, dependencies ...string) *DIContainer

RegisterRequest registers a request-scoped service

func (*DIContainer) RegisterSingleton

func (di *DIContainer) RegisterSingleton(name string, factory interface{}, dependencies ...string) *DIContainer

RegisterSingleton registers a singleton service

func (*DIContainer) RegisterTransient

func (di *DIContainer) RegisterTransient(name string, factory interface{}, dependencies ...string) *DIContainer

RegisterTransient registers a transient service

type DIScope

type DIScope string

DIScope defines the lifecycle of a service

const (
	ScopeSingleton DIScope = "singleton" // One instance for entire app
	ScopeRequest   DIScope = "request"   // One instance per HTTP request
	ScopeTransient DIScope = "transient" // New instance every time
)

type DefaultWebSocketHandler

type DefaultWebSocketHandler struct {
	OnConnectFunc    func(conn *WebSocketConnection)
	OnDisconnectFunc func(conn *WebSocketConnection)
	OnMessageFunc    func(conn *WebSocketConnection, messageType string, data interface{})
	OnErrorFunc      func(conn *WebSocketConnection, err error)
}

Default WebSocket handler implementation

func (*DefaultWebSocketHandler) OnConnect

func (h *DefaultWebSocketHandler) OnConnect(conn *WebSocketConnection)

func (*DefaultWebSocketHandler) OnDisconnect

func (h *DefaultWebSocketHandler) OnDisconnect(conn *WebSocketConnection)

func (*DefaultWebSocketHandler) OnError

func (h *DefaultWebSocketHandler) OnError(conn *WebSocketConnection, err error)

func (*DefaultWebSocketHandler) OnMessage

func (h *DefaultWebSocketHandler) OnMessage(conn *WebSocketConnection, messageType string, data interface{})

type Engine

type Engine struct {
	*gin.Engine
	// contains filtered or unexported fields
}

Engine wraps gin.Engine with enhanced capabilities

func New

func New(config ...Config) *Engine

New creates a new SuperGin engine

func (*Engine) BidirectionalGrpcHttp

func (e *Engine) BidirectionalGrpcHttp(name string, httpPath string, grpcService string, grpcMethod string,
	httpInput, httpOutput, grpcInput, grpcOutput interface{}) error

Helper function to register both HTTP and gRPC endpoints

func (*Engine) DI

func (e *Engine) DI() *DIContainer

DI returns the dependency injection container

func (*Engine) GetRoute

func (e *Engine) GetRoute(name string) (*RouteInfo, bool)

GetRoute returns route information by name

func (*Engine) GetRoutes

func (e *Engine) GetRoutes() map[string]*RouteInfo

GetRoutes returns all registered routes

func (*Engine) GetRoutesByTag

func (e *Engine) GetRoutesByTag(tag string) []*RouteInfo

GetRoutesByTag returns routes filtered by tag

func (*Engine) GrpcBridge

func (e *Engine) GrpcBridge() *GrpcBridge

Engine extension for gRPC bridge

func (*Engine) Named

func (e *Engine) Named(name string) *RouteBuilder

Named creates a new route builder with a name

func (*Engine) Resource

func (e *Engine) Resource(name string, controller CRUDController) *ResourceBuilder

Resource creates a new resource builder for a model

func (*Engine) URLFor

func (e *Engine) URLFor(name string, params ...interface{}) (string, error)

URLFor generates URL for a named route with parameters

func (*Engine) WebSocket

func (e *Engine) WebSocket(name, path string, handler WebSocketHandler) *WebSocketHub

Engine extension for WebSocket support

type ErrorCode

type ErrorCode string

ErrorCode represents different types of SuperGin errors

const (
	ErrRouteNotFound      ErrorCode = "ROUTE_NOT_FOUND"
	ErrValidationFailed   ErrorCode = "VALIDATION_FAILED"
	ErrDIServiceNotFound  ErrorCode = "DI_SERVICE_NOT_FOUND"
	ErrCircularDependency ErrorCode = "CIRCULAR_DEPENDENCY"
	ErrInvalidFactory     ErrorCode = "INVALID_FACTORY"
	ErrContextRequired    ErrorCode = "CONTEXT_REQUIRED"
)

type GrpcBridge

type GrpcBridge struct {
	// contains filtered or unexported fields
}

GrpcBridge manages HTTP to gRPC conversions

func NewGrpcBridge

func NewGrpcBridge(engine *Engine) *GrpcBridge

NewGrpcBridge creates a new gRPC bridge

func (*GrpcBridge) CreateGrpcToHttpProxy

func (gb *GrpcBridge) CreateGrpcToHttpProxy(serviceName, methodName string, httpEndpoint string) gin.HandlerFunc

Reverse proxy: gRPC to HTTP

func (*GrpcBridge) RegisterGrpcMethod

func (gb *GrpcBridge) RegisterGrpcMethod(serviceName, methodName string,
	httpInputType, httpOutputType, grpcInputType, grpcOutputType interface{}) error

RegisterGrpcMethod registers a gRPC method with type mappings

func (*GrpcBridge) RegisterGrpcService

func (gb *GrpcBridge) RegisterGrpcService(name, address, serviceName string) error

RegisterGrpcService registers a gRPC service for HTTP bridging

type GrpcConverter

type GrpcConverter interface {
	ToGrpc() (proto.Message, error)
	FromGrpc(proto.Message) error
}

GrpcConverter interface for types that can convert to/from gRPC

type GrpcMethod

type GrpcMethod struct {
	Name            string
	FullName        string
	InputType       reflect.Type
	OutputType      reflect.Type
	GrpcInputType   reflect.Type
	GrpcOutputType  reflect.Type
	StreamingInput  bool
	StreamingOutput bool
}

GrpcMethod represents a gRPC method configuration

type GrpcService

type GrpcService struct {
	Name        string
	Address     string
	ServiceName string
	Methods     map[string]*GrpcMethod
	Connection  *grpc.ClientConn
}

GrpcService represents a gRPC service configuration

type InputOutput

type InputOutput struct {
	Input  interface{}
	Output interface{}
}

InputOutput defines the container for request/response validation

type ModelInfo

type ModelInfo struct {
	Name         string
	PluralName   string
	BasePath     string
	Controller   CRUDController
	InputType    reflect.Type
	OutputType   reflect.Type
	SearchType   reflect.Type
	Middleware   []gin.HandlerFunc
	Tags         []string
	Metadata     map[string]interface{}
	CustomRoutes map[string]CustomRoute
}

ModelInfo holds information about a model for route generation

type RequestScope

type RequestScope struct {
	// contains filtered or unexported fields
}

RequestScope holds request-scoped dependencies

type ResourceBuilder

type ResourceBuilder struct {
	// contains filtered or unexported fields
}

ResourceBuilder provides Rails-like resource routing

func (*ResourceBuilder) Build

func (rb *ResourceBuilder) Build() *RestRoutes

Build generates all the REST routes and custom routes

func (*ResourceBuilder) Collection

func (rb *ResourceBuilder) Collection(name, method, path string, handler gin.HandlerFunc) *ResourceBuilder

Collection adds a custom collection route (operates on the collection)

func (*ResourceBuilder) Except

func (rb *ResourceBuilder) Except(actions ...string) *ResourceBuilder

Except excludes specific REST actions from generation

func (*ResourceBuilder) Member

func (rb *ResourceBuilder) Member(name, method, path string, handler gin.HandlerFunc) *ResourceBuilder

Member adds a custom member route (operates on a single resource)

func (*ResourceBuilder) Only

func (rb *ResourceBuilder) Only(actions ...string) *ResourceBuilder

Only restricts which REST actions to generate

func (*ResourceBuilder) WithBasePath

func (rb *ResourceBuilder) WithBasePath(path string) *ResourceBuilder

WithBasePath sets a custom base path for the resource

func (*ResourceBuilder) WithMetadata

func (rb *ResourceBuilder) WithMetadata(key string, value interface{}) *ResourceBuilder

WithMetadata adds metadata to all resource routes

func (*ResourceBuilder) WithMiddleware

func (rb *ResourceBuilder) WithMiddleware(middleware ...gin.HandlerFunc) *ResourceBuilder

WithMiddleware adds middleware to all resource routes

func (*ResourceBuilder) WithModel

func (rb *ResourceBuilder) WithModel(input, output, search interface{}) *ResourceBuilder

WithModel attaches model types to the resource

func (*ResourceBuilder) WithTags

func (rb *ResourceBuilder) WithTags(tags ...string) *ResourceBuilder

WithTags adds tags to all resource routes

type RestRoutes

type RestRoutes struct {
	Create string
	Read   string
	Update string
	Delete string
	List   string
	Search string
}

RestRoutes holds the generated REST route names

type RouteBuilder

type RouteBuilder struct {
	// contains filtered or unexported fields
}

RouteBuilder provides a fluent interface for building routes

func (*RouteBuilder) DELETE

func (rb *RouteBuilder) DELETE(path string) *RouteBuilder

DELETE sets the HTTP method to DELETE

func (*RouteBuilder) GET

func (rb *RouteBuilder) GET(path string) *RouteBuilder

GET sets the HTTP method to GET

func (*RouteBuilder) Handler

func (rb *RouteBuilder) Handler(handler gin.HandlerFunc) *RouteBuilder

Handler sets the handler function and registers the route

func (*RouteBuilder) HandlerFunc

func (rb *RouteBuilder) HandlerFunc(handler gin.HandlerFunc) *RouteBuilder

HandlerFunc is an alias for Handler for convenience

func (*RouteBuilder) PATCH

func (rb *RouteBuilder) PATCH(path string) *RouteBuilder

PATCH sets the HTTP method to PATCH

func (*RouteBuilder) POST

func (rb *RouteBuilder) POST(path string) *RouteBuilder

POST sets the HTTP method to POST

func (*RouteBuilder) PUT

func (rb *RouteBuilder) PUT(path string) *RouteBuilder

PUT sets the HTTP method to PUT

func (*RouteBuilder) WebSocket

func (rb *RouteBuilder) WebSocket(path string, handler WebSocketHandler) *RouteBuilder

WebSocket route builder extension

func (*RouteBuilder) WithDescription

func (rb *RouteBuilder) WithDescription(desc string) *RouteBuilder

WithDescription adds a description to the route

func (*RouteBuilder) WithGrpcBridge

func (rb *RouteBuilder) WithGrpcBridge(serviceName, methodName string) *RouteBuilder

Route builder extension for gRPC bridging

func (*RouteBuilder) WithIO

func (rb *RouteBuilder) WithIO(input, output interface{}) *RouteBuilder

WithIO sets input and output types for validation

func (*RouteBuilder) WithInput

func (rb *RouteBuilder) WithInput(input interface{}) *RouteBuilder

WithInput sets only the input type for validation

func (*RouteBuilder) WithMetadata

func (rb *RouteBuilder) WithMetadata(key string, value interface{}) *RouteBuilder

WithMetadata adds metadata to the route

func (*RouteBuilder) WithMiddleware

func (rb *RouteBuilder) WithMiddleware(middleware ...gin.HandlerFunc) *RouteBuilder

WithMiddleware adds middleware to the route

func (*RouteBuilder) WithOutput

func (rb *RouteBuilder) WithOutput(output interface{}) *RouteBuilder

WithOutput sets only the output type for validation

func (*RouteBuilder) WithTags

func (rb *RouteBuilder) WithTags(tags ...string) *RouteBuilder

WithTags adds tags to the route

type RouteInfo

type RouteInfo struct {
	Name        string                 `json:"name"`
	Method      string                 `json:"method"`
	Path        string                 `json:"path"`
	Handler     gin.HandlerFunc        `json:"-"`
	InputType   reflect.Type           `json:"-"`
	OutputType  reflect.Type           `json:"-"`
	Metadata    map[string]interface{} `json:"metadata"`
	Description string                 `json:"description"`
	Tags        []string               `json:"tags"`
	CreatedAt   time.Time              `json:"created_at"`
}

RouteInfo holds metadata about a route

type ServiceDefinition

type ServiceDefinition struct {
	Name         string                 `json:"name"`
	Type         reflect.Type           `json:"-"`
	Scope        DIScope                `json:"scope"`
	Factory      interface{}            `json:"-"`
	Dependencies []string               `json:"dependencies"`
	Singleton    interface{}            `json:"-"`
	Metadata     map[string]interface{} `json:"metadata"`
}

ServiceDefinition defines how to create and manage a service

type SuperGinError

type SuperGinError struct {
	Code    ErrorCode
	Message string
	Cause   error
}

SuperGinError represents an error within the SuperGin framework

func NewSuperGinError

func NewSuperGinError(code ErrorCode, message string, args ...interface{}) *SuperGinError

NewSuperGinError creates a new SuperGin error

func NewSuperGinErrorWithCause

func NewSuperGinErrorWithCause(code ErrorCode, cause error, message string, args ...interface{}) *SuperGinError

NewSuperGinErrorWithCause creates a new SuperGin error with a cause

func (*SuperGinError) Error

func (e *SuperGinError) Error() string

Error implements the error interface

func (*SuperGinError) Unwrap

func (e *SuperGinError) Unwrap() error

Unwrap returns the underlying cause

type WebSocketConfig

type WebSocketConfig struct {
	ReadBufferSize    int
	WriteBufferSize   int
	CheckOrigin       func(r *http.Request) bool
	EnableCompression bool
	HandshakeTimeout  time.Duration
	ReadTimeout       time.Duration
	WriteTimeout      time.Duration
	PingInterval      time.Duration
}

WebSocketConfig holds WebSocket configuration

type WebSocketConnection

type WebSocketConnection struct {
	ID       string
	Conn     *websocket.Conn
	Send     chan []byte
	Hub      *WebSocketHub
	User     interface{} // User context/session data
	Metadata map[string]interface{}
	// contains filtered or unexported fields
}

WebSocketConnection represents a WebSocket connection with metadata

func (*WebSocketConnection) Close

func (conn *WebSocketConnection) Close()

Close closes the WebSocket connection

func (*WebSocketConnection) GetMetadata

func (conn *WebSocketConnection) GetMetadata(key string) (interface{}, bool)

GetMetadata gets metadata for this connection

func (*WebSocketConnection) Send

func (conn *WebSocketConnection) Send(messageType string, data interface{}) error

Send sends a message through this connection

func (*WebSocketConnection) SetMetadata

func (conn *WebSocketConnection) SetMetadata(key string, value interface{})

SetMetadata sets metadata for this connection

type WebSocketHandler

type WebSocketHandler interface {
	OnConnect(conn *WebSocketConnection)
	OnDisconnect(conn *WebSocketConnection)
	OnMessage(conn *WebSocketConnection, messageType string, data interface{})
	OnError(conn *WebSocketConnection, err error)
}

WebSocketHandler defines the interface for WebSocket event handlers

type WebSocketHub

type WebSocketHub struct {
	// contains filtered or unexported fields
}

WebSocketHub manages all WebSocket connections

func NewWebSocketHub

func NewWebSocketHub(handler WebSocketHandler) *WebSocketHub

NewWebSocketHub creates a new WebSocket hub

func (*WebSocketHub) Broadcast

func (h *WebSocketHub) Broadcast(messageType string, data interface{}) error

Broadcast sends a message to all connected clients

func (*WebSocketHub) GetConnections

func (h *WebSocketHub) GetConnections() map[string]*WebSocketConnection

GetConnections returns all active connections

func (*WebSocketHub) Run

func (h *WebSocketHub) Run()

Run starts the WebSocket hub

func (*WebSocketHub) SendToConnection

func (h *WebSocketHub) SendToConnection(connID string, messageType string, data interface{}) error

SendToConnection sends a message to a specific connection

type WebSocketMessage

type WebSocketMessage struct {
	Type      string      `json:"type"`
	Data      interface{} `json:"data"`
	Timestamp time.Time   `json:"timestamp"`
	ID        string      `json:"id,omitempty"`
}

WebSocketMessage represents a structured WebSocket message

Directories

Path Synopsis
advanced command

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL