Skip to content

francose/jinx_web_framework

Repository files navigation

Jynx Web Framework

**A- Authentication & Authorization: JWT tokens, role-based access control

  • High Performance: Built on native Go networking with HTTP/HTTPS support
  • Middleware System: Express.js-inspired chainable middleware
  • RESTful APIs: Clean routing with JSON/HTML response helpers
  • CORS Support: Built-in cross-origin resource sharing
  • Request Parsing: Automatic JSON body and header parsingn, Express.js-inspired web framework for Go** - Build powerful backend applications and APIs with ease!

Jynx combines the simplicity of Express.js with the performance and reliability of Go, making it perfect for building production-ready backend services, REST APIs, and web applications.

Why Choose Jynx?

Express.js-like Developer Experience

// Express.js
app.get('/api/users', (req, res) => {
    res.json({ users: users });
});

// Jynx - Same simplicity, Go power!
app.GET("/api/users", func(conn net.Conn, method, path string) {
    res := jynx.NewResponse(conn)
    res.JSON(200, map[string]interface{}{"users": users})
})

Features

  • Backend Applications: Build e-commerce, blogs, APIs, microservices
  • Authentication & Authorization: JWT tokens, role-based access control
  • High Performance: Built on native Go networking with HTTP/HTTPS support
  • Middleware System: Express.js-style chainable middleware
  • RESTful APIs: Clean routing with JSON/HTML response helpers
  • CORS Support: Built-in cross-origin resource sharing
  • Request Parsing: Automatic JSON body and header parsing -- Production Ready: Logging, recovery, graceful error handling

Real-World Backend Examples

Complete E-Commerce Backend (example_backend/)

A full-featured e-commerce API with user management, product catalog, and authentication:

cd example_backend && go run main.go
# Server starts at http://localhost:3000

# Test the API
curl -X POST http://localhost:3000/auth/login \
  -H "Content-Type: application/json" \
  -d '{"username":"admin","password":"admin123"}'

curl -X GET http://localhost:3000/api/products

Features:

  • User authentication & authorization
  • Product management with CRUD operations
  • Role-based access control (admin/customer)
  • RESTful API design
  • JWT token authentication

Blog Platform (example_blog/)

A blogging platform with post management and comment system:

cd example_blog && go run main.go  
# Server starts at http://localhost:4000

# Create a blog post
curl -X POST http://localhost:4000/api/posts \
  -H "Authorization: Bearer YOUR_JWT_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{"title":"My Post","content":"Hello World!","published":true}'

Features:

  • Create and manage blog posts
  • Comment system for reader engagement
  • Author authentication with role-based access
  • Draft/publish workflow
  • Tag-based post organization

Building Your Own Backend

Jynx makes it easy to build any type of backend application. Check out our comprehensive guide:

Backend Development Guide - Learn how to build production-ready backends with Jynx

Common Use Cases:

  • REST APIs - Build scalable web APIs
  • Microservices - Create lightweight, focused services
  • E-commerce Platforms - Product catalogs, user management, orders
  • Content Management - Blogs, documentation, media platforms
  • Social Networks - User profiles, posts, messaging
  • IoT Backends - Device management, data collection
  • Admin Dashboards - User management, analytics, reporting

Quick Start

package main

import (
    "net"
    "jynx_webserver/jynx"
)

func main() {
    app := jynx.New()

    app.GET("/", func(conn net.Conn, method, path string) {
        res := jynx.NewResponse(conn)
        res.HTML(200, "<h1>Hello Jynx!</h1>")
    })

    app.Start() // Starts both HTTP:8080 and HTTPS:8443
}

Configuration

Method 1: During initialization

app := jynx.New(jynx.Config{
    HTTPPort:  ":3000",
    HTTPSPort: ":3443",
    CertFile:  "my-cert.crt",
    KeyFile:   "my-key.key",
})

Method 2: After initialization

app := jynx.New()

