Files
sim-link/server/routes/router.go
2026-02-22 17:08:11 -05:00

98 lines
2.3 KiB
Go

package routes
import (
"database/sql"
"net/http"
"strings"
"net/url"
)
type Router struct {
DB *sql.DB
}
func NewRouter(db *sql.DB) *Router {
return &Router{DB: db}
}
func (rt *Router) Register(mux *http.ServeMux) {
mux.HandleFunc("/api/simulations", rt.handleSimulationsBase)
mux.HandleFunc("/api/simulations/", rt.handleSimulationsPath)
}
func (rt *Router) handleSimulationsBase(w http.ResponseWriter, r *http.Request) {
if r.Method == "OPTIONS" {
rt.OptionsHandler(w, r)
return
}
if r.Method == "GET" {
rt.GetSimulations(w, r)
} else {
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
}
}
func (rt *Router) handleSimulationsPath(w http.ResponseWriter, r *http.Request) {
if r.Method == "OPTIONS" {
rt.OptionsHandler(w, r)
return
}
pathParts := strings.Split(strings.Trim(r.URL.Path[len("/api/simulations/"):], "/"), "/")
if len(pathParts) == 0 || pathParts[0] == "" {
http.Error(w, "Not found", http.StatusNotFound)
return
}
if pathParts[0] == "create" && r.Method == "POST" {
rt.CreateSimulation(w, r)
return
}
idStr := pathParts[0]
if len(pathParts) == 1 {
if r.Method == "GET" {
rt.GetSimulationDetails(w, r, idStr)
} else if r.Method == "DELETE" {
rt.DeleteSimulation(w, r, idStr)
} else {
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
}
return
}
if len(pathParts) > 1 {
action := pathParts[1]
if r.Method == "PUT" && action == "time" {
rt.UpdateSimulationTime(w, r, idStr)
return
}
if r.Method == "PUT" && action == "rename" {
rt.RenameSimulation(w, r, idStr)
return
}
if r.Method == "PUT" && action == "hardware" {
rt.UpdateSimulationHardware(w, r, idStr)
return
}
if r.Method == "POST" && action == "upload" {
rt.UploadSimulationResource(w, r, idStr)
return
}
if r.Method == "DELETE" && action == "resources" && len(pathParts) > 2 {
fileName, _ := url.PathUnescape(pathParts[2])
rt.DeleteSimulationResource(w, r, idStr, fileName)
return
}
}
http.Error(w, "Not found", http.StatusNotFound)
}
func (rt *Router) OptionsHandler(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set("Access-Control-Allow-Methods", "GET, PUT, POST, DELETE, OPTIONS")
w.WriteHeader(http.StatusOK)
}