FunctionsCore

Server Functions

Core utility functions for creating servers and handling HTTP requests in Squirrel Framework.

SpawnServer()

Creates and returns a new SqurlMux instance for handling HTTP requests.

func SpawnServer() *SqurlMux

NewResponse()

Creates a new Response instance from a network connection.

func NewResponse(conn *net.Conn) *Response

ParseRequest()

Parses an HTTP request from a network connection.

func ParseRequest(conn *net.Conn) (*Request, error)

Complete Server Example

A comprehensive example using all core functions together.

package main

import (
    "fmt"
    "log"
    "net"
    "time"
    "github.com/useranonymous001/squirrel"
    "github.com/useranonymous001/squirrel/middlewares"
)

func main() {
    // Create server using SpawnServer()
    server := SpawnServer()
    
    // Add middleware
    server.Use(middlewares.Logger)
    server.Use(customMiddleware)
    
    // Add routes
    setupRoutes(server)
    
    // Start server
    fmt.Println("Server starting on :8080")
    server.Listen(":8080")
}

func setupRoutes(server *SqurlMux) {
    // Home route
    server.Get("/", homeHandler)
    
    // API routes
    server.Get("/api/status", statusHandler)
    server.Post("/api/echo", echoHandler)
    server.Get("/api/users/:id", getUserHandler)
    
    // Static files
    server.ServeStatic("/static", "public")
    
    // Custom protocol endpoint
    server.Get("/custom", customProtocolHandler)
}

func homeHandler(req *Request, res *Response) {
    html := `<!DOCTYPE html>
<html>
<head><title>Squirrel Server</title></head>
<body>
    <h1>Welcome to Squirrel Framework!</h1>
    <p>Server is running successfully.</p>
    <ul>
        <li><a href="/api/status">Server Status</a></li>
        <li><a href="/api/users/123">User Example</a></li>
        <li><a href="/static/index.html">Static Files</a></li>
    </ul>
</body>
</html>`
    
    res.SetHeader("Content-Type", "text/html")
    res.Write(html)
    res.Send()
}

func statusHandler(req *Request, res *Response) {
    status := map[string]interface{}{
        "server": "Squirrel Framework",
        "version": "1.0.0",
        "timestamp": time.Now().Unix(),
        "uptime": "24h",
        "status": "healthy",
    }
    
    res.JSON(status)
    res.Send()
}

func echoHandler(req *Request, res *Response) {
    body, err := req.ReadBodyAsString()
    if err != nil {
        res.SetStatus(400)
        res.JSON(map[string]string{"error": "Failed to read body"})
        res.Send()
        return
    }
    
    response := map[string]interface{}{
        "method": req.Method,
        "path": req.Path,
        "headers": req.Headers,
        "body": body,
        "timestamp": time.Now().Format(time.RFC3339),
    }
    
    res.JSON(response)
    res.Send()
}

func getUserHandler(req *Request, res *Response) {
    userID := req.Param("id")
    
    user := map[string]interface{}{
        "id": userID,
        "name": "John Doe",
        "email": "john@example.com",
        "created": time.Now().AddDate(-1, 0, 0).Format(time.RFC3339),
    }
    
    res.JSON(user)
    res.Send()
}

func customProtocolHandler(req *Request, res *Response) {
    // Example of using lower-level functions
    // This demonstrates direct connection access
    
    res.SetHeader("X-Custom-Protocol", "Squirrel-1.0")
    res.SetStatus(200)
    res.JSON(map[string]string{
        "message": "Custom protocol response",
        "connection": "direct",
    })
    res.Send()
}

func customMiddleware(next HandlerFunc) HandlerFunc {
    return func(req *Request, res *Response) {
        start := time.Now()
        
        // Add custom headers
        res.SetHeader("X-Powered-By", "Squirrel Framework")
        res.SetHeader("X-Request-ID", fmt.Sprintf("req_%d", start.UnixNano()))
        
        // Call next handler
        next(req, res)
        
        // Log completion
        duration := time.Since(start)
        fmt.Printf("Request completed in %v\n", duration)
    }
}