init()函数可以安全地启动例程,包括进行测试吗?

I have an app. which creates an HTTP service to listen to a few connections points we can use to check the app status.

That service runs in the background (with a go routine).

It gets initialized in the init() function among other things:

func init() {
    ...
    initHttpEndPoints();
    ...
}

Can the fact that a go routine is created in the init() function cause issues when testing this app.?

I'm asking because it looks like my tests re-run the init() a second time and I'm wondering why that is and what the side effects could be... (probably not so good if all the go routines are all of a sudden duplicated.)

Note: The complete app. creates several hundred go routines in the init() function. I use the HTTP end point as an example.

Strongly related answer: Are tests run concurrently?

In addition to icza's answer, it sounds like you're using init() incorrectly with the testing package.

Rather than using init() to initialize things needed for tests, you should define the function TestMain().

Spec: Package initialization:

Package initialization—variable initialization and the invocation of init functions—happens in a single goroutine, sequentially, one package at a time. An init function may launch other goroutines, which can run concurrently with the initialization code. However, initialization always sequences the init functions: it will not invoke the next one until the previous one has returned.

There is nothing wrong about launching goroutines from init() functions, although you must remember that these goroutines run concurrently with the initialization process, so for example you can't assume anything about the initialization state of the (current) package.

If you see your init() functions running multiple times, that is most likely multiple tests run separately. init() functions run only once during the lifetime of a package.