// Change ports dynamically
app.SetHTTPPort(":9000")
app.SetHTTPSPort(":9443")

// Change certificate files
app.SetTLSConfig("custom.crt", "custom.key")

Method 3: Environment-based configuration

import "os"

httpPort := os.Getenv("HTTP_PORT")
if httpPort == "" {
    httpPort = ":8080" // default
}

httpsPort := os.Getenv("HTTPS_PORT") 
if httpsPort == "" {
    httpsPort = ":8443" // default
}

app := jynx.New(jynx.Config{
    HTTPPort:  httpPort,
    HTTPSPort: httpsPort,
})

Routing

// HTTP Methods
app.GET("/users", getUsersHandler)
app.POST("/users", createUserHandler)
app.PUT("/users/:id", updateUserHandler)
app.DELETE("/users/:id", deleteUserHandler)

// Custom method
app.Handle("PATCH", "/users/:id", patchUserHandler)

Middleware

Built-in Middleware

app.Use(jynx.Logger())    // Request logging
app.Use(jynx.Recovery())  // Panic recovery
app.Use(jynx.CORS())      // CORS headers

Custom Middleware

authMiddleware := func(next middleware.HandlerFunc) middleware.HandlerFunc {
    return func(conn net.Conn, method, path string) {
        // Authentication logic
        next(conn, method, path)
    }
}

app.Use(authMiddleware)

Authentication

import "jynx_webserver/auth"

// Setup authentication
provider := auth.NewMemoryProvider("secret-key", 24*time.Hour)
authConfig := &auth.Config{
    SecretKey:   "secret-key", 
    TokenExpiry: 24 * time.Hour,
    Provider:    provider,
}

authModule := auth.NewAuth(authConfig)
provider.SetAuth(authModule)

authMiddleware := auth.NewAuthMiddleware(authModule)
authHandlers := auth.NewAuthHandlers(authModule)

// Setup auth routes
app.POST("/auth/register", authHandlers.RegisterHandler)
app.POST("/auth/login", authHandlers.LoginHandler)

// Protected routes
app.Use(authMiddleware.RequireAuth())
app.GET("/profile", authHandlers.ProfileHandler)

// Role-based protection
app.Use(authMiddleware.RequireRole("admin"))
app.GET("/admin", adminHandler)

Response Helpers

func handler(conn net.Conn, method, path string) {
    res := jynx.NewResponse(conn)
    
    // JSON response
    res.JSON(200, map[string]string{"message": "success"})
    
    // HTML response
    res.HTML(200, "<h1>Hello World</h1>")
    
    // Plain text
    res.Text(200, "Hello World")
    
    // Status only
    res.Status(204)
}

Request Helpers

func handler(conn net.Conn, method, path string) {
    req := jynx.NewRequest(conn, method, path)
    
    // Parse JSON body
    var data map[string]interface{}
    req.JSON(&data)
    
    // Get headers
    contentType := req.Header("Content-Type")
    
    // Check header existence
    if req.HasHeader("Authorization") {
        // Handle auth
    }
}

Server Control

// Start both HTTP and HTTPS
app.Start()

// Start only HTTP
app.StartHTTP()

// Start only HTTPS
app.StartHTTPS()

Port Configuration

The framework provides flexible port configuration:

Available Methods:

  • SetHTTPPort(port string) - Change HTTP port dynamically
  • SetHTTPSPort(port string) - Change HTTPS port dynamically
  • Config struct - Set ports during initialization

Examples:

// Default ports (HTTP: 8080, HTTPS: 8443)
app := jynx.New()

// Custom ports during initialization
app := jynx.New(jynx.Config{
    HTTPPort:  ":3000",
    HTTPSPort: ":3443",
})

// Change ports after initialization
app.SetHTTPPort(":9000")
app.SetHTTPSPort(":9443")

// Use only specific port numbers
app.SetHTTPPort("3000")   // Works without ":"
app.SetHTTPSPort("3443")  // Works without ":"

