backend structure build

This commit is contained in:
2025-12-23 18:38:44 +00:00
parent 861e0f65c3
commit e7f55839eb
8 changed files with 702 additions and 27 deletions

View File

@@ -1,8 +1,6 @@
package api
import (
"net/http"
"github.com/bams/backend/internal/logger"
"github.com/bams/backend/internal/services"
"github.com/gorilla/mux"
@@ -11,7 +9,8 @@ import (
func NewRouter(sm *services.ServiceManager, log *logger.Logger) *mux.Router {
router := mux.NewRouter()
// Middleware
// Middleware (order matters)
router.Use(recoveryMiddleware(log))
router.Use(loggingMiddleware(log))
router.Use(corsMiddleware())
@@ -42,6 +41,8 @@ func NewRouter(sm *services.ServiceManager, log *logger.Logger) *mux.Router {
v1.HandleFunc("/iscsi/targets/{id}", handleUpdateTarget(sm)).Methods("PUT")
v1.HandleFunc("/iscsi/targets/{id}", handleDeleteTarget(sm)).Methods("DELETE")
v1.HandleFunc("/iscsi/targets/{id}/apply", handleApplyTarget(sm)).Methods("POST")
v1.HandleFunc("/iscsi/targets/{id}/luns", handleAddLUN(sm)).Methods("POST")
v1.HandleFunc("/iscsi/targets/{id}/luns/{lun}", handleRemoveLUN(sm)).Methods("DELETE")
v1.HandleFunc("/iscsi/sessions", handleListSessions(sm)).Methods("GET")
// Bacula integration
@@ -61,27 +62,3 @@ func NewRouter(sm *services.ServiceManager, log *logger.Logger) *mux.Router {
return router
}
func loggingMiddleware(log *logger.Logger) mux.MiddlewareFunc {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
log.Info("HTTP request", "method", r.Method, "path", r.URL.Path)
next.ServeHTTP(w, r)
})
}
}
func corsMiddleware() mux.MiddlewareFunc {
return func(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")
if r.Method == "OPTIONS" {
w.WriteHeader(http.StatusOK)
return
}
next.ServeHTTP(w, r)
})
}
}