-
Notifications
You must be signed in to change notification settings - Fork 13
/
example_test.go
41 lines (32 loc) · 1.12 KB
/
example_test.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
package router_test
import (
"fmt"
"github.com/gowww/router"
"net/http"
)
func Example() {
rt := router.New()
// File server
rt.Get("/static/", http.StripPrefix("/static/", http.FileServer(http.Dir("static"))))
// Static route
rt.Get("/", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
fmt.Fprint(w, "Hello")
}))
// Path parameter
rt.Get("/users/:name", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Get user %s", router.Parameter(r, "name"))
}))
// Path parameter with regular expression
rt.Get(`users/:id:^\d+$`, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Page of user #%s", router.Parameter(r, "id"))
}))
// Path parameter + Trailing slash for wildcard
rt.Post("/users/:id/files/", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Post file %s to user %s", router.Parameter(r, "*"), router.Parameter(r, "id"))
}))
// Custom "not found"
rt.NotFoundHandler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
http.NotFound(w, r)
})
http.ListenAndServe(":8080", rt)
}