305 lines
6.3 KiB
Markdown
305 lines
6.3 KiB
Markdown
# Examples
|
|
|
|
## Basic Usage
|
|
|
|
```go
|
|
package main
|
|
|
|
import (
|
|
"fmt"
|
|
"github.com/valyala/fasthttp"
|
|
"git.sharkk.net/Go/FastRouter"
|
|
)
|
|
|
|
func main() {
|
|
r := router.New()
|
|
|
|
r.Get("/", func(ctx router.Ctx, _ []string) {
|
|
fmt.Fprintf(ctx, "Hello World!")
|
|
})
|
|
|
|
r.Get("/about", func(ctx router.Ctx, _ []string) {
|
|
fmt.Fprintf(ctx, "About page")
|
|
})
|
|
|
|
fasthttp.ListenAndServe(":8080", r.Handler())
|
|
}
|
|
```
|
|
|
|
## Path Parameters
|
|
|
|
```go
|
|
r := router.New()
|
|
|
|
// Single parameter
|
|
r.Get("/users/[id]", func(ctx router.Ctx, params []string) {
|
|
id := params[0]
|
|
fmt.Fprintf(ctx, "User ID: %s", id)
|
|
})
|
|
|
|
// Multiple parameters
|
|
r.Get("/posts/[category]/[id]", func(ctx router.Ctx, params []string) {
|
|
category := params[0]
|
|
id := params[1]
|
|
fmt.Fprintf(ctx, "Category: %s, Post ID: %s", category, id)
|
|
})
|
|
|
|
// Wildcard
|
|
r.Get("/files/*path", func(ctx router.Ctx, params []string) {
|
|
path := params[0]
|
|
fmt.Fprintf(ctx, "File path: %s", path)
|
|
})
|
|
```
|
|
|
|
## Middleware
|
|
|
|
```go
|
|
// Logging middleware
|
|
func LoggingMiddleware(next router.Handler) router.Handler {
|
|
return func(ctx router.Ctx, params []string) {
|
|
fmt.Printf("[%s] %s\n", string(ctx.Method()), string(ctx.Path()))
|
|
next(ctx, params)
|
|
}
|
|
}
|
|
|
|
// Auth middleware
|
|
func AuthMiddleware(next router.Handler) router.Handler {
|
|
return func(ctx router.Ctx, params []string) {
|
|
token := string(ctx.Request.Header.Peek("Authorization"))
|
|
if token == "" {
|
|
ctx.Error("Unauthorized", fasthttp.StatusUnauthorized)
|
|
return
|
|
}
|
|
next(ctx, params)
|
|
}
|
|
}
|
|
|
|
// Global middleware
|
|
r := router.New()
|
|
r.Use(LoggingMiddleware)
|
|
|
|
// Route-specific middleware
|
|
r.WithMiddleware(AuthMiddleware).Get("/admin", adminHandler)
|
|
```
|
|
|
|
## Route Groups
|
|
|
|
```go
|
|
r := router.New()
|
|
|
|
// API group
|
|
api := r.Group("/api")
|
|
api.Get("/status", statusHandler)
|
|
|
|
// Versioned API
|
|
v1 := api.Group("/v1")
|
|
v1.Get("/users", listUsersHandler)
|
|
v1.Post("/users", createUserHandler)
|
|
|
|
v2 := api.Group("/v2")
|
|
v2.Get("/users", listUsersV2Handler)
|
|
```
|
|
|
|
## Using Standard fasthttp Handlers
|
|
|
|
```go
|
|
r := router.New()
|
|
|
|
// Using existing fasthttp handlers
|
|
r.Get("/legacy", router.StandardHandler(func(ctx *fasthttp.RequestCtx) {
|
|
fmt.Fprintf(ctx, "Legacy fasthttp handler")
|
|
}))
|
|
|
|
// Mixing router handlers with standard handlers
|
|
r.Get("/users/[id]", func(ctx router.Ctx, params []string) {
|
|
// Get ID from params
|
|
id := params[0]
|
|
|
|
// Pass to standard handler
|
|
standardUserHandler := router.StandardHandler(func(ctx *fasthttp.RequestCtx) {
|
|
fmt.Fprintf(ctx, "Processing user: %s", id)
|
|
})
|
|
|
|
standardUserHandler(ctx, params)
|
|
})
|
|
```
|
|
|
|
## Combining Features
|
|
|
|
```go
|
|
r := router.New()
|
|
|
|
// Global middleware
|
|
r.Use(LoggingMiddleware)
|
|
|
|
// API group with middleware
|
|
api := r.Group("/api")
|
|
api.Use(ApiKeyMiddleware)
|
|
|
|
// Admin group with auth middleware
|
|
admin := r.Group("/admin")
|
|
admin.Use(AuthMiddleware)
|
|
|
|
// Users endpoints with versioning
|
|
users := api.Group("/v1/users")
|
|
users.Get("/", listUsersHandler)
|
|
users.Post("/", createUserHandler)
|
|
users.Get("/[id]", getUserHandler)
|
|
users.Put("/[id]", updateUserHandler)
|
|
users.Delete("/[id]", deleteUserHandler)
|
|
|
|
// Special case with route-specific middleware
|
|
api.WithMiddleware(CacheMiddleware).Get("/cached-resource", cachedResourceHandler)
|
|
```
|
|
|
|
## Error Handling
|
|
|
|
```go
|
|
r := router.New()
|
|
|
|
err := r.Get("/users/[id]", getUserHandler)
|
|
if err != nil {
|
|
// Handle error
|
|
}
|
|
|
|
// Custom NotFound handler
|
|
r.ServeHTTP = func(ctx *fasthttp.RequestCtx) {
|
|
path := string(ctx.Path())
|
|
method := string(ctx.Method())
|
|
|
|
h, params, found := r.Lookup(method, path)
|
|
if !found {
|
|
// Custom 404 handler
|
|
ctx.SetStatusCode(fasthttp.StatusNotFound)
|
|
fmt.Fprintf(ctx, "Custom 404: %s not found", path)
|
|
return
|
|
}
|
|
h(ctx, params)
|
|
}
|
|
```
|
|
|
|
## Complete Application Example
|
|
|
|
```go
|
|
package main
|
|
|
|
import (
|
|
"fmt"
|
|
"log"
|
|
|
|
"github.com/valyala/fasthttp"
|
|
"github.com/yourusername/fastrouter"
|
|
)
|
|
|
|
func main() {
|
|
r := router.New()
|
|
|
|
// Global middleware
|
|
r.Use(LoggingMiddleware)
|
|
|
|
// Basic routes
|
|
r.Get("/", homeHandler)
|
|
r.Get("/about", aboutHandler)
|
|
|
|
// API routes
|
|
api := r.Group("/api")
|
|
api.Use(ApiKeyMiddleware)
|
|
|
|
// Users API
|
|
users := api.Group("/users")
|
|
users.Get("/", listUsersHandler)
|
|
users.Post("/", createUserHandler)
|
|
users.Get("/[id]", getUserHandler)
|
|
users.Put("/[id]", updateUserHandler)
|
|
users.Delete("/[id]", deleteUserHandler)
|
|
|
|
// Admin routes with auth
|
|
admin := r.Group("/admin")
|
|
admin.Use(AuthMiddleware)
|
|
admin.Get("/", adminDashboardHandler)
|
|
admin.Get("/users", adminUsersHandler)
|
|
|
|
// Start server
|
|
log.Println("Server starting on :8080")
|
|
log.Fatal(fasthttp.ListenAndServe(":8080", r.Handler()))
|
|
}
|
|
|
|
// Handlers
|
|
func homeHandler(ctx router.Ctx, _ []string) {
|
|
fmt.Fprintf(ctx, "Welcome to the home page")
|
|
}
|
|
|
|
func aboutHandler(ctx router.Ctx, _ []string) {
|
|
fmt.Fprintf(ctx, "About us")
|
|
}
|
|
|
|
func listUsersHandler(ctx router.Ctx, _ []string) {
|
|
fmt.Fprintf(ctx, "List of users")
|
|
}
|
|
|
|
func getUserHandler(ctx router.Ctx, params []string) {
|
|
id := params[0]
|
|
fmt.Fprintf(ctx, "User details for ID: %s", id)
|
|
}
|
|
|
|
func createUserHandler(ctx router.Ctx, _ []string) {
|
|
// Parse form data or JSON body
|
|
// You can use ctx.PostBody() to get the request body
|
|
fmt.Fprintf(ctx, "User created")
|
|
}
|
|
|
|
func updateUserHandler(ctx router.Ctx, params []string) {
|
|
id := params[0]
|
|
fmt.Fprintf(ctx, "User updated: %s", id)
|
|
}
|
|
|
|
func deleteUserHandler(ctx router.Ctx, params []string) {
|
|
id := params[0]
|
|
fmt.Fprintf(ctx, "User deleted: %s", id)
|
|
}
|
|
|
|
func adminDashboardHandler(ctx router.Ctx, _ []string) {
|
|
fmt.Fprintf(ctx, "Admin Dashboard")
|
|
}
|
|
|
|
func adminUsersHandler(ctx router.Ctx, _ []string) {
|
|
fmt.Fprintf(ctx, "Admin Users Management")
|
|
}
|
|
|
|
// Middleware
|
|
func LoggingMiddleware(next router.Handler) router.Handler {
|
|
return func(ctx router.Ctx, params []string) {
|
|
log.Printf("[%s] %s", string(ctx.Method()), string(ctx.Path()))
|
|
next(ctx, params)
|
|
}
|
|
}
|
|
|
|
func ApiKeyMiddleware(next router.Handler) router.Handler {
|
|
return func(ctx router.Ctx, params []string) {
|
|
apiKey := string(ctx.Request.Header.Peek("X-API-Key"))
|
|
if apiKey == "" {
|
|
ctx.Error("API key required", fasthttp.StatusUnauthorized)
|
|
return
|
|
}
|
|
next(ctx, params)
|
|
}
|
|
}
|
|
|
|
func AuthMiddleware(next router.Handler) router.Handler {
|
|
return func(ctx router.Ctx, params []string) {
|
|
// Check session or JWT
|
|
authorized := checkUserAuth(ctx)
|
|
if !authorized {
|
|
ctx.Redirect("/login", fasthttp.StatusSeeOther)
|
|
return
|
|
}
|
|
next(ctx, params)
|
|
}
|
|
}
|
|
|
|
func checkUserAuth(ctx router.Ctx) bool {
|
|
// Implementation of auth check
|
|
return len(ctx.Request.Header.Peek("Authorization")) > 0
|
|
}
|
|
```
|