example/

directory
v1.8.3 Latest Latest
Warning

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

Go to latest
Published: Mar 10, 2026 License: MIT

README ΒΆ

DotWeb Examples

This directory contains examples demonstrating DotWeb features.

Quick Start (5 minutes)

cd quickstart
go run main.go
# Visit http://localhost:8080

Examples Index

πŸš€ Getting Started
Example Description Complexity
quickstart Minimal "Hello World" β˜…β˜†β˜†
routing Route patterns, params, groups β˜…β˜…β˜†
group Route grouping with 404 handlers β˜…β˜…β˜†
πŸ”§ Core Features
Example Description Complexity
middleware Logging, auth, CORS β˜…β˜…β˜†
session Session management β˜…β˜…β˜†
bind Data binding (form, JSON) β˜…β˜…β˜†
config Configuration files β˜…β˜…β˜†
router Advanced routing β˜…β˜…β˜†
🌐 Web Features
Example Description Complexity
json-api RESTful API with CRUD β˜…β˜…β˜†
file-upload File upload/download β˜…β˜…β˜†
websocket WebSocket (echo, chat) β˜…β˜…β˜…
πŸ§ͺ Testing
Example Description Complexity
mock Mock mode for testing β˜…β˜…β˜†

Feature Examples

1. Basic Routing
app.HttpServer.GET("/", handler)
app.HttpServer.POST("/users", handler)
app.HttpServer.PUT("/users/:id", handler)
app.HttpServer.DELETE("/users/:id", handler)
2. Route Parameters
// Path parameter
app.HttpServer.GET("/users/:id", func(ctx dotweb.Context) error {
    id := ctx.GetRouterName("id")
    return ctx.WriteString("User ID: " + id)
})

// Wildcard
app.HttpServer.GET("/files/*filepath", func(ctx dotweb.Context) error {
    path := ctx.GetRouterName("filepath")
    return ctx.WriteString("File: " + path)
})
3. Route Groups
api := app.HttpServer.Group("/api")
api.GET("/users", listUsers)
api.POST("/users", createUser)
api.GET("/health", healthCheck)

// Group-level 404 handler
api.SetNotFoundHandle(func(ctx dotweb.Context) error {
    return ctx.WriteString(`{"error": "API endpoint not found"}`)
})
4. Middleware
app.HttpServer.Use(func(ctx dotweb.Context) error {
    // Before handler
    ctx.Items().Set("startTime", time.Now())
    
    err := ctx.NextHandler()  // Call next handler
    
    // After handler
    duration := time.Since(ctx.Items().Get("startTime").(time.Time))
    log.Printf("Request took %v", duration)
    
    return err
})
5. Session
app.HttpServer.SetEnabledSession(true)
app.HttpServer.SetSessionConfig(session.NewDefaultRuntimeConfig())

app.HttpServer.GET("/login", func(ctx dotweb.Context) error {
    ctx.SetSession("user", "admin")
    return ctx.WriteString("Logged in!")
})
6. Data Binding
type User struct {
    Name string `json:"name" form:"name"`
    Age  int    `json:"age" form:"age"`
}

app.HttpServer.POST("/users", func(ctx dotweb.Context) error {
    user := new(User)
    if err := ctx.Bind(user); err != nil {
        return err
    }
    return ctx.WriteString(fmt.Sprintf("Created: %s", user.Name))
})
7. JSON API
app.HttpServer.GET("/api/users", func(ctx dotweb.Context) error {
    ctx.Response().Header().Set("Content-Type", "application/json")
    return ctx.WriteString(`{"users": ["Alice", "Bob"]}`)
})

// Or use WriteJsonC
app.HttpServer.GET("/api/user", func(ctx dotweb.Context) error {
    return ctx.WriteJsonC(200, map[string]string{
        "name": "Alice",
        "email": "[email protected]",
    })
})
8. File Upload
app.HttpServer.POST("/upload", func(ctx dotweb.Context) error {
    file, header, err := ctx.Request().FormFile("file")
    if err != nil {
        return err
    }
    defer file.Close()
    
    // Save file...
    return ctx.WriteString("Uploaded: " + header.Filename)
})
9. WebSocket
app.HttpServer.GET("/ws", func(ctx dotweb.Context) error {
    if !ctx.IsWebSocket() {
        return ctx.WriteString("Requires WebSocket")
    }
    
    ws := ctx.WebSocket()
    
    for {
        msg, err := ws.ReadMessage()
        if err != nil {
            break
        }
        ws.SendMessage("Echo: " + msg)
    }
    
    return nil
})
10. Error Handling
app.SetExceptionHandle(func(ctx dotweb.Context, err error) {
    ctx.Response().SetContentType(dotweb.MIMEApplicationJSONCharsetUTF8)
    ctx.WriteJsonC(500, map[string]string{"error": err.Error()})
})

app.SetNotFoundHandle(func(ctx dotweb.Context) {
    ctx.Response().SetContentType(dotweb.MIMEApplicationJSONCharsetUTF8)
    ctx.WriteJsonC(404, map[string]string{"error": "Not found"})
})

Running Examples

# Run any example
cd example/session
go run main.go

# With hot reload (using air)
air

Project Structure

For larger projects, consider this structure:

myapp/
β”œβ”€β”€ main.go
β”œβ”€β”€ config/
β”‚   └── config.yaml
β”œβ”€β”€ handlers/
β”‚   β”œβ”€β”€ user.go
β”‚   └── auth.go
β”œβ”€β”€ middleware/
β”‚   β”œβ”€β”€ auth.go
β”‚   └── logger.go
β”œβ”€β”€ models/
β”‚   └── user.go
└── routes/
    └── routes.go

Testing

# Run all tests
go test ./...

# With coverage
go test ./... -coverprofile=coverage.out
go tool cover -html=coverage.out

Documentation

Support

Directories ΒΆ

Path Synopsis
Package main demonstrates file upload and download in DotWeb.
Package main demonstrates file upload and download in DotWeb.
Package main demonstrates RESTful JSON API in DotWeb.
Package main demonstrates RESTful JSON API in DotWeb.
Package main demonstrates the simplest DotWeb application.
Package main demonstrates the simplest DotWeb application.
Package main demonstrates routing patterns in DotWeb.
Package main demonstrates routing patterns in DotWeb.
Package main demonstrates session management in DotWeb.
Package main demonstrates session management in DotWeb.
Package main demonstrates WebSocket in DotWeb.
Package main demonstrates WebSocket in DotWeb.

Jump to

Keyboard shortcuts

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