I try create package config in my example project but something doesn't work as I expected, I have folder structure:
config/config.go // package config
main.go // package main
and I want use config in my main file:
func main() {
conf := config.GetConf()
db := dbConn{
schemas: map[string]*sql.DB{},
url: fmt.Sprintf("tcp(%s)", conf.db['dev']),
username: db.user,
password: db.password,
}
db.create()
}
my config file:
type Config struct {
db map[string]string
user string
password string
}
func GetConf() *Config {
config := Config{
db: map[string]string{
"dev": "database.url",
},
user: "root",
password: "pass",
}
return &config
}
compiler return error: conf.db undefined (cannot refer to unexported field or method db)
It is a compile-time error to refer to unexported identifiers from other packages (other than the declaring package).
Export the identifiers (start them with an uppercase letter), and it will work.
type Config struct {
DB map[string]string
User string
Password string
}
func GetConf() *Config {
config := Config{
DB: map[string]string{
"dev": "database.url",
},
User: "root",
Password: "pass",
}
return &config
}
And in your main:
func main() {
conf := config.GetConf()
db := dbConn{
schemas: map[string]*sql.DB{},
url: fmt.Sprintf("tcp(%s)", conf.DB['dev']),
username: conf.User,
password: conf.Password,
}
db.create()
}