Why is it not work that way?

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.

2 Likes

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

2 Likes

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

3 Likes

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
}
3 Likes

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.