package main import ( "context" "fmt" "nyanimedb-server/api" "nyanimedb-server/db" "os" "reflect" "time" "github.com/gin-contrib/cors" "github.com/gin-gonic/gin" "github.com/jackc/pgx/v5" "github.com/pelletier/go-toml/v2" ) var AppConfig Config func main() { // if len(os.Args) != 2 { // AppConfig.Mode = "env" // } else { // AppConfig.Mode = "argv" // } // err := InitConfig() // if err != nil { // log.Fatalf("Failed to init config: %v\n", err) // } conn, err := pgx.Connect(context.Background(), os.Getenv("DATABASE_URL")) if err != nil { fmt.Fprintf(os.Stderr, "Unable to connect to database: %v\n", err) os.Exit(1) } defer conn.Close(context.Background()) r := gin.Default() queries := db.New(conn) server := api.NewServer(queries) // r.LoadHTMLGlob("templates/*") r.Use(cors.New(cors.Config{ AllowOrigins: []string{"*"}, // allow all origins, change to specific domains in production AllowMethods: []string{"GET", "POST", "PUT", "DELETE"}, AllowHeaders: []string{"Origin", "Content-Type", "Accept"}, ExposeHeaders: []string{"Content-Length"}, AllowCredentials: true, MaxAge: 12 * time.Hour, })) api.RegisterHandlers(r, api.NewStrictHandler( server, // сюда можно добавить middlewares, если нужно []api.StrictMiddlewareFunc{}, )) // r.GET("/", func(c *gin.Context) { // c.HTML(http.StatusOK, "index.html", gin.H{ // "title": "Welcome Page", // "message": "Hello, Gin with HTML templates!", // }) // }) // r.GET("/api", func(c *gin.Context) { // items := []Item{ // {ID: 1, Title: "First Item", Description: "This is the description of the first item."}, // {ID: 2, Title: "Second Item", Description: "This is the description of the second item."}, // {ID: 3, Title: "Third Item", Description: "This is the description of the third item."}, // } // c.JSON(http.StatusOK, items) // }) r.Run(":8080") } func InitConfig() error { if AppConfig.Mode == "argv" { content, err := os.ReadFile(os.Args[1]) if err != nil { return err } toml.Unmarshal(content, &AppConfig) fmt.Printf("%+v\n", AppConfig) return nil } else if AppConfig.Mode == "env" { f := reflect.ValueOf(AppConfig) for i := 0; i < f.NumField(); i++ { field := f.Type().Field(i) tag := field.Tag env_var := tag.Get("env") fmt.Printf("Field: %v.\nEnvironment variable: %v.\n", field.Name, env_var) if env_var != "" { env_value, exists := os.LookupEnv(env_var) if !exists { return fmt.Errorf("there is no env variable %s", env_var) } err := setField(&AppConfig, field.Name, env_value) if err != nil { return fmt.Errorf("failed to set config field %s: %v", field.Name, err) } } } return nil } else { return fmt.Errorf("incorrect config mode") } }