-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhttp.go
More file actions
280 lines (242 loc) · 7.09 KB
/
Copy pathhttp.go
File metadata and controls
280 lines (242 loc) · 7.09 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
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
package main
import (
"context"
"encoding/json"
"fmt"
"log"
"net/http"
"os"
"os/signal"
"path/filepath"
"strings"
"syscall"
"time"
)
// CacheStats represents cache statistics
type CacheStats struct {
TotalRequests int64 `json:"total_requests"`
CacheHits int64 `json:"cache_hits"`
CacheMisses int64 `json:"cache_misses"`
HitRatio float64 `json:"hit_ratio"`
NotFound int64 `json:"not_found_404"`
ServerErrors int64 `json:"server_errors_5xx"`
OtherErrors int64 `json:"other_errors"`
FileCount int64 `json:"file_count"`
CacheSize int64 `json:"cache_size_bytes"`
}
// HealthStatus represents service health information
type HealthStatus struct {
Status string `json:"status"`
Uptime string `json:"uptime"`
DataDir string `json:"data_dir"`
CacheFiles int64 `json:"cache_files"`
CacheSize int64 `json:"cache_size_bytes"`
MaxCacheAge int `json:"max_cache_age_hours"`
CronSchedule string `json:"cron_schedule"`
}
// CacheEntry represents a single cached file
type CacheEntry struct {
Filename string `json:"filename"`
Size int64 `json:"size"`
ModTime string `json:"mod_time"`
}
// CacheListResponse represents the response for listing cache entries
type CacheListResponse struct {
Count int `json:"count"`
Entries []CacheEntry `json:"entries"`
}
var startTime = time.Now()
// handleHealth returns service health status
func handleHealth(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
health := HealthStatus{
Status: "healthy",
Uptime: time.Since(startTime).String(),
DataDir: args.dataDir,
CacheFiles: getFilesCount(),
CacheSize: getSizeCount(),
MaxCacheAge: args.maxCacheAge,
CronSchedule: args.cronSchedule,
}
json.NewEncoder(w).Encode(health)
}
// handleCacheStats returns current cache statistics
func handleCacheStats(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
totalReq := getRequestsCount()
hits := getHitsCount()
misses := getMissesCount()
notFound := getNotFoundCount()
serverErrors := getServerErrCount()
otherErrors := getErrorsCount()
hitRatio := 0.0
if totalReq > 0 {
hitRatio = float64(hits) / float64(totalReq)
}
stats := CacheStats{
TotalRequests: totalReq,
CacheHits: hits,
CacheMisses: misses,
HitRatio: hitRatio,
NotFound: notFound,
ServerErrors: serverErrors,
OtherErrors: otherErrors,
FileCount: getFilesCount(),
CacheSize: getSizeCount(),
}
json.NewEncoder(w).Encode(stats)
}
// handleCacheList lists all cached items
func handleCacheList(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
files, err := os.ReadDir(args.dataDir)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
json.NewEncoder(w).Encode(map[string]string{
"error": fmt.Sprintf("Error reading cache dir: %s", err.Error()),
})
incErrors()
return
}
entries := []CacheEntry{}
for _, file := range files {
if !file.IsDir() {
fileInfo, _ := file.Info()
entries = append(entries, CacheEntry{
Filename: file.Name(),
Size: fileInfo.Size(),
ModTime: fileInfo.ModTime().String(),
})
}
}
response := CacheListResponse{
Count: len(entries),
Entries: entries,
}
json.NewEncoder(w).Encode(response)
}
// handleCacheDelete handles cache deletion
func handleCacheDelete(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
if r.Method != http.MethodDelete {
w.WriteHeader(http.StatusMethodNotAllowed)
json.NewEncoder(w).Encode(map[string]string{
"error": "Only DELETE method allowed",
})
return
}
// Check if specific cache key is provided
key := strings.TrimPrefix(r.URL.Path, "/api/cache/delete/")
if key != "" && key != r.URL.Path {
// Delete specific cache entry
filename := filepath.Join(args.dataDir, key)
// Security check: ensure we're only accessing files in dataDir
absDataDir, _ := filepath.Abs(args.dataDir)
absFilename, _ := filepath.Abs(filename)
if !strings.HasPrefix(absFilename, absDataDir) {
w.WriteHeader(http.StatusForbidden)
json.NewEncoder(w).Encode(map[string]string{
"error": "Invalid cache key",
})
return
}
file, err := os.Stat(filename)
if err != nil {
w.WriteHeader(http.StatusNotFound)
json.NewEncoder(w).Encode(map[string]string{
"error": "Cache entry not found",
})
return
}
if err := os.Remove(filename); err != nil {
w.WriteHeader(http.StatusInternalServerError)
json.NewEncoder(w).Encode(map[string]string{
"error": fmt.Sprintf("Failed to delete cache entry: %s", err.Error()),
})
incErrors()
return
}
subSize(file.Size())
decFiles()
log.Printf("Deleted cache entry: %s", key)
json.NewEncoder(w).Encode(map[string]interface{}{
"status": "deleted",
"key": key,
"size": file.Size(),
})
} else {
// Delete all cache entries
files, err := os.ReadDir(args.dataDir)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
json.NewEncoder(w).Encode(map[string]string{
"error": fmt.Sprintf("Error reading cache dir: %s", err.Error()),
})
incErrors()
return
}
deleted := 0
var totalSize int64
for _, file := range files {
if !file.IsDir() {
fileInfo, _ := file.Info()
fullPath := filepath.Join(args.dataDir, file.Name())
if err := os.Remove(fullPath); err != nil {
log.Printf("Error deleting %s: %s", fullPath, err)
incErrors()
continue
}
subSize(fileInfo.Size())
decFiles()
totalSize += fileInfo.Size()
deleted++
}
}
log.Printf("Cleared entire cache: deleted %d files", deleted)
json.NewEncoder(w).Encode(map[string]interface{}{
"status": "cleared",
"deleted": deleted,
"size_freed": totalSize,
})
}
}
func StartHTTP() {
port := fmt.Sprintf(":%d", args.httpPort)
log.Printf("Starting HTTP server on %s", port)
// Create a mux for routing incoming requests
myHandler := http.NewServeMux()
// API endpoints
myHandler.HandleFunc("/api/health", handleHealth)
myHandler.HandleFunc("/api/cache/stats", handleCacheStats)
myHandler.HandleFunc("/api/cache/list", handleCacheList)
myHandler.HandleFunc("/api/cache/delete", handleCacheDelete)
myHandler.HandleFunc("/api/cache/delete/", handleCacheDelete)
// Proxy endpoint (all other paths)
myHandler.HandleFunc("/", handleRequest)
s := &http.Server{
Addr: port,
Handler: myHandler,
ReadTimeout: 60 * time.Second,
WriteTimeout: 60 * time.Second,
MaxHeaderBytes: 1 << 20,
}
done := make(chan os.Signal, 1)
signal.Notify(done, os.Interrupt, syscall.SIGINT, syscall.SIGTERM)
go func() {
if err := s.ListenAndServe(); err != nil && err != http.ErrServerClosed {
log.Fatalf("listen: %s\n", err)
}
}()
log.Print("Server Started")
<-done
log.Print("Server Stopped")
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer func() {
// extra handling here
cancel()
}()
if err := s.Shutdown(ctx); err != nil {
log.Fatalf("Server Shutdown Failed:%+v", err)
}
log.Print("Server Exited Properly")
}