newsbot-api/cmd/server.go

91 lines
2.0 KiB
Go

package main
import (
"context"
"database/sql"
"errors"
"fmt"
"os"
_ "github.com/glebarez/go-sqlite"
"github.com/pressly/goose/v3"
"git.jamestombleson.com/jtom38/newsbot-api/docs"
v1 "git.jamestombleson.com/jtom38/newsbot-api/internal/handler/v1"
"git.jamestombleson.com/jtom38/newsbot-api/internal/services"
"git.jamestombleson.com/jtom38/newsbot-api/internal/services/cron"
)
// @title NewsBot collector
// @version 0.1
// @BasePath /api
// @securityDefinitions.apikey Bearer
// @in header
// @name Authorization
// @description Type "Bearer" followed by a space and JWT token.
func main() {
ctx := context.Background()
cfg := services.NewConfig()
configs := services.GetEnvConfig()
address := cfg.GetConfig(services.ServerAddress)
docs.SwaggerInfo.Host = fmt.Sprintf("%v:8081", address)
db, err := sql.Open("sqlite", "newsbot.db")
if err != nil {
panic(err)
}
err = migrateDatabase(db)
if err != nil {
fmt.Print(err)
}
c := cron.NewScheduler(ctx, db)
c.Start()
server := v1.NewServer(ctx, configs, db)
fmt.Println("API is online and waiting for requests.")
fmt.Printf("API: http://%v:8081/api\r\n", configs.ServerAddress)
fmt.Printf("Swagger: http://%v:8081/swagger/index.html\r\n", configs.ServerAddress)
server.Router.Start(":8081")
}
func migrateDatabase(db *sql.DB) error {
err := goose.SetDialect("sqlite3")
if err != nil {
panic(err)
}
err = goose.Up(db, "../internal/database/migrations")
if err != nil {
panic(err)
}
_, err = os.Stat("./migrations")
if err == nil {
err = goose.Up(db, "../internal/database/migrations")
if err != nil {
panic(err)
}
return nil
}
_, err = os.Stat("../internal/database/migrations")
if err == nil {
err = goose.Up(db, "../internal/database/migrations")
if err != nil {
panic(err)
}
return nil
}
return errors.New("failed to find the migration files")
}