This directory contains examples demonstrating DotWeb features.
cd quickstart
go run main.go
# Visit http://localhost:8080
| Example |
Description |
Complexity |
| quickstart |
Minimal "Hello World" |
★☆☆ |
| routing |
Route patterns, params, groups |
★★☆ |
| group |
Route grouping with 404 handlers |
★★☆ |
| Example |
Description |
Complexity |
| middleware |
Logging, auth, CORS |
★★☆ |
| session |
Session management |
★★☆ |
| bind |
Data binding (form, JSON) |
★★☆ |
| config |
Configuration files |
★★☆ |
| router |
Advanced routing |
★★☆ |
| Example |
Description |
Complexity |
| mock |
Mock mode for testing |
★★☆ |
app.HttpServer.GET("/", handler)
app.HttpServer.POST("/users", handler)
app.HttpServer.PUT("/users/:id", handler)
app.HttpServer.DELETE("/users/:id", handler)
// 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)
})
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"}`)
})
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
})
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!")
})
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))
})
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": "alice@example.com",
})
})
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)
})
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
})
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"})
})
# Run any example
cd example/session
go run main.go
# With hot reload (using air)
air
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
# Run all tests
go test ./...
# With coverage
go test ./... -coverprofile=coverage.out
go tool cover -html=coverage.out