Add pathvalue example to README and implement PathValue handler. (#985)

This commit is contained in:
Tatsuya Kaneko 2025-08-16 00:25:26 +09:00 committed by GitHub
parent 23c395f852
commit 80d8da2a18
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
2 changed files with 26 additions and 0 deletions

View file

@ -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

View file

@ -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)))
}