-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.go
More file actions
151 lines (128 loc) · 3.66 KB
/
Copy pathserver.go
File metadata and controls
151 lines (128 loc) · 3.66 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
package main
import (
"embed"
"io/fs"
"log"
"net/http"
"strings"
"time"
)
//go:embed static/*
var staticFS embed.FS
// Server holds the HTTP server and dependencies
type Server struct {
config *Config
storage Storage
broadcaster *SSEBroadcaster
handlers *Handlers
ac *AccessControl
rateLimiter *RateLimiter
}
// NewServer creates a new server instance
func NewServer(config *Config) (*Server, error) {
// Create access control
ac, err := NewAccessControl(config.AllowCIDRs, config.TrustProxy)
if err != nil {
return nil, err
}
// Create storage
var storage Storage
if config.Persist {
storage, err = NewSQLiteStorage(config.DBPath, config.MaxSnippets)
if err != nil {
return nil, err
}
log.Printf("Using SQLite storage: %s", config.DBPath)
} else {
storage = NewMemoryStorage(config.MaxSnippets)
log.Printf("Using in-memory storage (max %d snippets)", config.MaxSnippets)
}
// Create SSE broadcaster
broadcaster := NewSSEBroadcaster(1000) // max 1000 concurrent SSE connections
// Create handlers
handlers := NewHandlers(storage, broadcaster, config.AdminToken, config.MaxSnippetBytes)
// Create rate limiter (10 requests/second, burst of 20)
rateLimiter := NewRateLimiter(10, 20)
return &Server{
config: config,
storage: storage,
broadcaster: broadcaster,
handlers: handlers,
ac: ac,
rateLimiter: rateLimiter,
}, nil
}
// Start starts the HTTP server
func (s *Server) Start() error {
mux := http.NewServeMux()
// API routes
mux.HandleFunc("/health", s.handlers.HealthCheck)
mux.HandleFunc("/api/snippets", s.apiSnippetsHandler)
mux.HandleFunc("/api/snippets/latest", s.handlers.GetLatestSnippet)
mux.HandleFunc("/api/stream", s.handlers.SSEHandler)
// Image serving (matches /api/snippets/{id}/image)
mux.HandleFunc("/api/snippets/", s.imageHandler)
// Static files
staticSub, err := fs.Sub(staticFS, "static")
if err != nil {
return err
}
fileServer := http.FileServer(http.FS(staticSub))
mux.Handle("/", fileServer)
// Build middleware chain
handler := http.Handler(mux)
handler = RequestLogger(handler)
handler = SecurityHeaders(handler)
handler = s.rateLimiter.Middleware(s.ac)(handler)
handler = s.ac.Middleware(handler)
// Start TTL cleanup goroutine if enabled
if s.config.TTLHours > 0 {
go s.cleanupLoop()
}
addr := s.config.Bind + ":" + s.config.Port
log.Printf("Starting server on %s", addr)
log.Printf("Web UI: http://%s", addr)
server := &http.Server{
Addr: addr,
Handler: handler,
ReadTimeout: 30 * time.Second,
WriteTimeout: 30 * time.Second,
IdleTimeout: 120 * time.Second,
}
return server.ListenAndServe()
}
// apiSnippetsHandler routes to the appropriate handler based on method
func (s *Server) apiSnippetsHandler(w http.ResponseWriter, r *http.Request) {
switch r.Method {
case http.MethodGet:
s.handlers.GetSnippets(w, r)
case http.MethodPost:
s.handlers.CreateSnippet(w, r)
case http.MethodDelete:
s.handlers.ClearSnippets(w, r)
default:
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
}
}
// imageHandler handles requests for /api/snippets/{id}/image
func (s *Server) imageHandler(w http.ResponseWriter, r *http.Request) {
if strings.HasSuffix(r.URL.Path, "/image") {
s.handlers.ServeImage(w, r)
} else {
http.NotFound(w, r)
}
}
// cleanupLoop periodically removes old snippets
func (s *Server) cleanupLoop() {
ticker := time.NewTicker(time.Hour)
defer ticker.Stop()
for range ticker.C {
if err := s.storage.Cleanup(s.config.TTLHours); err != nil {
log.Printf("Cleanup error: %v", err)
}
}
}
// Close closes the server and its resources
func (s *Server) Close() error {
return s.storage.Close()
}