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
。谁能告诉我为什么会这样?