Browse Source

docs and examples

pull/598/head
Bergutov Ruslan 5 years ago
parent
commit
cddaa9690d
  1. 27
      README.md
  2. 25
      example_router_test.go

27
README.md

@ -28,6 +28,7 @@ The name mux stands for "HTTP request multiplexer". Like the standard `http.Serv @@ -28,6 +28,7 @@ The name mux stands for "HTTP request multiplexer". Like the standard `http.Serv
* [Serving Single Page Applications](#serving-single-page-applications) (e.g. React, Vue, Ember.js, etc.)
* [Registered URLs](#registered-urls)
* [Walking Routes](#walking-routes)
* [Alias Pattern Registration](#pattern-registration)
* [Graceful Shutdown](#graceful-shutdown)
* [Middleware](#middleware)
* [Handling CORS Requests](#handling-cors-requests)
@ -435,6 +436,32 @@ func main() { @@ -435,6 +436,32 @@ func main() {
}
```
### Alias Pattern Registration
There can be a situation when you often need to specify some complex regular expressions inside your paths, e.g. uuid. This can be easily shorthanded:
```go
package main
import (
"net/http"
"github.com/gorilla/mux"
)
func handler(w http.ResponseWriter, r *http.Request) {
return
}
func main() {
r := mux.NewRouter().RegisterPattern("uuid", "[a-fA-F0-9]{8}-[a-fA-F0-9]{4}-4[a-fA-F0-9]{3}-[8|9|aA|bB][a-fA-F0-9]{3}-[a-fA-F0-9]{12}")
r.HandleFunc("/products/{id:uuid}", handler)
r.HandleFunc("/articles/{id:uuid}", handler)
r.HandleFunc("/authors/{id:uuid}", handler)
}
```
### Graceful Shutdown
Go 1.8 introduced the ability to [gracefully shutdown](https://golang.org/doc/go1.8#http_shutdown) a `*http.Server`. Here's how to do that alongside `mux`:

25
example_router_test.go

@ -0,0 +1,25 @@ @@ -0,0 +1,25 @@
package mux_test
import (
"fmt"
"github.com/gorilla/mux"
"net/http"
)
// This example demonstrates alias pattern registration on router
func ExampleRouter_RegisterPattern() {
r := mux.NewRouter().RegisterPattern("uuid", "[a-fA-F0-9]{8}-[a-fA-F0-9]{4}-4[a-fA-F0-9]{3}-[8|9|aA|bB][a-fA-F0-9]{3}-[a-fA-F0-9]{12}")
route := r.Path("/category/{id:uuid}")
yes, _ := http.NewRequest("GET", "example.co/category/abe193ed-e0bc-4e1b-8e3c-736d5b381b60", nil)
no, _ := http.NewRequest("GET", "example.co/category/42", nil)
mathInfo := &mux.RouteMatch{}
fmt.Printf("Match: %v %q\n", route.Match(yes, mathInfo), yes.URL.Path)
fmt.Printf("Match: %v %q\n", route.Match(no, mathInfo), no.URL.Path)
// Output
// Match: true /category/abe193ed-e0bc-4e1b-8e3c-736d5b381b60
// Match: false /category/42
}
Loading…
Cancel
Save