-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathserver.go
More file actions
83 lines (68 loc) · 1.68 KB
/
server.go
File metadata and controls
83 lines (68 loc) · 1.68 KB
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
package requiem
import (
"fmt"
"net/http"
"gorm.io/gorm"
)
const (
defaultPort = 8080
defaultBasePath = "/api"
)
// Server represents a REST API server container
// Default port is 8080
// Default path is /api
type Server struct {
Port int
BasePath string
ExitOnFatal bool
healthcheckEnabled bool
db *gorm.DB
controllers []IHttpController
}
func (s *Server) UsePostgresDB(debugMode bool) {
s.db = newPostgresDBConnection(debugMode)
}
func (s *Server) UseInMemoryDB(debugMode bool) {
s.db = newInMemoryDBConnection(debugMode)
}
func (s *Server) UseHealthcheck() {
if !s.healthcheckEnabled {
s.controllers = append(s.controllers, HealthcheckController{})
s.healthcheckEnabled = true
}
}
func (s *Server) AutoMigrate(models ...interface{}) {
for idx := range models {
s.db.AutoMigrate(models[idx])
}
}
// Start initializes the API and starts running on the specified port
// Blocks on current thread
func (s *Server) Start() {
if s.db != nil {
sqlDB, _ := s.db.DB()
defer sqlDB.Close()
}
// Create API router and load controllers
r := newRouter(s.BasePath, s.db, s.controllers)
r.printRoutes()
// Create HTTP server using API router
srv := &http.Server{
Handler: r.MuxRouter,
Addr: fmt.Sprintf(":%d", s.Port),
}
Logger.Info("Starting server on port %d", s.Port)
Logger.Fatal(srv.ListenAndServe().Error())
}
// NewServer creates a route-based REST API server instance
func NewServer(controllers ...IHttpController) *Server {
s := Server{
Port: defaultPort,
BasePath: defaultBasePath,
ExitOnFatal: true,
controllers: controllers,
}
// Create logger
InitLogger(s.ExitOnFatal)
return &s
}