package main import ( "fmt" "log" "net/http" "os" "git.xdrm.io/go/aicra" "git.xdrm.io/go/aicra/datatype/builtin" "git.xdrm.io/go/articles-api/pkg/handlers" "git.xdrm.io/go/articles-api/pkg/persistence/drivers/sqlite" "git.xdrm.io/go/articles-api/pkg/persistence/storage" ) func main() { if err := run(); err != nil { log.Fatalf("%s", err) } } func run() error { // 1. prepare builder builder := &aicra.Builder{} builder.AddType(builtin.AnyDataType{}) builder.AddType(builtin.BoolDataType{}) builder.AddType(builtin.UintDataType{}) builder.AddType(builtin.IntDataType{}) builder.AddType(builtin.StringDataType{}) // 2. setup with configuration file config, err := os.OpenFile("api.json", os.O_RDONLY, os.ModePerm) if err != nil { return fmt.Errorf("cannot open config file: %w", err) } err = builder.Setup(config) config.Close() if err != nil { return fmt.Errorf("cannot setup builder: %w", err) } // 3. connect to storage db := &sqlite.Storage{} err = db.Open() if err != nil { return fmt.Errorf("cannot open database: %w", err) } defer db.Close() // 3. create services SetupRoutes(builder, db) // 4. create http server server, err := builder.Build() if err != nil { return fmt.Errorf("cannot build server: %w", err) } // 5. listen and serve log.Printf("[server] listening to '%s'", ":4242") return http.ListenAndServe(":4242", server) } func SetupRoutes(b *aicra.Builder, db storage.T) error { app := &handlers.App{Db: db} if err := b.Bind(http.MethodGet, "/articles", app.HandleGetAllArticles); err != nil { return err } if err := b.Bind(http.MethodGet, "/user/{id}/articles", app.HandleGetArticlesByAuthor); err != nil { return err } if err := b.Bind(http.MethodGet, "/article/{id}", app.HandleGetArticleByID); err != nil { return err } if err := b.Bind(http.MethodPost, "/article/{author}", app.HandleCreateArticle); err != nil { return err } if err := b.Bind(http.MethodDelete, "/article/{id}", app.HandleDeleteArticle); err != nil { return err } if err := b.Bind(http.MethodPost, "/article/{id}/up", app.HandleUpVote); err != nil { return err } if err := b.Bind(http.MethodPost, "/article/{id}/down", app.HandleDownVote); err != nil { return err } if err := b.Bind(http.MethodGet, "/user/{id}", app.HandleGetUserByID); err != nil { return err } if err := b.Bind(http.MethodGet, "/users", app.HandleGetAllUsers); err != nil { return err } if err := b.Bind(http.MethodPost, "/user", app.HandleCreateUser); err != nil { return err } if err := b.Bind(http.MethodPut, "/user/{id}", app.HandleUpdateUser); err != nil { return err } if err := b.Bind(http.MethodDelete, "/user/{id}", app.HandleDeleteUser); err != nil { return err } return nil }