# Examples ## Basic Usage ```go package main import ( "fmt" "net/http" "github.com/yourusername/router" ) func main() { r := router.New() r.Get("/", func(w http.ResponseWriter, r *http.Request, _ []string) { fmt.Fprintf(w, "Hello World!") }) r.Get("/about", func(w http.ResponseWriter, r *http.Request, _ []string) { fmt.Fprintf(w, "About page") }) http.ListenAndServe(":8080", r) } ``` ## Path Parameters ```go r := router.New() // Single parameter r.Get("/users/[id]", func(w http.ResponseWriter, r *http.Request, params []string) { id := params[0] fmt.Fprintf(w, "User ID: %s", id) }) // Multiple parameters r.Get("/posts/[category]/[id]", func(w http.ResponseWriter, r *http.Request, params []string) { category := params[0] id := params[1] fmt.Fprintf(w, "Category: %s, Post ID: %s", category, id) }) // Wildcard r.Get("/files/*path", func(w http.ResponseWriter, r *http.Request, params []string) { path := params[0] fmt.Fprintf(w, "File path: %s", path) }) ``` ## Middleware ```go // Logging middleware func LoggingMiddleware(next router.Handler) router.Handler { return router.Handler(func(w http.ResponseWriter, r *http.Request, params []string) { fmt.Printf("[%s] %s\n", r.Method, r.URL.Path) next(w, r, params) }) } // Auth middleware func AuthMiddleware(next router.Handler) router.Handler { return router.Handler(func(w http.ResponseWriter, r *http.Request, params []string) { token := r.Header.Get("Authorization") if token == "" { http.Error(w, "Unauthorized", http.StatusUnauthorized) return } next(w, r, 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) ``` ## 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 oldServeHTTP := r.ServeHTTP r.ServeHTTP = func(w http.ResponseWriter, req *http.Request) { h, params, ok := r.Lookup(req.Method, req.URL.Path) if !ok { // Custom 404 handler w.WriteHeader(http.StatusNotFound) fmt.Fprintf(w, "Custom 404: %s not found", req.URL.Path) return } h(w, req, params) } ``` ## Complete Application Example ```go package main import ( "fmt" "log" "net/http" "github.com/yourusername/router" ) 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(http.ListenAndServe(":8080", r)) } // Handlers func homeHandler(w http.ResponseWriter, r *http.Request, _ []string) { fmt.Fprintf(w, "Welcome to the home page") } func aboutHandler(w http.ResponseWriter, r *http.Request, _ []string) { fmt.Fprintf(w, "About us") } func listUsersHandler(w http.ResponseWriter, r *http.Request, _ []string) { fmt.Fprintf(w, "List of users") } func getUserHandler(w http.ResponseWriter, r *http.Request, params []string) { id := params[0] fmt.Fprintf(w, "User details for ID: %s", id) } func createUserHandler(w http.ResponseWriter, r *http.Request, _ []string) { // Parse form data or JSON body fmt.Fprintf(w, "User created") } func updateUserHandler(w http.ResponseWriter, r *http.Request, params []string) { id := params[0] fmt.Fprintf(w, "User updated: %s", id) } func deleteUserHandler(w http.ResponseWriter, r *http.Request, params []string) { id := params[0] fmt.Fprintf(w, "User deleted: %s", id) } func adminDashboardHandler(w http.ResponseWriter, r *http.Request, _ []string) { fmt.Fprintf(w, "Admin Dashboard") } func adminUsersHandler(w http.ResponseWriter, r *http.Request, _ []string) { fmt.Fprintf(w, "Admin Users Management") } // Middleware func LoggingMiddleware(next router.Handler) router.Handler { return router.Handler(func(w http.ResponseWriter, r *http.Request, params []string) { log.Printf("[%s] %s", r.Method, r.URL.Path) next(w, r, params) }) } func ApiKeyMiddleware(next router.Handler) router.Handler { return router.Handler(func(w http.ResponseWriter, r *http.Request, params []string) { apiKey := r.Header.Get("X-API-Key") if apiKey == "" { http.Error(w, "API key required", http.StatusUnauthorized) return } next(w, r, params) }) } func AuthMiddleware(next router.Handler) router.Handler { return router.Handler(func(w http.ResponseWriter, r *http.Request, params []string) { // Check session or JWT authorized := checkUserAuth(r) if !authorized { http.Redirect(w, r, "/login", http.StatusSeeOther) return } next(w, r, params) }) } func checkUserAuth(r *http.Request) bool { // Implementation of auth check return r.Header.Get("Authorization") != "" } ```