-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.go
More file actions
138 lines (117 loc) · 3.34 KB
/
server.go
File metadata and controls
138 lines (117 loc) · 3.34 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
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
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
package main
import (
"context"
"errors"
"fmt"
"net/http"
"os"
"os/signal"
"syscall"
"time"
"github.com/rs/zerolog/log"
"gorm.io/gorm"
)
type ServerOption func(*Server)
func WithConfig(cfg *Config) ServerOption {
return func(s *Server) { s.cfg = cfg }
}
func WithDB(db *gorm.DB) ServerOption {
return func(s *Server) { s.db = db }
}
func WithProcessor(processor QueueTrigger) ServerOption {
return func(s *Server) { s.processor = processor }
}
func NewServer(opts ...ServerOption) (*Server, error) {
s := &Server{}
var err error // Declare err here
for _, opt := range opts {
opt(s)
}
// Fallback ke default kalau belum diinject
if s.cfg == nil {
s.cfg, err = Load()
if err != nil {
return nil, fmt.Errorf("failed to load config: %w", err)
}
}
if s.db == nil {
s.db, err = NewGORM(s.cfg)
if err != nil {
return nil, fmt.Errorf("failed to create GORM instance: %w", err)
}
}
if err := Migrate(s.db); err != nil {
return nil, fmt.Errorf("failed to run migrations: %w", err)
}
if s.processor == nil {
s.processor, err = NewQueueProcessor(s.cfg, s.db, &FakeAPI{})
if err != nil {
return nil, fmt.Errorf("failed to create queue processor: %w", err)
}
}
repo := NewRepository(s.db)
handler := NewHttpHandler(repo, s.processor)
r := http.NewServeMux()
r.HandleFunc("GET /", rootHandler)
r.HandleFunc("POST /api/v1/queues", handler.CreateQueue)
r.HandleFunc("GET /api/v1/queues", handler.GetQueueList)
r.HandleFunc("DELETE /api/v1/queues/{id}", handler.DeleteQueueByID)
r.HandleFunc("POST /api/v1/queues/process", handler.ProcessQueue)
r.HandleFunc("POST /api/v1/queues/leave", handler.LeaveQueue)
s.router = r
return s, nil
}
type Server struct {
router *http.ServeMux
cfg *Config
db *gorm.DB
processor QueueTrigger
}
// Run method of the Server struct runs the HTTP server on the specified port. It initializes
// a new HTTP server instance with the specified port and the server's router.
func (s *Server) Run(port int) error {
addr := fmt.Sprintf(":%d", port)
h := chainMiddleware(
s.router,
recoverHandler,
loggerHandler(func(w http.ResponseWriter, r *http.Request) bool { return r.URL.Path == "/health" }),
realIPHandler,
requestIDHandler,
corsHandler,
)
httpSrv := http.Server{
Addr: addr,
Handler: h,
ReadTimeout: 60 * time.Second,
WriteTimeout: 60 * time.Second,
}
done := make(chan bool)
quit := make(chan os.Signal, 1)
signal.Notify(quit, os.Interrupt, syscall.SIGTERM)
go func() {
<-quit
log.Info().Msg("server is shuting down...")
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
httpSrv.SetKeepAlivesEnabled(false)
if err := httpSrv.Shutdown(ctx); err != nil {
log.Error().Err(fmt.Errorf("could not gracefully shutdown the server: %w", err)).Msg("server shutdown error")
}
close(done)
}()
log.Info().Msgf("server serving on port %d", port)
if err := httpSrv.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) {
return fmt.Errorf("could not listen on %s: %w", addr, err)
}
<-done
log.Info().Msg("server stopped")
return nil
}
func rootHandler(w http.ResponseWriter, r *http.Request) {
if r.URL.Path != "/" {
http.Error(w, http.StatusText(http.StatusNotFound), http.StatusNotFound)
return
}
w.WriteHeader(http.StatusOK)
w.Write([]byte(http.StatusText(http.StatusOK)))
}