[DEPRECATED] Go implementation of plcbundle
1package server
2
3import (
4 "net/http"
5
6 "github.com/goccy/go-json"
7)
8
9// corsMiddleware adds CORS headers
10func corsMiddleware(next http.Handler) http.Handler {
11 return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
12 // Skip CORS for WebSocket upgrade requests
13 if r.Header.Get("Upgrade") == "websocket" {
14 next.ServeHTTP(w, r)
15 return
16 }
17
18 // Set CORS headers for all requests
19 w.Header().Set("Access-Control-Allow-Origin", "*")
20 w.Header().Set("Access-Control-Allow-Methods", "GET, POST, OPTIONS")
21 w.Header().Set("Access-Control-Allow-Headers", "Content-Type, Authorization")
22 w.Header().Set("Access-Control-Max-Age", "86400")
23 w.Header().Set("Access-Control-Expose-Headers",
24 "X-Bundle-Number, X-Position, X-Global-Position, X-Pointer, "+
25 "X-Operation-DID, X-Operation-CID, X-Load-Time-Ms, X-Total-Time-Ms, "+
26 "X-Resolution-Time-Ms, X-Resolution-Source, X-Index-Time-Ms")
27
28 // Handle OPTIONS preflight - return immediately WITHOUT calling handler
29 if r.Method == "OPTIONS" {
30 w.WriteHeader(http.StatusNoContent) // 204
31 return // STOP HERE - don't call next
32 }
33
34 // Only call handler for non-OPTIONS requests
35 next.ServeHTTP(w, r)
36 })
37}
38
39// sendJSON sends a JSON response
40func sendJSON(w http.ResponseWriter, statusCode int, data interface{}) {
41 w.Header().Set("Content-Type", "application/json")
42
43 jsonData, err := json.Marshal(data)
44 if err != nil {
45 w.WriteHeader(500)
46 w.Write([]byte(`{"error":"failed to marshal JSON"}`))
47 return
48 }
49
50 w.WriteHeader(statusCode)
51 w.Write(jsonData)
52}