Why is it not work that way?


(cinematik) #1

In main.go I have:

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.


(cinematik) #2

Solved. The problem was in recreation variables and not using type assertion.


(Norbert Melzer) #3

inits host and port are initialised using :=, which causes them to shadow the package variables, just use regular assignment (=).


(Yamil Bracho) #4

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
}