Detect a hidden goroutine

Go pattern

Function invocations are expected to synchronous, and this function will execute asynchronously because all it does is call a goroutine. Instead, remove the internal goroutine and call the function using go.


Apply with the Grit CLI
grit apply hidden_goroutine

Detect a hidden goroutine with func call

BEFORE
package main

import "fmt"

//  hidden goroutine
func HiddenGoroutine() {
    go func() {
        fmt.Println("hello world")
    }()
}

func main() {
	// Call the HiddenGoroutine function
	HiddenGoroutine()
}
AFTER
package main

import "fmt"

//  hidden goroutine
func HiddenGoroutine() {
        fmt.Println("hello world")
    }

func main() {
	// Call the HiddenGoroutine function
	go HiddenGoroutine()
}

Detect a hidden goroutine without func call

BEFORE
package main

import "fmt"

//  hidden goroutine
func HiddenGoroutine() {
    go func() {
        fmt.Println("hello world")
    }()
}
AFTER
package main

import "fmt"

//  hidden goroutine
func HiddenGoroutine() {
        fmt.Println("hello world")
    }

Detect a hidden goroutine with other operation on top

GO
//  hidden goroutine
func FunctionThatCallsGoroutineIsOk() {
    fmt.Println("This is normal")
    go func() {
        fmt.Println("This is OK because the function does other things")
    }()
}

func main() {
	FunctionThatCallsGoroutineIsOk()
}

Detect a hidden goroutine with other operation on bottom

GO
//  hidden goroutine
func FunctionThatCallsGoroutineAlsoOk() {
    go func() {
        fmt.Println("This is OK because the function does other things")
    }()
    fmt.Println("This is normal")
}

func main() {
    FunctionThatCallsGoroutineAlsoOk()
}