From 74c67c940001582671c41430e81000d248de7d7b Mon Sep 17 00:00:00 2001 From: catatsuy Date: Sun, 23 Feb 2025 17:12:21 +0900 Subject: [PATCH] Add pathvalue example to README and implement PathValue handler. --- _examples/README.md | 1 + _examples/pathvalue/main.go | 25 +++++++++++++++++++++++++ 2 files changed, 26 insertions(+) create mode 100644 _examples/pathvalue/main.go diff --git a/_examples/README.md b/_examples/README.md index 4bc4edc8..18b809b6 100644 --- a/_examples/README.md +++ b/_examples/README.md @@ -12,6 +12,7 @@ chi examples * [router-walk](https://github.com/go-chi/chi/blob/master/_examples/router-walk/main.go) - Print to stdout a router's routes * [todos-resource](https://github.com/go-chi/chi/blob/master/_examples/todos-resource/main.go) - Struct routers/handlers, an example of another code layout style * [versions](https://github.com/go-chi/chi/blob/master/_examples/versions/main.go) - Demo of `chi/render` subpkg +* [pathvalue](https://github.com/go-chi/chi/blob/master/_examples/pathvalue/main.go) - Demonstrates `PathValue` usage for retrieving URL parameters ## Usage diff --git a/_examples/pathvalue/main.go b/_examples/pathvalue/main.go new file mode 100644 index 00000000..c13f2800 --- /dev/null +++ b/_examples/pathvalue/main.go @@ -0,0 +1,25 @@ +package main + +import ( + "fmt" + "net/http" + + "github.com/go-chi/chi/v5" +) + +func main() { + r := chi.NewRouter() + + // Registering a handler that retrieves a path parameter using PathValue + r.Get("/users/{userID}", pathValueHandler) + + http.ListenAndServe(":3333", r) +} + +// pathValueHandler retrieves a URL parameter using PathValue and writes it to the response. +func pathValueHandler(w http.ResponseWriter, r *http.Request) { + userID := r.PathValue("userID") + + // Respond with the extracted userID + w.Write([]byte(fmt.Sprintf("User ID: %s", userID))) +}