Documentation

Getting Started

Learn how to build high-performance web applications with go-wolf. From installation to advanced features, we've got you covered.

Install go-wolf

Add go-wolf to your Go project using go get

Create your app

Initialize a new Wolf instance and define your routes

Add middleware

Use built-in middleware or create custom ones

Start building

Run your server and start building amazing applications

Installation

Get started with go-wolf in your Go project

Installation
go mod init myproject
go get github.com/aliwert/go-wolf

Basic Application

Create your first go-wolf application

Basic Application
package main

import (
    "log"
    "github.com/aliwert/go-wolf"
)

func main() {
    // Create new Wolf instance
    app := wolf.New()
    
    // Add global middleware
    app.Use(wolf.Logger())
    app.Use(wolf.Recovery())
    
    // Define routes
    app.Get("/", func(c *wolf.Context) error {
        return c.JSON(200, wolf.Map{
            "message": "Hello, go-wolf!",
            "version": "1.0.0",
        })
    })
    
    app.Get("/users/:id", func(c *wolf.Context) error {
        id := c.Param("id")
        return c.JSON(200, wolf.Map{
            "user_id": id,
            "message": "User details",
        })
    })
    
    // Start server
    log.Fatal(app.Listen(":3000"))
}

Routing

Define routes with parameters, groups, and wildcards

Routing
// HTTP Methods
app.Get("/users", getUsersHandler)
app.Post("/users", createUserHandler)
app.Put("/users/:id", updateUserHandler)
app.Delete("/users/:id", deleteUserHandler)

// Route Groups
api := app.Group("/api")
{
    v1 := api.Group("/v1")
    v1.Use(authMiddleware) // Group middleware
    {
        v1.Get("/profile", getProfileHandler)
        v1.Put("/profile", updateProfileHandler)
    }
    
    v2 := api.Group("/v2")
    {
        v2.Get("/profile", getProfileV2Handler)
    }
}

// Wildcard Routes
app.Get("/static/*filepath", staticFileHandler)

// Parameter Constraints
app.Get("/users/:id[0-9]+", getUserByIDHandler) // Only numbers

Context API

Use the rich context API for request/response handling

Context API
func userHandler(c *wolf.Context) error {
    // Path parameters
    id := c.Param("id")
    
    // Query parameters
    page := c.Query("page", "1")           // With default
    limit := c.QueryInt("limit", 10)       // Convert to int
    search := c.Query("search")            // Optional
    
    // Headers
    auth := c.Header("Authorization")
    userAgent := c.Header("User-Agent")
    
    // Request binding
    var req CreateUserRequest
    if err := c.BindJSON(&req); err != nil {
        return c.JSON(400, wolf.Map{"error": "Invalid JSON"})
    }
    
    // Validation
    if err := c.Validate(&req); err != nil {
        return c.JSON(400, wolf.Map{"error": err.Error()})
    }
    
    // Store data in context
    c.Set("user_id", id)
    c.Set("request_time", time.Now())
    
    // Response helpers
    return c.JSON(200, wolf.Map{
        "id": id,
        "page": page,
        "limit": limit,
        "data": req,
    })
}

Middleware

Built-in and custom middleware for your applications

Middleware
// Built-in Middleware
app.Use(wolf.Logger())                    // Request logging
app.Use(wolf.Recovery())                  // Panic recovery
app.Use(wolf.CORS())                     // CORS headers
app.Use(wolf.Compress())                 // Gzip compression
app.Use(wolf.RateLimit(100, time.Minute)) // Rate limiting
app.Use(wolf.RequestID())                // Request ID

// Custom Middleware
func CustomMiddleware() wolf.HandlerFunc {
    return func(c *wolf.Context) error {
        // Before request
        start := time.Now()
        
        // Process request
        err := c.Next()
        
        // After request
        duration := time.Since(start)
        log.Printf("Request took %v", duration)
        
        return err
    }
}

// Conditional middleware
app.Use(func(c *wolf.Context) error {
    if strings.HasPrefix(c.Path(), "/api/") {
        return authMiddleware(c)
    }
    return c.Next()
})

Error Handling

Comprehensive error handling and custom error types

Error Handling
// Global error handler
app.ErrorHandler = func(c *wolf.Context, err error) error {
    // Handle different error types
    switch e := err.(type) {
    case *wolf.HTTPError:
        return c.JSON(e.Code, wolf.Map{
            "error": e.Message,
            "code": e.Code,
        })
    case *validator.ValidationErrors:
        return c.JSON(400, wolf.Map{
            "error": "Validation failed",
            "details": formatValidationErrors(e),
        })
    default:
        // Log internal errors
        log.Printf("Internal error: %v", err)
        return c.JSON(500, wolf.Map{
            "error": "Internal server error",
        })
    }
}

// Custom error types
func handler(c *wolf.Context) error {
    user, err := getUserByID(c.Param("id"))
    if err != nil {
        if err == ErrUserNotFound {
            return wolf.NewHTTPError(404, "User not found")
        }
        return err // Will be handled by global handler
    }
    
    return c.JSON(200, user)
}

// Abort with error
func authMiddleware(c *wolf.Context) error {
    token := c.Header("Authorization")
    if token == "" {
        return c.Abort(401, "Authorization header required")
    }
    
    if !isValidToken(token) {
        return c.Abort(403, "Invalid token")
    }
    
    return c.Next()
}

What's Next?

Now that you have the basics, explore more advanced features and examples.

Advanced Features

Explore advanced routing, middleware patterns, and performance optimization.

View Features

Code Examples

See real-world examples and learn best practices for building applications.

View Examples

GitHub Repository

Check out the source code, contribute, and report issues on GitHub.

Star on GitHub