-
-
Notifications
You must be signed in to change notification settings - Fork 36
/
Copy pathmain.go
93 lines (76 loc) · 2.24 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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
package main
import (
"errors"
"fmt"
"html/template"
"log"
"net/http"
"github.com/rs/cors"
"github.com/uptrace/bunrouter"
"github.com/uptrace/bunrouter/extra/reqlog"
)
func main() {
router := bunrouter.New(
bunrouter.Use(reqlog.NewMiddleware()),
)
router.GET("/", indexHandler)
router.Use(errorMiddleware).
// Install CORS only for this group.
Use(newCorsMiddleware([]string{"http://localhost:9999"})).
WithGroup("/api/v1", func(g *bunrouter.Group) {
g.GET("/users/:id", userHandler)
g.GET("/error", failingHandler)
})
log.Println("listening on http://localhost:9999")
log.Println(http.ListenAndServe(":9999", router))
}
// newCorsMiddleware creates CORS middleware using github.com/rs/cors package.
func newCorsMiddleware(allowedOrigins []string) bunrouter.MiddlewareFunc {
corsHandler := cors.New(cors.Options{
AllowedOrigins: allowedOrigins,
AllowCredentials: true,
})
return func(next bunrouter.HandlerFunc) bunrouter.HandlerFunc {
return bunrouter.HTTPHandler(corsHandler.Handler(next))
}
}
func errorMiddleware(next bunrouter.HandlerFunc) bunrouter.HandlerFunc {
return func(w http.ResponseWriter, req bunrouter.Request) error {
err := next(w, req)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
return err
}
}
//------------------------------------------------------------------------------
func indexHandler(w http.ResponseWriter, req bunrouter.Request) error {
return indexTemplate().Execute(w, nil)
}
func userHandler(w http.ResponseWriter, req bunrouter.Request) error {
id, err := req.Params().Uint64("id")
if err != nil {
return err
}
return bunrouter.JSON(w, bunrouter.H{
"url": fmt.Sprintf("GET /api/v1/%d", id),
"route": req.Route(),
})
}
func failingHandler(w http.ResponseWriter, req bunrouter.Request) error {
return errors.New("just an error")
}
var indexTmpl = `
<html>
<h1>Welcome</h1>
<ul>
<li><a href="/api/v1/users/123">/api/v1/users/123</a></li>
<li><a href="/api/v1/error">/api/v1/error</a></li>
<li><a href="/api/v2/users/123">/api/v2/users/123</a></li>
<li><a href="/api/v2/error">/api/v2/error</a></li>
</ul>
</html>
`
func indexTemplate() *template.Template {
return template.Must(template.New("index").Parse(indexTmpl))
}