This repository has been archived by the owner on Oct 2, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.go
73 lines (59 loc) · 1.47 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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
package main
import (
"html/template"
"log"
"net/http"
"github.com/uptrace/treemux"
"github.com/uptrace/treemux/extra/reqlog"
)
func main() {
router := treemux.New(
treemux.WithMiddleware(reqlog.NewMiddleware()),
).Compat()
router.GET("/", indexHandler)
router.WithGroup("/api", func(g *treemux.CompatGroup) {
g.GET("/users/:id", userHandler)
g.GET("/images/*path", imageHandler)
})
log.Println("listening on http://localhost:8888")
log.Println(http.ListenAndServe(":8888", router))
}
func indexHandler(w http.ResponseWriter, req *http.Request) {
if err := indexTemplate().Execute(w, nil); err != nil {
panic(err)
}
}
func userHandler(w http.ResponseWriter, req *http.Request) {
route := treemux.RouteFromContext(req.Context())
id, err := route.Params().Uint64("id")
if err != nil {
panic(err)
}
if err := treemux.JSON(w, treemux.H{
"route": route.Name(),
"id": id,
}); err != nil {
panic(err)
}
}
func imageHandler(w http.ResponseWriter, req *http.Request) {
route := treemux.RouteFromContext(req.Context())
if err := treemux.JSON(w, treemux.H{
"route": route.Name(),
"path": route.Param("path"),
}); err != nil {
panic(err)
}
}
var indexTmpl = `
<html>
<h1>Welcome</h1>
<ul>
<li><a href="/api/users/123">/api/users/123</a></li>
<li><a href="/api/images/path/to/image.jpg">/images/path/to/image.jpg</a></li>
</ul>
</html>
`
func indexTemplate() *template.Template {
return template.Must(template.New("index").Parse(indexTmpl))
}