-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
102 lines (79 loc) · 2.32 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
94
95
96
97
98
99
100
101
102
package main
import (
"fmt"
"net/http"
"github.com/go-chi/chi/v5"
"github.com/sxc/oishifood/controllers"
"github.com/sxc/oishifood/migrations"
"github.com/sxc/oishifood/models"
"github.com/sxc/oishifood/templates"
"github.com/sxc/oishifood/views"
)
func main() {
// Setup the database...
cfg := models.DefaultPostgresConfig()
fmt.Println(cfg.String())
db, err := models.Open(cfg)
if err != nil {
panic(err)
}
fmt.Println("Connected to database")
defer db.Close()
err = models.MigrateFS(db, migrations.FS, ".")
if err != nil {
panic(err)
}
sessionService := models.SessionService{
DB: db,
}
err = db.Ping()
if err != nil {
panic(err)
}
// Setup the routes...
r := chi.NewRouter()
// These middleware are used for every request
r.Use(csrfMw)
r.Use(umw.SetUser)
// now we setup routes
r.Get("/", controllers.StaticHandler(
views.Must(views.ParseFS(templates.FS, "home.gohtml", "tailwind.gohtml"))))
r.Get("/contact", controllers.StaticHandler(
views.Must(views.ParseFS(templates.FS, "contact.gohtml", "tailwind.gohtml"))))
r.Get("/faq", controllers.StaticHandler(
views.Must(views.ParseFS(templates.FS, "faq.gohtml", "tailwind.gohtml"))))
userService := models.UserService{
DB: db,
}
usersC := controllers.Users{
UserService: &userService,
SessionService: &sessionService,
}
usersC.Templates.New = views.Must(views.ParseFS(templates.FS,
"signup.gohtml", "tailwind.gohtml"))
usersC.Templates.SignIn = views.Must(views.ParseFS(templates.FS,
"signin.gohtml", "tailwind.gohtml"))
r.Get("/signup", usersC.New)
r.Post("/users", usersC.Create)
r.Get("/signin", usersC.SignIn)
r.Post("/signin", usersC.ProcessSignIn)
r.Post("/signout", usersC.ProcessSignOut)
r.Get("/users/me", func(r chi.Router) {
r.Use(umw.RequireUser)
r.Get("/", usersC.CurrentUser)
})
// defer db.Close()
r.NotFound(func(w http.ResponseWriter, r *http.Request) {
http.Error(w, "404 Page Not Found not found", http.StatusNotFound)
})
umw := controllers.UserMiddleware{
SessionService: &sessionService,
}
fmt.Println("Server is running on port 3000")
csrfKey := []byte("very-secret")
// TODO: Fix this before deploying to production
// csrfMw := csrf.Protect(csrfKey, csrf.Secure(false))
// r.Use(csrfMiddleware)
// http.ListenAndServe(":3000", csrfMiddleware(r))
http.ListenAndServe(":3000", r)
}