package main import ( "fmt" _ "github.com/lib/pq" "log" "net/http" "os" "git.minhas.io/asara/sudoscientist-go-backend/packages/auth" "git.minhas.io/asara/sudoscientist-go-backend/packages/blog" "git.minhas.io/asara/sudoscientist-go-backend/packages/database" "git.minhas.io/asara/sudoscientist-go-backend/packages/users" "github.com/go-chi/chi" "github.com/go-chi/chi/middleware" "github.com/go-chi/cors" "github.com/go-chi/jwtauth" "github.com/go-chi/render" ) func main() { // initiate the database db, _ := database.NewDB() defer db.Close() auth.DB = db users.DB = db blog.DB = db // initiate jwt token auth.TokenAuth = jwtauth.New("HS256", []byte(os.Getenv("JWT_SECRET")), nil) users.TokenAuth = auth.TokenAuth blog.TokenAuth = auth.TokenAuth // initilize auth for email verification auth.Init() // initiate the routes router := Routes() walkFunc := func(method string, route string, handler http.Handler, middlewares ...func(http.Handler) http.Handler) error { fmt.Printf("%s %s\n", method, route) return nil } if err := chi.Walk(router, walkFunc); err != nil { log.Panicf("Logging err: %s\n", err.Error()) } // start server apiPort := fmt.Sprintf(":%s", os.Getenv("API_PORT")) log.Fatal(http.ListenAndServe(apiPort, router)) } func Routes() *chi.Mux { router := chi.NewRouter() cors := cors.New(cors.Options{ AllowedOrigins: []string{"https://sudoscientist.com", "https://www.sudoscientist.com"}, AllowedMethods: []string{"GET", "POST", "PUT", "DELETE", "PATCH", "OPTIONS"}, AllowedHeaders: []string{"Accept", "Authorization", "Content-Type", "X-CSRF-Token"}, AllowCredentials: true, MaxAge: 360, }) router.Use( cors.Handler, render.SetContentType(render.ContentTypeJSON), middleware.Logger, middleware.DefaultCompress, middleware.RedirectSlashes, middleware.Recoverer, ) router.Route("/v1", func(r chi.Router) { r.Mount("/api/auth", auth.Routes()) r.Mount("/api/blog", blog.Routes()) r.Mount("/api/users", users.Routes()) }) return router }