go - Go 如何将字符串解码为包装的原子 int ?

标签 go go-zap

Uber 的日志库 Zap 有一个 Config 结构体,其中日志级别定义如下:

type Config struct {
    Level AtomicLevel `json:"level" yaml:"level"`
}

其中类型 AtomicLevel 是包装 Go 的 atomic.Int32struct:

type AtomicLevel struct {
    l *atomic.Int32
}

通过此设置,Go 的 json.Unmarshall 如何成功将 string 解码,例如“调试”为正确的原子 int 值,如以下示例所示?

package main

import (
    "encoding/json"

    "go.uber.org/zap"
)

func main() {
    // For some users, the presets offered by the NewProduction, NewDevelopment,
    // and NewExample constructors won't be appropriate. For most of those
    // users, the bundled Config struct offers the right balance of flexibility
    // and convenience. (For more complex needs, see the AdvancedConfiguration
    // example.)
    //
    // See the documentation for Config and zapcore.EncoderConfig for all the
    // available options.
    rawJSON := []byte(`{
      "level": "debug",
      "encoding": "json",
    }`)

    var cfg zap.Config
    if err := json.Unmarshal(rawJSON, &cfg); err != nil {
        panic(err)
    }
    logger, err := cfg.Build()
    if err != nil {
        panic(err)
    }
    defer logger.Sync()

    logger.Info("logger construction succeeded")
}

最佳答案

AtomicLevel 有 UnmarshalText方法,这意味着它实现了encoding.TextUnmarshaler界面。当 JSON 解码器看到 JSON 字符串并且目标是实现 TextUnmarshaler 的类型时,会调用其 UnmarshalText 方法将字符串转换为适当的值(除非该类型实现了 json.Unmarshaler,在这种情况下优先。AtomicLevel 不优先。)

关于go - Go 如何将字符串解码为包装的原子 int ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72851107/

相关文章:

go - go-logr 和 uber 的 zap 详细级别之间的对应关系是什么?

go - 具有自定义消息编码器的 Uber zap 日志记录

go - 如何在不使用字段的情况下在 Uber Zap 中记录键/值对

go - 在 Go 中设置包路径

reactjs - 您如何使用 fetch 在本地从客户端向服务器发出请求而不会得到不透明的响应?

go - 无法分配内存错误

Golang 无法杀死子进程的父进程

go - 为什么在 Uber Zap 中调用 logger.With 后自定义编码会丢失?

go - 如何知道 2 个 go map 是否引用相同的数据