func init() {
...
port := viper.Get("port")
host := viper.Get("host")
if port == nil || host == nil {
log.Fatal("configuration data not found")
}
fmt.Println(fmt.Sprintf("%s:%d", host, port)) // this produces 127.0.0.1:8080
}
func main() {
...
fmt.Println(fmt.Sprintf("%s:%d", host, port)) // but this produses ':'
log.Fatal(http.ListenAndServe(host+":"+port), r))
}
Why those init data is not present in main function? Where port and host are package variables. I expect that init fuction is executed before the main function.
you define host and port inside the init function() so when this function ends those variables disappears. You then need to declare them in outer block, for example
var port string
var host string
func init() {
...
port = viper.Get("port")
host = viper.Get("host")
if port == nil || host == nil {
log.Fatal("configuration data not found")
}
fmt.Println(fmt.Sprintf("%s:%d", host, port)) // this produces 127.0.0.1:8080
}