首頁  >  文章  >  後端開發  >  GORM:將 bytea 序列化為十六進位字串

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

WBOY
WBOY轉載
2024-02-12 16:24:05369瀏覽

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刪除