Files
httpx/examples/server-basic/main.go
Aleksey Shakhmatov 3aa7536328
All checks were successful
CI / test (push) Successful in 31s
Add examples/ with runnable usage demos for all major features
Six examples covering the full API surface:
- basic-client: retry, timeout, logging, response size limit
- form-request: form-encoded POST for OAuth/webhooks
- load-balancing: weighted endpoints, circuit breaker, health checks
- server-basic: routing, groups, JSON helpers, health, custom 404
- server-protected: CORS, rate limiting, body limits, timeouts
- request-id-propagation: cross-service request ID forwarding

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-22 22:05:08 +03:00

55 lines
1.3 KiB
Go

// Basic HTTP server with routing, middleware, health checks, and graceful shutdown.
package main
import (
"log"
"log/slog"
"net/http"
"git.codelab.vc/pkg/httpx/server"
)
func main() {
logger := slog.Default()
r := server.NewRouter(
server.WithNotFoundHandler(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
server.WriteError(w, http.StatusNotFound, "resource not found")
})),
)
// Public endpoints.
r.HandleFunc("GET /hello", func(w http.ResponseWriter, _ *http.Request) {
server.WriteJSON(w, http.StatusOK, map[string]string{
"message": "Hello, World!",
})
})
// API group with shared prefix.
api := r.Group("/api/v1")
api.HandleFunc("GET /users/{id}", getUser)
api.HandleFunc("POST /users", createUser)
// Health checks.
r.Mount("/", server.HealthHandler())
// Server with production defaults (RequestID → Recovery → Logging).
srv := server.New(r, server.Defaults(logger)...)
log.Fatal(srv.ListenAndServe())
}
func getUser(w http.ResponseWriter, r *http.Request) {
id := r.PathValue("id")
server.WriteJSON(w, http.StatusOK, map[string]string{
"id": id,
"name": "Alice",
})
}
func createUser(w http.ResponseWriter, r *http.Request) {
server.WriteJSON(w, http.StatusCreated, map[string]any{
"id": 1,
"message": "user created",
})
}