go.lang.best-practice.hidden-goroutine.hidden-goroutine

profile photo of semgrepsemgrep
Author
3,250
Download Count*

Detected a hidden goroutine. 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'.

Run Locally

Run in CI

Defintion

rules:
  - id: hidden-goroutine
    patterns:
      - pattern-not: |
          func $FUNC(...) {
            go func() {
              ...
            }(...)
            $MORE
          }
      - pattern: |
          func $FUNC(...) {
            go func() {
              ...
            }(...)
          }
    message: Detected a hidden goroutine. 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'.
    languages:
      - go
    severity: WARNING
    metadata:
      category: best-practice
      technology:
        - go
      license: Commons Clause License Condition v1.0[LGPL-2.1-only]

Examples

hidden-goroutine.go

package main

import "fmt"

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

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

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