1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.
  2. Anuncie Aqui
    Anuncie aqui você Também: fdantas@4each.com.br

Trouble Deploying Blog App with Go + Angular + PostgreSQL using Coolify

Discussão em 'Angular' iniciado por Grey, Setembro 14, 2024.

  1. Grey

    Grey Guest

    Hello to everyone out here, i hope you are doing great.

    I'm trying to deploy my blog app written in Go, Angular, and PostgreSQL. I chose Coolify as the deployment solution, but I'm having trouble contacting the API.

    Access to XMLHttpRequest at 'https://api.windysrl.net/check-username?name=s' from origin 'https://blog.windysrl.net' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.


    This is my docker-compose.yml file:

    version: '3.8'

    services:
    go-backend:
    build:
    context: ./API
    dockerfile: Dockerfile
    ports:
    - "3000:3000"
    environment:
    DB_HOST: ${DB_HOST}
    DB_PORT: ${DB_PORT}
    DB_USER: ${DB_USER}
    DB_PASSWORD: ${DB_PASSWORD}
    DB_NAME: ${DB_NAME}
    JWT_SECRET: ${JWT_SECRET}
    SMTP_HOST: ${SMTP_HOST}
    SMTP_PORT: ${SMTP_PORT}
    SMTP_USER: ${SMTP_USER}
    SMTP_PASS: ${SMTP_PASS}
    ENV: ${ENV}
    PROD_DOMAIN: ${PROD_DOMAIN}
    FRONTEND_PROD_DOMAIN: ${FRONTEND_PROD_DOMAIN}
    labels:
    - "traefik.enable=true"
    - "traefik.http.routers.api.rule=Host(`api.windysrl.net`)"
    - "traefik.http.routers.api.entrypoints=websecure"
    - "traefik.http.routers.api.tls.certresolver=myresolver"
    - "traefik.http.services.api.loadbalancer.server.port=3000"
    - "traefik.docker.network=traefik-public"

    angular-frontend:
    build:
    context: ./client
    dockerfile: Dockerfile
    ports:
    - "8081:80"
    environment:
    NODE_ENV: production
    labels:
    - "traefik.enable=true"
    - "traefik.http.routers.frontend.rule=Host(`blog.windysrl.net`)"
    - "traefik.http.routers.frontend.entrypoints=websecure"
    - "traefik.http.routers.frontend.tls.certresolver=myresolver"
    - "traefik.http.services.frontend.loadbalancer.server.port=80"
    - "traefik.docker.network=traefik-public"

    networks:
    traefik-public:
    external: true


    This is part of my Go application setup:

    type App struct {
    Router *fiber.App
    DB *sqlx.DB
    }

    func NewApp() *App {
    app := &App{}

    fxApp := fx.New(
    fx.Provide(
    // Provide various config
    loadConfig,
    connectDB,
    initFiberApp,
    // Repos
    repositories.NewUserRepository,
    repositories.NewArticleRepository,
    // Email Sender
    email.NewEmailSender,
    // Provide JWT secret from config
    func(cfg *config.Config) string {
    return cfg.JWTSecret
    },
    // Services
    services.NewAuthService,
    services.NewArticleService,
    // Controllers
    controllers.NewAuthController,
    controllers.NewArticleController,
    controllers.NewHealthCheckController,
    ),
    fx.Invoke(setupRoutes),
    )

    if err := fxApp.Err(); err != nil {
    fmt.Printf("Error starting fx app: %v\n", err)
    return nil
    }

    fxApp.Run()
    return app
    }

    func loadConfig() *config.Config {
    config.LoadConfig()
    return config.Cfg
    }

    func connectDB(cfg *config.Config) (*sqlx.DB, error) {
    dbURI := fmt.Sprintf(
    "postgres://%s:%s@%s:%s/%s?sslmode=disable",
    cfg.DBUser,
    cfg.DBPassword,
    cfg.DBHost,
    cfg.DBPort,
    cfg.DBName,
    )

    db, err := sqlx.Connect("postgres", dbURI)
    if err != nil {
    return nil, err
    }
    return db, nil
    }

    func initFiberApp() *fiber.App {
    app := fiber.New()

    app.Use(cors.New(cors.Config{
    AllowOrigins: "https://blog.windysrl.net",
    AllowMethods: "GET,POST,PUT,DELETE,OPTIONS",
    AllowHeaders: "Origin, Content-Type, Accept, Authorization",
    AllowCredentials: true,
    }))

    return app
    }

    func jwtMiddleware() fiber.Handler {
    return jwtware.New(jwtware.Config{
    SigningKey: []byte(config.Cfg.JWTSecret),
    TokenLookup: "header:Authorization",
    AuthScheme: "Bearer",
    ContextKey: "user",
    ErrorHandler: jwtError,
    })
    }

    func jwtError(c *fiber.Ctx, err error) error {
    return c.Status(fiber.StatusUnauthorized).JSON(fiber.Map{"error": "Unauthorized"})
    }

    func setupRoutes(
    app *fiber.App,
    authController *controllers.AuthController,
    articleController *controllers.ArticleController,
    healthCheckController *controllers.HealthCheckController,
    ) {
    // Public Routes
    app.Post("/register", authController.Register)
    app.Post("/login", authController.Login)
    app.Post("/request-password-reset", authController.RequestPasswordReset)
    app.Get("/reset-password", authController.ShowResetPasswordPage)
    app.Post("/reset-password", authController.ResetPassword)
    app.Get("/confirm", authController.ConfirmEmail)
    app.Get("/check-username", authController.CheckUsername)

    // Health Check Route
    app.Get("/health", healthCheckController.CheckHealth)

    // Protected Routes
    app.Use("/articles", jwtMiddleware())

    app.Post("/articles", articleController.CreateArticle)
    app.Get("/articles", articleController.GetArticles)
    app.Get("/articles/:id", articleController.GetArticleByID)
    app.Put("/articles/:id", articleController.UpdateArticle)
    app.Delete("/articles/:id", articleController.DeleteArticle)

    // Start Fiber app
    go func() {
    if err := app.Listen(":3000"); err != nil {
    fmt.Println("Error starting server:", err)
    }
    }()
    }


    Thanks in advance to anyone kind enough to answer this (probably simple) problem!


    I initially had problems connecting with the PostgreSQL database created in Coolify because Go could not find the host, but I solved it by getting the IP of the Docker container for the DB.

    I tried adding cors middleware in go and adding traefik labels in the docker compose.

    Continue reading...

Compartilhe esta Página