forked from budougumi0617/go_todo_app
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmux.go
73 lines (69 loc) · 1.97 KB
/
mux.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 (
"context"
"net/http"
"github.com/budougumi0617/go_todo_app/auth"
"github.com/budougumi0617/go_todo_app/clock"
"github.com/budougumi0617/go_todo_app/config"
"github.com/budougumi0617/go_todo_app/handler"
"github.com/budougumi0617/go_todo_app/service"
"github.com/budougumi0617/go_todo_app/store"
"github.com/go-chi/chi/v5"
"github.com/go-playground/validator/v10"
)
func NewMux(ctx context.Context, cfg *config.Config) (http.Handler, func(), error) {
mux := chi.NewRouter()
mux.HandleFunc("/health", func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json; charset=utf-8")
_, _ = w.Write([]byte(`{"status": "ok"}`))
})
v := validator.New()
db, cleanup, err := store.New(ctx, cfg)
if err != nil {
return nil, cleanup, err
}
clocker := clock.RealClocker{}
r := store.Repository{Clocker: clocker}
rcli, err := store.NewKVS(ctx, cfg)
if err != nil {
return nil, cleanup, err
}
jwter, err := auth.NewJWTer(rcli, clocker)
if err != nil {
return nil, cleanup, err
}
ru := &handler.RegisterUser{
Service: &service.RegisterUser{DB: db, Repo: &r},
Validator: v,
}
mux.Post("/register", ru.ServeHTTP)
l := &handler.Login{
Service: &service.Login{
DB: db,
Repo: &r,
TokenGenerator: jwter,
},
Validator: v,
}
mux.Post("/login", l.ServeHTTP)
at := &handler.AddTask{
Service: &service.AddTask{DB: db, Repo: &r},
Validator: v,
}
lt := &handler.ListTask{
Service: &service.ListTask{DB: db, Repo: &r},
}
mux.Route("/tasks", func(r chi.Router) {
r.Use(handler.AuthMiddleware(jwter))
r.Post("/", at.ServeHTTP)
r.Get("/", lt.ServeHTTP)
})
mux.Route("/admin", func(r chi.Router) {
r.Use(handler.AuthMiddleware(jwter), handler.AdminMiddleware)
r.Get("/", func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json; charset=utf-8")
_, _ = w.Write([]byte(`{"message": "admin only"}`))
})
})
return mux, cleanup, nil
}