-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
89 lines (76 loc) · 2.59 KB
/
main.go
File metadata and controls
89 lines (76 loc) · 2.59 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
package main
import (
"context"
"fmt"
"net/http"
"os"
"os/signal"
"strconv"
"strings"
"syscall"
"time"
"github.com/TrueBlocks/trueblocks-core/src/apps/chifra/pkg/logger"
"github.com/TrueBlocks/trueblocks-dalle/v2/pkg/storage"
)
func main() {
app := NewApp()
// Fail fast if required OpenAI key missing (before starting server)
if os.Getenv("OPENAI_API_KEY") == "" {
fmt.Fprintln(os.Stderr, "WARNING: OPENAI_API_KEY not set; image generation will be skipped.")
}
// Initialize circuit breaker for OpenAI
circuitBreaker := NewCircuitBreaker(5, 30*time.Second)
// Initialize health checker with circuit breaker
GetHealthChecker().SetCircuitBreaker(circuitBreaker)
mux := http.NewServeMux()
// Apply middleware to all handlers
mux.HandleFunc("/", WrapWithMiddleware(app.handleDefault, circuitBreaker))
mux.HandleFunc("/dalle/", WrapWithMiddleware(app.handleDalleDress, circuitBreaker))
mux.HandleFunc("/series", WrapWithMiddleware(app.handleSeries, circuitBreaker))
mux.HandleFunc("/series/", WrapWithMiddleware(app.handleSeries, circuitBreaker))
mux.HandleFunc("/health", WrapWithMiddleware(app.handleHealth, circuitBreaker))
mux.HandleFunc("/metrics", WrapWithMiddleware(app.handleMetrics, circuitBreaker))
mux.HandleFunc("/preview", WrapWithMiddleware(app.handlePreview, circuitBreaker))
mux.Handle("/files/", http.StripPrefix("/files/", http.FileServer(http.Dir(storage.OutputDir()))))
startStatusPrinter(0)
port := getPort()
srv := &http.Server{
Addr: port,
Handler: mux,
ReadHeaderTimeout: 10 * time.Second, // mitigates Slowloris (gosec G112)
ReadTimeout: 30 * time.Second,
WriteTimeout: 60 * time.Second,
IdleTimeout: 120 * time.Second,
}
// Graceful shutdown
go func() {
logger.InfoG(fmt.Sprintf("Starting server on %s", port))
if err := srv.ListenAndServe(); err != nil && err != http.ErrServerClosed {
logger.InfoR(fmt.Sprintf("Server error: %v", err))
}
}()
quit := make(chan os.Signal, 1)
signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)
<-quit
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
if err := srv.Shutdown(ctx); err != nil {
_ = srv.Close()
}
}
func getPort() string {
port := ":8080"
if len(os.Args) > 1 && strings.Contains(os.Args[1], "--port=") {
isNumeric := func(s string) bool {
_, err := strconv.ParseFloat(s, 64)
return err == nil
}
n := strings.ReplaceAll(os.Args[1], "--port=", "")
if !isNumeric(n) {
fmt.Fprintln(os.Stderr, "WARNING: invalid port number, falling back to :8080 =>", n)
} else {
port = ":" + n
}
}
return port
}