-
Notifications
You must be signed in to change notification settings - Fork 8
/
main.go
77 lines (62 loc) · 1.44 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
package main
import (
"fmt"
"log"
"net/http"
"os"
"strconv"
"github.com/go-chi/chi"
"github.com/go-chi/chi/middleware"
"github.com/while1malloc0/hotwire-go-example/models"
"github.com/while1malloc0/hotwire-go-example/routes"
)
func main() {
log.Println("Starting app")
setupDB()
router := registerRoutes()
port := getPort()
log.Printf("Serving on port %d", port)
if err := http.ListenAndServe(fmt.Sprintf(":%d", port), router); err != nil {
log.Fatal(err)
}
}
func registerRoutes() http.Handler {
log.Println("Registering routes")
r := chi.NewMux()
r.Use(middleware.Logger)
r.Use(middleware.Recoverer)
routes.Register(r)
r.Handle("/public/*", http.StripPrefix("/public/", http.FileServer(http.Dir("./public"))))
logRoutes(r)
return r
}
func logRoutes(r chi.Router) {
log.Println("Serving with routes")
chi.Walk(r, func(method, route string, handler http.Handler, middlewares ...func(http.Handler) http.Handler) error {
log.Println(method, route)
return nil
})
}
func setupDB() {
log.Println("Running migrations")
err := models.Migrate()
if err != nil {
log.Fatalf("Fatal error: %v", err)
}
log.Println("Seeding database")
err = models.Seed()
if err != nil {
log.Fatalf("Fatal error: %v", err)
}
}
func getPort() int {
port := 8080
if p, ok := os.LookupEnv("HOTWIRE_CHAT_PORT"); ok {
parsed, err := strconv.Atoi(p)
if err != nil {
log.Fatalf("Fatal error: %v", err)
}
port = parsed
}
return port
}