-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathgo-json-server.go
145 lines (123 loc) · 3.64 KB
/
go-json-server.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
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
package main
import (
"context"
"flag"
"fmt"
"log"
"net/http"
"os"
"os/signal"
"strconv"
"syscall"
"time"
"github.com/tkc/go-json-server/src/config"
"github.com/tkc/go-json-server/src/handler"
"github.com/tkc/go-json-server/src/logger"
"github.com/tkc/go-json-server/src/middleware"
)
var (
// Version of the application
Version = "1.0.0"
// Command line flags
configPath = flag.String("config", "./api.json", "Path to the configuration file")
port = flag.Int("port", 0, "Server port (overrides config)")
logLevel = flag.String("log-level", "", "Log level: debug, info, warn, error, fatal (overrides config)")
logFormat = flag.String("log-format", "", "Log format: text, json (overrides config)")
logPath = flag.String("log-path", "", "Path to log file (overrides config)")
cacheTTL = flag.Int("cache-ttl", 300, "Cache TTL in seconds")
)
func main() {
// Parse command line flags
flag.Parse()
// Load configuration
cfg, err := config.LoadConfig(*configPath)
if err != nil {
log.Fatalf("Failed to load configuration: %v", err)
}
// Override configuration with command line flags
if *port > 0 {
cfg.Port = *port
}
if *logLevel != "" {
cfg.LogLevel = *logLevel
}
if *logFormat != "" {
cfg.LogFormat = *logFormat
}
if *logPath != "" {
cfg.LogPath = *logPath
}
// Initialize logger
logConfig := logger.LogConfig{
Level: logger.ParseLogLevel(cfg.LogLevel),
Format: logger.LogFormat(cfg.LogFormat),
OutputPath: cfg.LogPath,
TimeFormat: time.RFC3339,
}
log, err := logger.NewLogger(logConfig)
if err != nil {
fmt.Printf("Failed to initialize logger: %v\n", err)
os.Exit(1)
}
defer log.Close()
// Log startup information
log.Info("Starting go-json-server", map[string]any{
"version": Version,
"port": cfg.Port,
})
// Create server with response cache
server := handler.NewServer(cfg, log, time.Duration(*cacheTTL)*time.Second)
// Setup configuration hot-reloading
reloadCh := make(chan bool)
if err := config.WatchConfig(*configPath, cfg, reloadCh); err != nil {
log.Error("Failed to watch config file", map[string]any{"error": err.Error()})
}
// Create HTTP server with middlewares
srv := &http.Server{
Addr: ":" + strconv.Itoa(cfg.Port),
Handler: middleware.Chain(
middleware.RequestID(),
middleware.Logger(log),
middleware.CORS(),
middleware.Timeout(30*time.Second),
middleware.Recovery(log),
)(http.HandlerFunc(server.HandleRequest)),
}
// Channel to listen for errors coming from the listener
serverErrors := make(chan error, 1)
// Start the server
go func() {
log.Info("Server listening", map[string]any{"address": srv.Addr})
serverErrors <- srv.ListenAndServe()
}()
// Channel to listen for config reload events
go func() {
for range reloadCh {
log.Info("Configuration reloaded")
// Clear the response cache when config changes
server.ClearCache()
}
}()
// Channel to listen for interrupt signals
shutdown := make(chan os.Signal, 1)
signal.Notify(shutdown, os.Interrupt, syscall.SIGTERM)
// Blocking main and waiting for shutdown or server error
select {
case err := <-serverErrors:
if err != nil && err != http.ErrServerClosed {
log.Error("Server error", map[string]any{"error": err.Error()})
}
case sig := <-shutdown:
log.Info("Shutdown signal received", map[string]any{
"signal": sig.String(),
})
// Give outstanding requests a deadline for completion
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
// Gracefully shutdown the server
if err := srv.Shutdown(ctx); err != nil {
log.Error("Graceful shutdown failed", map[string]any{"error": err.Error()})
srv.Close()
}
}
}