-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathmain.go
116 lines (95 loc) · 2.23 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
103
104
105
106
107
108
109
110
111
112
113
114
115
116
package main
import (
"context"
"fmt"
"log"
"net/http"
"os"
"os/signal"
"time"
"github.com/go-chi/chi/v5"
driver "github.com/jmoiron/sqlx"
"gorm.io/gorm"
"godb/config"
"godb/db"
"godb/db/ent"
"godb/db/ent/ent/gen"
gormDB "godb/db/gorm"
"godb/db/sqlboiler"
"godb/db/sqlc"
"godb/db/sqlx"
"godb/db/squirrel"
"godb/middleware"
)
type App struct {
sqlx *driver.DB
gorm *gorm.DB
ent *gen.Client
config *config.Configuration
router *chi.Mux
httpServer *http.Server
}
func main() {
app := &App{}
app.config = config.New()
app.SetupDB()
app.SetupRouter()
app.SetupServer()
app.Run()
}
func (a *App) Run() {
go func() {
log.Printf("Serving at %s", a.httpServer.Addr)
err := a.httpServer.ListenAndServe()
if err != nil {
log.Fatal(err)
}
}()
quit := make(chan os.Signal, 1)
signal.Notify(quit, os.Interrupt)
<-quit
ctx, shutdown := context.WithTimeout(context.Background(), 60*time.Second)
defer shutdown()
_ = a.sqlx.Close()
_ = a.ent.Close()
// You cannot close database connection created by gorm
_ = a.httpServer.Shutdown(ctx)
}
func (a *App) SetupRouter() {
a.router = chi.NewRouter()
a.router.Use(middleware.Json)
a.router.NotFound(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusNotFound)
_, _ = w.Write([]byte(`{"message": "endpoint not found"}`))
})
sqlx.Register(a.router, a.sqlx, a.config.DB.Type)
sqlc.Register(a.router, a.sqlx, a.config.DB.Type)
squirrel.Register(a.router, a.sqlx)
gormDB.Register(a.router, a.gorm)
sqlboiler.Register(a.router, a.sqlx)
ent.Register(a.router, a.ent)
printAllRegisteredRoutes(a.router)
}
func (a *App) SetupDB() {
a.sqlx = db.New(a.config.DB)
a.gorm = gormDB.New(a.config.DB)
a.ent = ent.New(a.config.DB)
}
func (a *App) SetupServer() {
a.httpServer = &http.Server{
Addr: "0.0.0.0:3080",
Handler: a.router,
ReadTimeout: 10 * time.Second,
WriteTimeout: 60 * time.Second,
MaxHeaderBytes: 1 << 20,
}
}
func printAllRegisteredRoutes(r *chi.Mux) {
walkFunc := func(method string, path string, handler http.Handler, middlewares ...func(http.Handler) http.Handler) error {
fmt.Printf("%-7s %s\n", method, path)
return nil
}
if err := chi.Walk(r, walkFunc); err != nil {
fmt.Print(err)
}
}