gpt4 book ai didi

struct - 在 golang 结构中转换字符串

转载 作者:数据小太阳 更新时间:2023-10-29 03:40:09 34 4
gpt4 key购买 nike

我有一个 AES 加密 secret 的 json 文件。结构是:

{
"username": "asdf123ASLdf3",
"password": "elisjdvo4etQW"
}

还有一个结构来保存这些值

type Secrets struct {
Username string `json:"username"`
Password string `json:"password"`
}

将加密的 json 值加载到结构中很容易,但我真正想要的是具有未加密值的结构。

因此,对于每个值,我想通过一个函数运行它:

aesDecrypt(key string, value string) 字符串

我很高兴在第一次加载时完成此操作,或者将所有内容移至新结构中。

我想避免重复 json 键或字段名称。

执行此操作的最佳方法是什么?

(也开放其他方式来管理 Go 中的加密 secret )

最佳答案

一个选项是定义自定义 JSON Unmarshaler。正如您提到的,另一种方法是将其复制到另一个结构。

  1. 实现 Unmarshaler 接口(interface)

    关键的见解是知道您可以覆盖 json.Unmarshal 的通过实现 the Unmarshaler interface 的行为.在我们的case,这意味着定义一个函数 func (ss *Secrets)
    UnmarshalJSON(bb []byte) error
    将在以下情况下进行 AES 解密您尝试将任何 JSON 解码为 Secrets

    package main

    import "fmt"
    import "encoding/json"

    type Secrets struct {
    Username string `json:"username"`
    Password string `json:"password"`
    }

    func main() {
    jj := []byte(`{
    "username": "asdf123ASLdf3",
    "password": "elisjdvo4etQW"
    }`)
    var ss Secrets
    json.Unmarshal(jj, &ss)
    fmt.Println(ss)
    }

    func aesDecrypt(key, value string) string {
    return fmt.Sprintf("'%s' decrypted with key '%s'", value, key)
    }

    func (ss *Secrets) UnmarshalJSON(bb []byte) error {
    var objmap map[string]*string
    err := json.Unmarshal(bb, &objmap)
    ss.Username = aesDecrypt("my key", *objmap["password"])
    ss.Password = aesDecrypt("my key", *objmap["username"])
    return err
    }

    这会输出一个 Secrets 结构:

    {'elisjdvo4etQW' decrypted with key 'my key'
    'asdf123ASLdf3' decrypted with key 'my key'}

    See it in action at the Go Playground.

  2. 复制到另一个结构

    您可以在每次需要时简单地创建一个新的 Secrets 结构解密 JSON。如果你经常这样做,这可能会很乏味,或者如果你不需要中间状态。

    package main

    import "fmt"
    import "encoding/json"

    type Secrets struct {
    Username string `json:"username"`
    Password string `json:"password"`
    }

    func main() {
    jj := []byte(`{
    "username": "asdf123ASLdf3",
    "password": "elisjdvo4etQW"
    }`)
    var ss Secrets
    json.Unmarshal(jj, &ss)
    decoded := Secrets{
    aesDecrypt(ss.Username, "my key"),
    aesDecrypt(ss.Password, "my key")}
    fmt.Println(decoded)
    }

    func aesDecrypt(key, value string) string {
    return fmt.Sprintf("'%s' decrypted with key '%s'", value, key)
    }

    Check it out at Go Playground.

    这与上面的输出相同:

    {'elisjdvo4etQW' decrypted with key 'my key'
    'asdf123ASLdf3' decrypted with key 'my key'}

显然,你会使用不同版本的 aesDecrypt,我的只是一个假人。而且,一如既往,你实际上应该检查在您自己的代码中返回错误。

关于struct - 在 golang 结构中转换字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30919448/

34 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com