1

我正在尝试将使用encoding/gob来自 Golang 的编码数据存储到 Postgres 中。我也在使用 Gorm。

首先,使用发送表单数据

if err := json.NewDecoder(r.Body).Decode(model); err != nil {
  http.Error(w, err.Error(), http.StatusBadRequest)
  return
}

目前client_encoding在 postgres 数据库中设置为 UTF8。这是我用来编码的内容:

type payload struct {
    Key     []byte
    Nonce   *[nonceLength]byte
    Message []byte
}

// Encrypt message
p.Message = secretbox.Seal(p.Message, plaintext, p.Nonce, key) // key set prior to this

buf := &bytes.Buffer{}
if err := gob.NewEncoder(buf).Encode(p); err != nil {
    return nil, err
}

return buf.Bytes(), nil

然后我将string(buf.Bytes())其存储在当前为字符串类型的数据库列中。现在我是编码新手,我认为 gob 对我的数据库有不同的编码。我在控制台中收到此错误:

(pq: invalid byte sequence for encoding "UTF8": 0xff)

我一直在关注加密/解密的要点: https ://gist.github.com/fuzzyami/f3a7231037166117a6fef9607960aee7

根据我的阅读,我不应该将结构编码到数据库中,在这种情况下p,除非使用gob. 如果我错了,请纠正我(在我找到这个的那一刻找不到资源)。

有没有人能指出我在 Postgres 中存储这些数据的正确方向,这些数据稍后会被解密?我显然不了解编码过程,也不完全确定从哪里开始阅读资源,因此感谢您的帮助!

4

2 回答 2

0

使用byteapostgresql 中的列来存储 a []byte,并跳过转换为string.

于 2018-11-11T18:01:11.190 回答
0

看看https://golang.org/src/encoding/base64/example_test.go

能够使用

return base64.StdEncoding.EncodeToString(buf.Bytes()), nil

其中成功存储在数据库中。

于 2018-11-11T20:58:34.970 回答