In my main.go, I load my config which determines whether it's in prod or dev mode. Once that's done, I start the server and initialize the database. However, when I'm in either prod or dev environment, it doesn't show the correct database information from the .env file and instead defaults to the fallback values. But when I try running it without the server startup part, the environment variables work fine. After extensive research and experimentation (stackoverflow, chatgpt, github), I still haven't found a solution.
func main() {
fmt.Printf("My_Land Ads Launch - Version: %s \n", Version)
// Load configuration
cfg, err := config.LoadConfig()
if err != nil {
log.Fatalf("Error loading config: %v", err)
}
fmt.Printf("My_Land Ads Launch - Config: %s", cfg)
// Initialize and start the server => *http.Server
/*srv := server.NewServer(cfg)
err = srv.ListenAndServe()
if err != nil {
panic(fmt.Sprintf("cannot start server: %s", err))
}*/
}
package server
import (
"fmt"
"net/http"
"time"
_ "github.com/joho/godotenv/autoload"
"My_Land-Ads-Launch/internal/config"
"My_Land-Ads-Launch/internal/database"
)
type Server struct {
config *config.Config
db database.Service
}
func NewServer(cfg *config.Config) *http.Server {
NewServer := &Server{
config: cfg,
db: database.New(cfg),
}
// Declare Server config
server := &http.Server{
Addr: fmt.Sprintf(":%d", NewServer.config.PORT),
Handler: NewServer.RegisterRoutes(),
IdleTimeout: time.Minute,
ReadTimeout: 10 * time.Second,
WriteTimeout: 30 * time.Second,
}
return server
}