diff options
author | Alexander NeonXP Kiryukhin <i@neonxp.ru> | 2024-07-29 02:47:35 +0300 |
---|---|---|
committer | Alexander NeonXP Kiryukhin <i@neonxp.ru> | 2024-07-29 02:47:35 +0300 |
commit | 96e2ce2e9d363a6296f9411ecb00168520258874 (patch) | |
tree | 09aa7fffe10eab84ae0edd39e570355984ba0148 /app/cmd | |
parent | 12ed72e4e1da181a6c87319a50d3b4142788b4c0 (diff) |
Отказ от echo
Diffstat (limited to 'app/cmd')
-rw-r--r-- | app/cmd/migrate.go | 99 | ||||
-rw-r--r-- | app/cmd/root.go | 1 | ||||
-rw-r--r-- | app/cmd/serve.go | 90 | ||||
-rw-r--r-- | app/cmd/user.go | 17 |
4 files changed, 48 insertions, 159 deletions
diff --git a/app/cmd/migrate.go b/app/cmd/migrate.go deleted file mode 100644 index 95a1dc3..0000000 --- a/app/cmd/migrate.go +++ /dev/null @@ -1,99 +0,0 @@ -package cmd - -import ( - "database/sql" - "fmt" - - "github.com/golang-migrate/migrate/v4" - "github.com/golang-migrate/migrate/v4/database/sqlite" - "github.com/golang-migrate/migrate/v4/source/iofs" - "github.com/spf13/cobra" - "gitrepo.ru/neonxp/gorum/migrations" -) - -var migrateCmd = &cobra.Command{ - Use: "migrate", - Short: "Migrate db", - Long: `Up and down migrations`, -} - -func init() { - migrateCmd.AddCommand( - &cobra.Command{ - Use: "up", - Short: "Migrate up", - Long: `Up migrations`, - RunE: up, - }, - &cobra.Command{ - Use: "down", - Short: "Migrate down", - Long: `Down migrations`, - RunE: down, - }, - &cobra.Command{ - Use: "drop", - Short: "Drop db", - Long: `Deletes everything in the database`, - RunE: drop, - }, - ) -} - -func up(_ *cobra.Command, _ []string) error { - m, err := initMigrate() - if err != nil { - return fmt.Errorf("open migration failed: %w", err) - } - defer m.Close() - if err := m.Up(); err != nil && err != migrate.ErrNoChange { - return fmt.Errorf("do migration failed: %w", err) - } - - return nil -} - -func down(_ *cobra.Command, _ []string) error { - m, err := initMigrate() - if err != nil { - return fmt.Errorf("open migration failed: %w", err) - } - defer m.Close() - if err := m.Down(); err != nil && err != migrate.ErrNoChange { - return fmt.Errorf("do migration failed: %w", err) - } - - return nil -} - -func drop(_ *cobra.Command, _ []string) error { - m, err := initMigrate() - if err != nil { - return fmt.Errorf("open migration failed: %w", err) - } - defer m.Close() - if err := m.Drop(); err != nil && err != migrate.ErrNoChange { - return fmt.Errorf("do migration failed: %w", err) - } - - return nil -} - -func initMigrate() (*migrate.Migrate, error) { - db, err := sql.Open("sqlite3", dbFile) - if err != nil { - return nil, fmt.Errorf("open db failed: %w", err) - } - defer db.Close() - - driver, err := sqlite.WithInstance(db, &sqlite.Config{}) - if err != nil { - return nil, fmt.Errorf("failed create migration driver: %w", err) - } - sourceDriver, err := iofs.New(migrations.FS, ".") - if err != nil { - return nil, fmt.Errorf("failed open migrations: %w", err) - } - - return migrate.NewWithInstance("fs", sourceDriver, "sqlite3", driver) -} diff --git a/app/cmd/root.go b/app/cmd/root.go index 5803166..7d1c731 100644 --- a/app/cmd/root.go +++ b/app/cmd/root.go @@ -25,7 +25,6 @@ func init() { viper.BindPFlag("db", serverCmd.Flags().Lookup("db")) rootCmd.AddCommand(serverCmd) - rootCmd.AddCommand(migrateCmd) rootCmd.AddCommand(userCmd) } diff --git a/app/cmd/serve.go b/app/cmd/serve.go index e2d2843..578de1e 100644 --- a/app/cmd/serve.go +++ b/app/cmd/serve.go @@ -7,21 +7,19 @@ import ( "net" "net/http" - "github.com/labstack/echo-contrib/session" - "github.com/labstack/echo/v4" - echomiddleware "github.com/labstack/echo/v4/middleware" _ "github.com/mattn/go-sqlite3" - "github.com/michaeljs1990/sqlitestore" "github.com/spf13/cobra" "github.com/spf13/viper" "gitrepo.ru/neonxp/gorum/contextlib" - "gitrepo.ru/neonxp/gorum/db" - "gitrepo.ru/neonxp/gorum/middleware" + "gitrepo.ru/neonxp/gorum/controllers" + appmiddleware "gitrepo.ru/neonxp/gorum/middleware" "gitrepo.ru/neonxp/gorum/repository" - "gitrepo.ru/neonxp/gorum/routes" - "gitrepo.ru/neonxp/gorum/utils" "gitrepo.ru/neonxp/gorum/views" "gitrepo.ru/neonxp/gorum/views/assets" + "go.etcd.io/bbolt" + "go.neonxp.ru/mux" + "go.neonxp.ru/mux/middleware" + "go.neonxp.ru/mux/middleware/session" ) var ( @@ -57,7 +55,7 @@ func serve(ctx context.Context) error { ) ctx = context.WithValue(ctx, contextlib.ThemeKey, theme) - orm, err := db.GetDB(dbFile) + orm, err := bbolt.Open(dbFile, 0600, nil) if err != nil { return err } @@ -65,59 +63,51 @@ func serve(ctx context.Context) error { defer orm.Close() userRepo := repository.NewUser(orm) - nodeRepo := repository.NewNode(orm) + nodeRepo := repository.NewPost(orm) + topicRepo := repository.NewTopic(orm) - r := routes.NewRouter(userRepo, nodeRepo) - - e := echo.New() - - e.HideBanner = true - - e.HTTPErrorHandler = func(err error, c echo.Context) { - _ = utils.Render(c, views.ErrorPage(err)) + if err := topicRepo.Init(); err != nil { + return err } - - sessionStore, err := sqlitestore.NewSqliteStoreFromConnection(orm.DB, "sessions", "", 0, []byte(sessionSecret)) - if err != nil { - return fmt.Errorf("failed init session store: %w", err) + if err := userRepo.Init(); err != nil { + return err } - e.Use( - echomiddleware.Recover(), - echomiddleware.Gzip(), - // echomiddleware.CSRFWithConfig(echomiddleware.CSRFConfig{ - // Skipper: echomiddleware.DefaultSkipper, - // TokenLength: 32, - // TokenLookup: "form:" + echo.HeaderXCSRFToken, - // ContextKey: "csrf", - // CookieName: "_csrf", - // CookieMaxAge: 86400, - // }), - session.Middleware(sessionStore), - middleware.UserMiddleware(), - ) + r := controllers.NewRouter(userRepo, nodeRepo, topicRepo) - e.GET("/register", r.Register) - e.POST("/register", r.Register) - e.GET("/login", r.Login) - e.POST("/login", r.Login) - e.POST("/logout", r.Logout) + e := http.NewServeMux() - e.GET("/", r.Node) - e.GET("/p/:id", r.Node) - e.GET("/p/:id/new", r.NewPost) - e.POST("/p/:id/new", r.NewPost) - e.GET("/t/:id", r.Node) - e.GET("/t/:id/new", r.NewTopic) - e.POST("/t/:id/new", r.NewTopic) + mux.DefaultErrorHandler = func(err error) mux.Renderer { + return views.ErrorPage(err) + } - e.StaticFS("/assets", assets.FS) + e.HandleFunc("GET /register", r.Register) + e.HandleFunc("POST /register", r.Register) + e.HandleFunc("GET /login", r.Login) + e.HandleFunc("POST /login", r.Login) + e.HandleFunc("POST /logout", r.Logout) + + e.HandleFunc("GET /{$}", r.Index) + e.HandleFunc("GET /t/{id}", r.Topic) + e.HandleFunc("GET /t/new", r.NewTopic) + e.HandleFunc("POST /t/new", r.NewTopic) + e.HandleFunc("POST /p/new", r.NewPost) + + e.Handle("/assets/", http.StripPrefix("/assets", http.FileServerFS(assets.FS))) + + mh := mux.Use(e, + middleware.Logger(slog.Default()), + middleware.Recover(slog.Default()), + middleware.RequestID, + appmiddleware.UserMiddleware(), + session.Middleware(session.DefaultConfig, session.NewBoltStore(orm, []byte("sessions"))), + ) slog.InfoContext(ctx, "started gorum", slog.String("bind", listen)) server := http.Server{ Addr: listen, - Handler: e, + Handler: mh, ErrorLog: slog.NewLogLogger(slog.Default().Handler(), slog.LevelError), ConnContext: func(cctx context.Context, c net.Conn) context.Context { return ctx diff --git a/app/cmd/user.go b/app/cmd/user.go index 673c7b8..1f88c6f 100644 --- a/app/cmd/user.go +++ b/app/cmd/user.go @@ -6,9 +6,9 @@ import ( "os" "github.com/spf13/cobra" - "gitrepo.ru/neonxp/gorum/db" "gitrepo.ru/neonxp/gorum/models" "gitrepo.ru/neonxp/gorum/repository" + "go.etcd.io/bbolt" ) var userCmd = &cobra.Command{ @@ -21,7 +21,7 @@ var createUserCmd = &cobra.Command{ Args: cobra.ExactArgs(3), ArgAliases: []string{"username", "email", "role"}, RunE: func(cmd *cobra.Command, args []string) error { - orm, err := db.GetDB(dbFile) + orm, err := bbolt.Open(dbFile, 0600, nil) if err != nil { return fmt.Errorf("failed init db: %w", err) } @@ -40,12 +40,11 @@ var createUserCmd = &cobra.Command{ password, _ := reader.ReadString('\n') ur := repository.NewUser(orm) - id, err := ur.Create(cmd.Context(), email, password, username, iRole) - if err != nil { + if err := ur.Create(email, password, username, iRole); err != nil { return fmt.Errorf("failed create user: %w", err) } - fmt.Printf("Created user %s (id=%d, email=%s, role_id=%d)\n", username, id, email, iRole) + fmt.Printf("Created user %s (email=%s, role_id=%d)\n", username, email, iRole) return nil }, @@ -54,20 +53,20 @@ var createUserCmd = &cobra.Command{ var listUserCmd = &cobra.Command{ Use: "list", RunE: func(cmd *cobra.Command, args []string) error { - orm, err := db.GetDB(dbFile) + orm, err := bbolt.Open(dbFile, 0600, nil) if err != nil { return fmt.Errorf("failed init db: %w", err) } ur := repository.NewUser(orm) - users, err := ur.List(cmd.Context()) + users, err := ur.List() if err != nil { return err } - fmt.Printf("ID\tUsername\tEmail\tRole\n") + fmt.Printf("Username\tEmail\tRole\n") for _, u := range users { - fmt.Printf("%d\t%s\t%s\t%d\n", u.ID, u.Username, u.Email, u.Role) + fmt.Printf("%s\t%s\t%d\n", u.Username, u.Email, u.Role) } return nil |