恐慌:同步:对同一端点有多个请求的负 WaitGroup 计数器

panic: sync: negative WaitGroup counter with multiple requests to the same Endpoint

我正在做一个散列密码生成器,我在服务器上有一个端点,它生成一个 goroutine 来创建散列密码,然后在 goroutine 结束时将其作为响应发送。

这是生成散列密码所调用的函数

func SetHash(c echo.Context) error {
    hashedhPassword := make(chan string)
    var wg sync.WaitGroup
    wg.Add(2)
    go utils.GenerateSaltedHashAsync("demoprueba", wg, hashedhPassword)
    return response.Success(c, map[string]string{
        "salt": <-hashedhPassword,
    })
}

这是散列 class

package utils

import (
    "encoding/base64"
    "fmt"
    "golang.org/x/crypto/argon2"
    "sync"
    "tigoApi/config"
)

const (
    Time         = 4
    Memory       = 64 * 1024
    KeyLen       = 80
    Threads      = 10
)

var environment = config.Instance()

func GenerateSaltedHashAsync(password string,wg sync.WaitGroup, hashedPassword chan string) {
    cryptoKey := argon2.IDKey([]byte(password), []byte(environment.SaltedPassword), Time, Memory, uint8(Threads), KeyLen)
    encodedPassword := base64.StdEncoding.EncodeToString(cryptoKey)
    consoleHash := fmt.Sprintf("%s$%d$%d$%d$%d$%s$%s", environment.PepperPassword, Time, Memory, Threads, KeyLen, environment.SaltedPassword, encodedPassword)
    defer wg.Done()
    hashedPassword <- consoleHash
    wg.Wait()
}

当我执行单个请求时一切正常,但是当我一次发送多个请求时(压力测试)应用程序发送此错误。

panic: sync: negative WaitGroup counter

goroutine 1566 [running]: sync.(*WaitGroup).Add(0xc0001320a0, 0xffffffffffffffff) /usr/local/go/src/sync/waitgroup.go:74 +0x139 sync.(*WaitGroup).Done(0xc0001320a0) /usr/local/go/src/sync/waitgroup.go:99 +0x34 tigoApi/utils.GenerateSaltedHashAsync(0x8e5324, 0xa, 0x0, 0x2, 0xc000226240) /home/crdzbird/goApps/src/tigoApi/utils/hashing.go:46 +0x3cc created by tigoApi/controller.SetHash /home/crdzbird/goApps/src/tigoApi/controller/user_controller.go:23 +0xcd

Process finished with exit code 2

请任何人告诉我代码有什么问题。

更新。

感谢建议,代码工作应该是这样的...

func SetHash(c echo.Context) error {
    hashedhPassword := make(chan string)
    go utils.GenerateSaltedHashAsync("lacb2208", hashedhPassword)
    return response.Success(c, map[string]string{
        "salt": <-hashedhPassword,
    })
}


func GenerateSaltedHashAsync(password string, hashedPassword chan string) {
    cryptoKey := argon2.IDKey([]byte(password), []byte(environment.SaltedPassword), Time, Memory, uint8(Threads), KeyLen)
    encodedPassword := base64.StdEncoding.EncodeToString(cryptoKey)
    consoleHash := fmt.Sprintf("%s$%d$%d$%d$%d$%s$%s", environment.PepperPassword, Time, Memory, Threads, KeyLen, environment.SaltedPassword, encodedPassword)
    hashedPassword <- consoleHash
    close(hashedPassword)
}

来自 syncdocs:

Values containing the types defined in this (sync) package should not be copied.

因此,如果需要引用,请使用指针。

更改函数签名,使 wg 成为指针引用:

func GenerateSaltedHashAsync(password string,wg *sync.WaitGroup, hashedPassword chan string)

然后用那个参考调用:

go utils.GenerateSaltedHashAsync("demoprueba", &wg, hashedhPassword)