[DEPRECATED] Go implementation of plcbundle
at main 100 lines 2.3 kB view raw
1package server 2 3import ( 4 "context" 5 "net/http" 6 "time" 7 8 "tangled.org/atscan.net/plcbundle-go/bundle" 9) 10 11// New creates a new HTTP server 12func New(manager *bundle.Manager, config *Config) *Server { 13 if config.Version == "" { 14 config.Version = "dev" 15 } 16 17 s := &Server{ 18 manager: manager, 19 addr: config.Addr, 20 config: config, 21 startTime: time.Now(), 22 } 23 24 handler := s.createHandler() 25 26 s.httpServer = &http.Server{ 27 Addr: config.Addr, 28 Handler: handler, 29 } 30 31 return s 32} 33 34// createHandler creates the HTTP handler with all routes 35func (s *Server) createHandler() http.Handler { 36 mux := http.NewServeMux() 37 38 // Specific routes first 39 mux.HandleFunc("GET /index.json", s.handleIndexJSON()) 40 mux.HandleFunc("GET /bundle/{number}", s.handleBundle()) 41 mux.HandleFunc("GET /data/{number}", s.handleBundleData()) 42 mux.HandleFunc("GET /jsonl/{number}", s.handleBundleJSONL()) 43 mux.HandleFunc("GET /op/{pointer}", s.handleOperation()) 44 mux.HandleFunc("GET /status", s.handleStatus()) 45 mux.HandleFunc("GET /debug/memory", s.handleDebugMemory()) 46 mux.HandleFunc("GET /debug/didindex", s.handleDebugDIDIndex()) 47 mux.HandleFunc("GET /debug/resolver", s.handleDebugResolver()) 48 49 // WebSocket 50 if s.config.EnableWebSocket { 51 mux.HandleFunc("GET /ws", s.handleWebSocket()) 52 } 53 54 // Sync mode endpoints 55 if s.config.SyncMode { 56 mux.HandleFunc("GET /mempool", s.handleMempool()) 57 } 58 59 // Root and DID resolver 60 mux.HandleFunc("GET /", func(w http.ResponseWriter, r *http.Request) { 61 path := r.URL.Path 62 63 if path == "/" { 64 s.handleRoot()(w, r) 65 return 66 } 67 68 if s.config.EnableResolver { 69 s.handleDIDRouting(w, r) 70 return 71 } 72 73 sendJSON(w, 404, map[string]string{"error": "not found"}) 74 }) 75 76 // Apply middleware in correct order: 77 handler := corsMiddleware(mux) 78 79 return handler 80} 81 82// ListenAndServe starts the HTTP server 83func (s *Server) ListenAndServe() error { 84 return s.httpServer.ListenAndServe() 85} 86 87// Shutdown gracefully shuts down the server 88func (s *Server) Shutdown(ctx context.Context) error { 89 return s.httpServer.Shutdown(ctx) 90} 91 92// GetStartTime returns when the server started 93func (s *Server) GetStartTime() time.Time { 94 return s.startTime 95} 96 97// Handler returns the configured HTTP handler 98func (s *Server) Handler() http.Handler { 99 return s.createHandler() 100}