Add pathvalue example to README and implement PathValue handler. (#985)
This commit is contained in:
parent
23c395f852
commit
80d8da2a18
2 changed files with 26 additions and 0 deletions
|
|
@ -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
|
||||
|
|
|
|||
25
_examples/pathvalue/main.go
Normal file
25
_examples/pathvalue/main.go
Normal 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)))
|
||||
}
|
||||
Loading…
Reference in a new issue