I’m writing a Google App Engine Go application. In it, I want to handle some calls separately in different .go files. Should I call “init()” function separately in each of those files, or just declare it in one file and call some other functions for initialisation of each .go file?
For example, if I’d have two files, user.go:
package User
import(
"http"
"fmt"
)
func init() {
http.HandleFunc("/", hello)
}
func hello(w http.ResponseWriter, r *http.Request) {
fmt.Fprint(w, "Hello, user!")
}
And admin.go:
package Admin
import(
"http"
"fmt"
)
func init() {
http.HandleFunc("/admin/", hello)
}
func hello(w http.ResponseWriter, r *http.Request) {
fmt.Fprint(w, "Hello, admin!")
}
Is such an initialisation correct, or is it advised against something like this?
According to Go language specification:
all initialization code is run in a single goroutine, and
init() functions within a single package execute in unspecified order
In your case, the packages User and Admin are independent (User does not import Admin, nor Admin imports User). This means that:
Joining the bodies of the two init() functions in a single init() function would look like this:
Notice that it is irrelevant whether the program first registers
"/"or"/admin/". So, the following code is also valid :From the above two snippets of code, we can see that it is OK for
http.HandleFunc("/", ...)andhttp.HandleFunc("/admin/", ...)to be called in unspecified order.Because
"/"and"/admin/"can be registered in any order, and all init() functions run in a single goroutine, the answer to your question is: Yes, such an initialisation correct.