标签: go

error.Wrap 和 error.WithMessage 之间有什么区别

github.com/pkg/errors

这是Wrap(err error, msg string) https://pkg.go.dev/github.com/pkg/errors#Wrap

这是WithMessage(err error, msg string) https://pkg.go.dev/github.com/pkg/errors#WithMessage

这两个函数都实现了接口causer https://pkg.go.dev/github.com/pkg/errors#Cause

这段代码适用于errors.WithMessage,尽管我认为我应该使用errors.Wrapforerrors.Cause

func main() {
    err := errors.New("first")
    err1 := errors.WithMessage(err, "tmp")
    err2 := errors.WithMessage(err1, "tmp")
    err3 := errors.WithMessage(err2, "tmp")
    fmt.Printf("%s", errors.Cause(err3))
}
Run Code Online (Sandbox Code Playgroud)

Output: first

go

3
推荐指数
1
解决办法
453
查看次数

如何通过 Zerolog 自动记录结构?

我用于zerolog登录 go 应用程序。我想记录一个地图(json)并找到一种方法:

log.Info().
    Str("foo", "bar").
    Dict("dict", zerolog.Dict().
        Str("bar", "baz").
        Int("n", 1),
    ).Msg("hello world")

// Output: {"level":"info","time":1494567715,"foo":"bar","dict":{"bar":"baz","n":1},"message":"hello world"}
Run Code Online (Sandbox Code Playgroud)

在上面的示例中,我需要key-value在方法中指定每一对zerolog.Dict()。我想知道是否有自动记录struct.

例如,我有一个类似的结构:

type Message struct {
    AWS_REGION     string `json:"region"`
    LOG_LEVEL      string `json:"level"`
    STAGE          string `json:"stage"`
    REQUEST_ID     string `json:"requestId"`
}
Run Code Online (Sandbox Code Playgroud)

我正在寻找一种将Message实例传递给的方法

msg := Message{ ... }
zerolog.Dict("message", msg)
Run Code Online (Sandbox Code Playgroud)

logging go

3
推荐指数
1
解决办法
2804
查看次数

有没有办法计算枚举中定义的项目总数?

我正在尝试计算 Go 中枚举 (iota) 中定义的项目数量,但我不确定如何执行此操作。

go

3
推荐指数
1
解决办法
188
查看次数

Golang 迁移安装在 Ubuntu 22.04 上失败,并出现以下 GPG 错误:公钥不可用:NO_PUBKEY B53DC80D13EDEF05

我尝试在 Ubutu 22.4 上安装 Golang Migrate,但在尝试执行命令时出现以下错误。

错误公钥不可用:NO_PUBKEY B53DC80D13EDEF05

这是我到目前为止所尝试过的,它在尝试执行第二个命令 - sudo-apt-get update 时抛出“未找到公钥”消息。

1.

curl -s https://packagecloud.io/install/repositories/golang-migrate/migrate/script.deb.sh | sudo bash
Run Code Online (Sandbox Code Playgroud)
  1. sudo apt-get 更新

sudo apt-get install migrate
Run Code Online (Sandbox Code Playgroud)

我尝试使用以下命令手动添加密钥,但在执行 sudo apt-get update 时仍然显示相同的错误。

sudo apt-key adv --keyserver keyserver.ubuntu.com --recv-keys B53DC80D13EDEF05
Run Code Online (Sandbox Code Playgroud)

上述 3 个命令在 Ubuntu 20.4 上运行良好,但在 22.4 上则不行。任何线索或解决方案都会非常有帮助。

go golang-migrate ubuntu-22.04

3
推荐指数
1
解决办法
1958
查看次数

为什么 Go 中的映射文字允许在使用函数调用而不是文字时覆盖键?

package main

import "fmt"

func main() {
    blaa := map[string]string{
        "key":    "value",
        getKey(): "value2", //replacing getKey() with "key" results in compile time error.
    }
    fmt.Println("Hello, " + blaa["key"])
}

func getKey() string {
    return "key"
}
Run Code Online (Sandbox Code Playgroud)

运行上面的程序将打印“Hello, value2”。在这里尝试一下https://go.dev/play/p/s92LaaNc3n4

虽然我可以看到密钥被覆盖,但我想知道为什么这panic在运行时不会被覆盖?使用两个字符串文字"key"将导致编译时错误,这是预期的行为。

dictionary go

