package service import ( "net/http" "git.umbrella.haus/ae/notatest/internal/data" "github.com/go-chi/chi/v5" "github.com/go-chi/chi/v5/middleware" "github.com/go-chi/cors" "github.com/jackc/pgx/v5" "github.com/rs/zerolog/log" ) type SvcConfig struct { JWTSecret string CSRFSecret string IsProd bool Domain string FrontendURL string } func (sc *SvcConfig) allowedOrigins() []string { var allowed []string if sc.IsProd { allowed = []string{sc.FrontendURL} } else { allowed = []string{"http://localhost:5173"} } log.Debug().Msgf("CORS allowedOrigins: %v", allowed) return allowed } func Run(conn *pgx.Conn, q *data.Queries, config SvcConfig) error { r := chi.NewRouter() if !config.IsProd { log.Warn().Msg("Running in *INSECURE* development mode") } authRouter := authResource{ Config: config, Users: q, Tokens: q, } notesRouter := notesResource{ Config: config, Notes: q, } // Global middlewares r.Use(middleware.RequestID) r.Use(middleware.RealIP) r.Use(loggerMiddleware(&log.Logger)) r.Use(cors.Handler(cors.Options{ AllowedOrigins: config.allowedOrigins(), AllowedMethods: []string{"GET", "POST", "PUT", "DELETE", "OPTIONS"}, AllowedHeaders: []string{"Accept", "Authorization", "Content-Type", "X-CSRF-Token"}, ExposedHeaders: []string{"List"}, AllowCredentials: true, MaxAge: 300, })) r.Use(middleware.Recoverer) r.Use(middleware.AllowContentType("application/json")) // Routes grouped by functionality (we must prefix the API routes with `/api` // as the domain will be the same for the front and back ends) r.Route("/api", func(r chi.Router) { r.Mount("/auth", authRouter.Routes()) r.Mount("/notes", notesRouter.Routes()) r.Get("/ping", ping) }) log.Info().Msg("Starting server on :8080") return http.ListenAndServe(":8080", r) } func ping(w http.ResponseWriter, r *http.Request) { respondJSON(w, http.StatusOK, map[string]string{ "message": "pong", }) }