RouterGetting Started
Getting Started
Learn how to create your first HTTP server with the NLG Router package using static routes, parameterized routes, and middleware-ready handlers.
Quick Start
The example below creates a minimal HTTP server using the router package.
It demonstrates:
- Router initialization
- Static route handling
- Parameterized routes
- Accessing route parameters
- Starting an HTTP server
package main
import (
"log/slog"
"net/http"
"os"
"github.com/netlifeguru/logger"
"github.com/netlifeguru/router"
)
func main() {
r := router.New()
closer, err := logger.Init(logger.Config{
Dir: "./logs",
TerminalOutput: true,
DisableColors: false,
MinLevel: slog.LevelInfo,
ConsoleMinLevel: slog.LevelDebug,
MaxFileSize: 100 * 1024 * 1024,
MaxLogFiles: 10,
})
if err != nil {
slog.Error("failed to initialize logger", "error", err)
os.Exit(1)
}
defer func() {
if err := closer.Close(); err != nil {
slog.Error("failed to close logger", "error", err)
}
}()
r.Use(router.Logger())
r.HandleFunc("/", "GET POST", func(w http.ResponseWriter, req *http.Request, ctx *router.Context) {
w.Header().Set("Content-Type", "text/html")
w.WriteHeader(http.StatusCreated)
w.Write([]byte(`<h1>Hello World</h1>`))
})
r.HandleFunc("/user/{id}", "GET", func(w http.ResponseWriter, req *http.Request, ctx *router.Context) {
id := ctx.Param("id")
w.Write([]byte(id))
})
if err := r.ListenAndServe(":8000"); err != nil {
slog.Error("failed to start server", "error", err)
os.Exit(1)
}
}Run the application:
go run main.goThe server starts on:
http://localhost:8000Example requests:
curl http://localhost:8000/
curl http://localhost:8000/user/42Expected response:
42The router.Context object provides access to route parameters, request-scoped values, and helper methods used throughout the routing system.
Continue with the next sections to learn about middleware, route groups, custom matchers, static assets, and advanced server configuration.