According to the Go language specification:
all initialization code runs in one goroutine, and
The init () functions in a single package are executed in unspecified order.
In your case, the User and Admin packages are independent (the User does not import Admin, and Admin does not import the user). It means that:
- two init () functions in User and Admin execute in unspecified order
The union of the bodies of two init () functions in one init () function will look like this:
func init() { http.HandleFunc("/", User.Hello) http.HandleFunc("/admin/", Admin.Hello) }
Please note that it doesn’t matter if the program first registers "/" or "/admin/" . Thus, the following code is valid:
func init() { http.HandleFunc("/admin/", Admin.Hello) http.HandleFunc("/", User.Hello) }
From the above two code snippets, we can see that OK http.HandleFunc("/", ...) and http.HandleFunc("/admin/", ...) should be called in an unspecified order.
Since "/" and "/admin/" can be registered in any order, and all init () functions are run in one goroutine, the answer to your question: Yes, this initialization is correct.
user811773
source share