Common Port Configurations:

// Development
HTTPPort: ":8080", HTTPSPort: ":8443"

// Production
HTTPPort: ":80", HTTPSPort: ":443"  

// Custom development
HTTPPort: ":3000", HTTPSPort: ":3443"

// Alternative ports
HTTPPort: ":9000", HTTPSPort: ":9443"

Certificate Management

// Generate self-signed certificate
app.GenerateCertificate()

// Set custom certificate
app.SetTLSConfig("path/to/cert.crt", "path/to/key.key")

Note: Certificate files (*.crt, *.key) are automatically generated and should not be committed to version control for security reasons.

Example Applications

  • example/main.go - Complete example with multiple routes, middleware, and API endpoints
  • example_ports/main.go - Port configuration example with environment variables
  • example_auth/main.go - Authentication example with JWT, roles, and protected routes

Project Structure

jynx_webserver/
├── main.go                    # Basic framework demo
├── go.mod
├── BACKEND_GUIDE.md          # Complete backend development guide
├── jynx/                     # Core framework package
│   ├── framework.go          # Main framework implementation  
│   ├── middleware.go         # Built-in middleware (Logger, CORS, Recovery)
│   ├── request.go            # HTTP request parsing utilities
│   └── response.go           # HTTP response helpers (JSON, HTML, Text)
├── auth/                     # Authentication module
│   ├── README.md             # Authentication documentation
│   ├── auth.go               # Core authentication module
│   ├── jwt.go                # JWT token implementation
│   ├── middleware.go         # Auth middleware (RequireAuth, RequireRole)
│   ├── handlers.go           # Auth HTTP handlers (login, register, profile)
│   └── memory_provider.go    # In-memory auth provider
├── example/                  # Basic framework example
│   └── main.go
├── example_auth/             # Authentication example  
│   └── main.go
├── example_ports/            # Port configuration example
│   └── main.go
├── example_backend/          # 🆕 Complete e-commerce backend
│   └── main.go               # Full REST API with auth & CRUD
├── example_blog/             # 🆕 Blog platform backend
│   └── main.go               # Blog posts, comments, author system
├── handler/                  # HTTP/HTTPS request handlers
│   ├── http_handler.go
│   └── https_handler.go  
├── server/                   # Server management
│   └── server.go             # HTTP/HTTPS server startup
├── security/
│   │   ├── module.go          # Main security module
│   │   ├── middleware.go      # Security middleware
│   │   ├── handler.go         # Secure request handlers
│   │   ├── validation.go      # Input validation (from earlier)
│   │   ├── safe_io.go        # Safe I/O operations
│   │   ├── rate_limiter.go   # Rate limiting
│   │   ├── buffer_pool.go    # Memory pool management
│   │   ├── plugin.go         # plugin to integrate module
│   │   ├── extension.go       # internal extension
│   │   ├── hook.go            # hook 
│   │   └── errors.go          # Security-specific errors
├── router/                   # Request routing
│   └── router.go             # URL pattern matching
├── middleware/               # Middleware type definitions
│   └── types.go
└── tls/                      # TLS/SSL certificate management
    └── config.go             # Certificate generation and loading

Memory Safety

  • Buffer overflow protection through bounds checking
  • Memory pool management to prevent exhaustion
  • Safe I/O operations with size limits
  • Automatic garbage collection leverage

Web Security

  • Rate limiting per IP/user
  • CSRF protection with token validation
  • XSS prevention through content sanitization
  • Request size limiting to prevent DoS
  • Timeout control for all operations
  • Security headers automatically applied

Input Validation

  • UTF-8 validation for all inputs
  • HTML sanitization to prevent XSS
  • SQL injection prevention through pattern detection
  • Email and URL validation utilities

License

MIT License

About

A modern, Express.js-inspired web framework for Go that makes building backend applications and REST APIs simple and powerful.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors