-
Notifications
You must be signed in to change notification settings - Fork 56
/
example_test.go
101 lines (88 loc) · 2.47 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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
package gear_test
import (
"fmt"
"github.com/teambition/gear"
"github.com/teambition/gear/logging"
"github.com/teambition/gear/middleware/static"
)
func Example() {
// Create app
app := gear.New()
// Use a default logger middleware
app.UseHandler(logging.Default())
// Add a static middleware
// http://localhost:3000/middleware/static.go
app.Use(static.New(static.Options{
Root: "./middleware",
Prefix: "/middleware",
StripPrefix: true,
}))
// Add some middleware to app
app.Use(func(ctx *gear.Context) (err error) {
// fmt.Println(ctx.IP(), ctx.Method, ctx.Path
// Do something...
// Add after hook to the ctx
ctx.After(func() {
// Do something in after hook
fmt.Println("After hook")
})
return
})
// Create views router
ViewRouter := gear.NewRouter()
// "http://localhost:3000"
ViewRouter.Get("/", func(ctx *gear.Context) error {
return ctx.HTML(200, "<h1>Hello, Gear!</h1>")
})
// "http://localhost:3000/view/abc"
// "http://localhost:3000/view/123"
ViewRouter.Get("/view/:view", func(ctx *gear.Context) error {
view := ctx.Param("view")
if view == "" {
return gear.ErrBadRequest.WithMsg("Invalid view")
}
return ctx.HTML(200, "View: "+view)
})
// "http://localhost:3000/abc"
// "http://localhost:3000/abc/efg"
ViewRouter.Get("/:others*", func(ctx *gear.Context) error {
others := ctx.Param("others")
if others == "" {
return gear.ErrBadRequest.WithMsg("Invalid path")
}
return ctx.HTML(200, "Request path: /"+others)
})
// Create API router
APIRouter := gear.NewRouter(gear.RouterOptions{Root: "/api", IgnoreCase: true})
// "http://localhost:3000/api/user/abc"
// "http://localhost:3000/abc/user/123"
APIRouter.Get("/user/:id", func(ctx *gear.Context) error {
id := ctx.Param("id")
if id == "" {
return gear.ErrBadRequest.WithMsg("Invalid user id")
}
return ctx.JSON(200, map[string]string{
"Method": ctx.Method,
"Path": ctx.Path,
"UserID": id,
})
})
// Must add APIRouter first.
app.UseHandler(APIRouter)
app.UseHandler(ViewRouter)
// Start app at 3000
app.Error(app.Listen(":3000"))
}
// func ExampleRunBackground() {
// app := gear.New()
// app.Use(func(ctx *gear.Context) error {
// return ctx.End(200, []byte("<h1>Hello!</h1>"))
// })
// s := app.Start() // Start at random addr.
// fmt.Printf("App start at: %s\n", s.Addr())
// go func() {
// time.Sleep(time.Second * 3) // Close it after 3 sec
// fmt.Printf("App closed: %s\n", s.Close())
// }()
// s.Wait()
// }