3
推荐指数
1
解决办法
99
查看次数

如何在 Golang 代码中测试 filepath.Abs​​ 失败?

在我的 Go 代码中,我必须多次使用 filepath.Abs​​(),这可能会导致我的方法返回不同的错误。

func (s *service) myFunc(path string) error {
    dir := s.Component().Dir()
    absDir, err := filepath.Abs(dir)

    if err != nil {
        return my_errors.NewFailedToGetAbsoluteComponentDir()
    }

    absPath, err := filepath.Abs(path)
    if absPath != nil {
        return my_errors.NewFailedToGetAbsPath()
    }

    // more code...
    return nil
}
Run Code Online (Sandbox Code Playgroud)

在我的单元测试中,我想测试它,但我能想到的唯一方法是将 filepath.Abs​​ 作为依赖项注入到我的结构中。

还有其他我没想到的办法吗?或者你认为这种测试没有必要?

unit-testing mocking go go-testing

3
推荐指数
1
解决办法
406
查看次数

泛型函数不能以匿名形式定义吗?

例如:

func f[T any](t T) T {
    var result T
    return result
}

// this got error !
var fAnonymous = func[T any](t T) T {
    var result T
    return result
}
Run Code Online (Sandbox Code Playgroud)

fAnonymous出现错误,它说:

函数文字不能有类型参数

那么,为什么 golang 不允许匿名函数是通用的呢?

generics anonymous-function go

3
推荐指数
1
解决办法
2080
查看次数

无法读取“https://github.com”的用户名:Windows 上禁用终端提示

我试图使用私有存储库获取一些依赖项go get -u <github_private_repo_link>,但它一直失败并出现以下错误:

server response:
not found: github.com/..../v3@v3.11.1: invalid version: git ls-remote -q origin in /tmp/gopath/pkg/mod/cache/vcs/168bff8af96cdfac9cbe3ad64f7753732f8a19d99f7f1e897f19371e1ea453d9: exit status 128:
fatal: could not read Username for 'https://github.com': terminal prompts disabled
Confirm the import path was entered correctly.
If this is a private repository, see https://golang.org/doc/faq#git_https for additional information.
Run Code Online (Sandbox Code Playgroud)

我尝试导出set GIT_TERMINAL_PROMPT=1,但没有任何反应,出现同样的错误。有什么办法 go get 会忽略 Windows 上这个变量的值吗go 1.13

git go

3
推荐指数
1
解决办法
7262
查看次数

Golang 到 wasm 编译

我使用以下命令将 Golang 代码编译为 wasm

GOOS=js GOARCH=wasm go build -o main.wasm
Run Code Online (Sandbox Code Playgroud)

尝试使用 wasmtime 执行时出现以下错误

wasmtime main.wasm 
Error: failed to run main module `main.wasm`

Caused by:
    0: failed to instantiate "main.wasm"
    1: unknown import: `go::debug` has not been defined

Run Code Online (Sandbox Code Playgroud)

当使用 wasm3 执行时,我得到

wasm3 main.wasm 
Error: function lookup failed ('_start')
Run Code Online (Sandbox Code Playgroud)

这些错误意味着什么以及如何修复它们?

go webassembly

3
推荐指数
1
解决办法
1574
查看次数

如何将已知类型转换为指向开关中类型参数的指针?

我正在尝试编写一个函数,根据返回值的类型参数将 JSON 字符串的字节数组转换为另一个字节数组,规则如下:

  • map[string]interface{}:转换为map[string]interface{}
  • []byte:不转换,按原样返回
  • 结构体:转换为结构体

我的代码如下:

func GetJsonData[T any](jsonByteArray []byte) (result *T, err error) {
    var buff T

    switch any(result).(type) { // https://appliedgo.com/blog/a-tip-and-a-trick-when-working-with-generics
    case *[]byte:
        result = &T(jsonByteArray)
    default:
        err = json.Unmarshal(jsonByteArray, &buff)
        result = &buff
    }

    return
}
Run Code Online (Sandbox Code Playgroud)

此代码在将jsonByteArray 的类型转换为 T 时发生类型错误,如下所示:

cannot convert jsonByteArray (variable of type []byte) to type T
Run Code Online (Sandbox Code Playgroud)

如何将这个[]byte类型变量的指针赋给泛型类型返回值?

generics go

3
推荐指数
1
解决办法
100
查看次数