forked from uptrace/bunrouter
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
59 lines (48 loc) · 1.27 KB
/
main.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
package main
import (
"html/template"
"log"
"net/http"
"github.com/uptrace/bunrouter"
"github.com/uptrace/bunrouter/extra/reqlog"
)
func main() {
router := bunrouter.New(
bunrouter.Use(reqlog.NewMiddleware(
reqlog.FromEnv("BUNDEBUG"),
)),
).Compat()
router.GET("/", indexHandler)
router.WithGroup("/api", func(g *bunrouter.CompatGroup) {
g.GET("/users/:id", debugHandler)
g.GET("/users/current", debugHandler)
g.GET("/users/*path", debugHandler)
})
log.Println("listening on http://localhost:9999")
log.Println(http.ListenAndServe(":9999", router))
}
func indexHandler(w http.ResponseWriter, req *http.Request) {
if err := indexTemplate().Execute(w, nil); err != nil {
panic(err)
}
}
func debugHandler(w http.ResponseWriter, req *http.Request) {
params := bunrouter.ParamsFromContext(req.Context())
_ = bunrouter.JSON(w, bunrouter.H{
"route": params.Route(),
"params": params.Map(),
})
}
var indexTmpl = `
<html>
<h1>Welcome</h1>
<ul>
<li><a href="/api/users/123">/api/users/123</a></li>
<li><a href="/api/users/current">/api/users/current</a></li>
<li><a href="/api/users/foo/bar">/api/users/foo/bar</a></li>
</ul>
</html>
`
func indexTemplate() *template.Template {
return template.Must(template.New("index").Parse(indexTmpl))
}