首頁 > 後端開發 > Golang > 主體

GORM:將 bytea 序列化為十六進位字串

WBOY
發布: 2024-02-12 16:24:05
轉載
387 人瀏覽過

GORM:将 bytea 序列化为十六进制字符串

問題內容

我在 psql 中有這樣的表格:

table transactions (
    hash bytea not null
)
登入後複製

我想從資料庫獲取資料並將其作為對用戶的回應傳回:

type transaction struct {
    hash []byte `gorm:"column:hash" json:"hash"`
}
登入後複製
func getalltransactions(c *gin.context) {
    var transactions []models.transaction
    initializers.database.limit(10).find(&transactions)

    c.json(http.statusok, gin.h{"result": transactions})
}
登入後複製

回應:

{
    "result": [
        {
            "hash": "lvei8w7ugvs7s/ay3wuxnbr2s9a+p7b/1l1+6z9k9jg="
        }
    ]
}
登入後複製

但是預設情況下hash有錯誤的數據,我想得到這樣的東西:

SELECT '0x' || encode(hash::bytea, 'hex') AS hash_hex FROM transactions LIMIT 1;

0x2d5788f30eee815b3bb3f018dd65319db476b3d6be3fb6ffd65d7ee99f4af638
登入後複製

我嘗試製作scanner / valuer,但到目前為止還沒有幫助

解決方法

#根據cerise limón的建議,我做了這個:

type hexbytes []byte

type transaction struct {
    hash              hexbytes `gorm:"column:hash" json:"hash"`
}

func (b hexbytes) marshaljson() ([]byte, error) {
    hexstr := hex.encodetostring(b)
    return []byte(`"0x` + hexstr + `"`), nil
}
登入後複製

回應變成這樣:

{
    "result": [
        {
            "hash": "0x2d5788f30eee815b3bb3f018dd65319db476b3d6be3fb6ffd65d7ee99f4af638"
        }
    ]
}
登入後複製

也許有更好的方法,我很高興看到其他建議

以上是GORM:將 bytea 序列化為十六進位字串的詳細內容。更多資訊請關注PHP中文網其他相關文章!

相關標籤:
來源:stackoverflow.com
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
最新問題
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!