0

db/db.go

    func DbClient(cfg *config.Config, logger log.Logger) *ent.Client {
    // "host=<host> port=<port> user=<user> dbname=<database> password=<pass>"
    psqlInfo := fmt.Sprintf("host=%s port=%s user=%s dbname=%s password=%s",
        cfg.DB_HOST, cfg.DB_PORT, cfg.DB_USER, cfg.DB_NAME, cfg.DB_PASS)
    client, err := ent.Open("postgres", psqlInfo)
    if err != nil {
        logger.Fatal(err)
    }
    defer client.Close()
    logger.Info("Database Connected")
    if err := client.Schema.Create(context.Background()); !errors.Is(err, nil) {
        logger.Fatalf("Error: failed creating schema resources %v\n", err)
    }

    return client
}

services/userservice.go

func CreateUser(client *ent.Client, input *model.NewUser) (*ent.User, error) {
    user, err := client.Debug().User.Create().SetName(input.Name).SetUsername(input.Username).SetEmail(input.Email).SetPassword(input.Password).Save(context.Background())
    if err != nil {
        return &ent.User{}, err
    }
    return user, nil
}

ent 客户端创建所有必要的表并显示数据库已连接。但是当我执行CreateUser()它时它正在返回sql: database is closed。谁能告诉我为什么会这样?

4

1 回答 1

2

Close您的引导代码中有一个数据库连接调用:

func DbClient(cfg *config.Config, logger log.Logger) *ent.Client {
  // "host=<host> port=<port> user=<user> dbname=<database> password=<pass>"
  psqlInfo := fmt.Sprintf("host=%s port=%s user=%s dbname=%s password=%s",
cfg.DB_HOST, cfg.DB_PORT, cfg.DB_USER, cfg.DB_NAME, cfg.DB_PASS)
  client, err := ent.Open("postgres", psqlInfo)
  if err != nil {
      logger.Fatal(err)
  }
  defer client.Close() // <- this one
  logger.Info("Database Connected")
  if err := client.Schema.Create(context.Background()); !errors.Is(err, nil) {
    logger.Fatalf("Error: failed creating schema resources %v\n", err)
  }
  return client
}

返回后此调用关闭连接client。如果需要关闭连接,请从CreateUser()func 中将其关闭。

func CreateUser(client *ent.Client, input *model.NewUser) (*ent.User, error) {
    user, err := client.Debug().User.Create().SetName(input.Name).SetUsername(input.Username).SetEmail(input.Email).SetPassword(input.Password).Save(context.Background())
    if err != nil {
        return &ent.User{}, err
    }
    defer client.Close() // <- here
    return user, nil
}
于 2022-01-13T07:58:58.410 回答