-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathservice.go
More file actions
executable file
·94 lines (77 loc) · 2.41 KB
/
Copy pathservice.go
File metadata and controls
executable file
·94 lines (77 loc) · 2.41 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
package main
import (
"context"
"embed"
"fmt"
"html/template"
"log"
"net/http"
"time"
"github.com/gorilla/mux"
)
//go:embed web/templates/*
var templateFS embed.FS
// PrintServer manages the HTTP server and routes
type PrintServer struct {
httpServer *http.Server
config *Config
templates *template.Template
}
// NewPrintServer creates a new PrintServer instance
func NewPrintServer() *PrintServer {
tmpl, err := template.ParseFS(templateFS, "web/templates/*.html")
if err != nil {
log.Printf("Warning: Could not parse templates: %v", err)
tmpl = template.New("empty")
}
return &PrintServer{
config: LoadConfig(),
templates: tmpl,
}
}
// Start begins the HTTP server
func (ps *PrintServer) Start() error {
router := mux.NewRouter()
// API routes
api := router.PathPrefix("/api").Subrouter()
api.Use(corsMiddleware)
api.HandleFunc("/health", ps.HealthCheckHandler).Methods("GET", "OPTIONS")
api.HandleFunc("/printers", ps.ListPrintersHandler).Methods("GET", "OPTIONS")
api.HandleFunc("/config", ps.GetConfigHandler).Methods("GET", "OPTIONS")
api.HandleFunc("/config", ps.SetConfigHandler).Methods("POST", "OPTIONS")
api.HandleFunc("/print", ps.PrintHandler).Methods("POST", "OPTIONS")
// Web interface
router.HandleFunc("/", ps.SettingsPageHandler).Methods("GET")
router.HandleFunc("/settings", ps.SettingsPageHandler).Methods("GET")
ps.httpServer = &http.Server{
Addr: fmt.Sprintf(":%d", ps.config.Port),
Handler: router,
ReadTimeout: 15 * time.Second,
WriteTimeout: 15 * time.Second,
IdleTimeout: 60 * time.Second,
}
log.Printf("Starting server on port %d", ps.config.Port)
return ps.httpServer.ListenAndServe()
}
// Stop gracefully shuts down the server
func (ps *PrintServer) Stop() error {
if ps.httpServer != nil {
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
return ps.httpServer.Shutdown(ctx)
}
return nil
}
func corsMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS")
w.Header().Set("Access-Control-Allow-Headers", "Content-Type, Authorization")
w.Header().Set("Access-Control-Max-Age", "86400")
if r.Method == http.MethodOptions {
w.WriteHeader(http.StatusNoContent)
return
}
next.ServeHTTP(w, r)
})
}