Home >Backend Development >Golang >GORM: Serialize bytea to hex string

GORM: Serialize bytea to hex string

WBOY
WBOYforward
2024-02-12 16:24:05424browse

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

Question content

I have such a table in psql:

table transactions (
    hash bytea not null
)

I want to get the data from the database and return it as a response to the user:

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})
}

Response:

{
    "result": [
        {
            "hash": "lvei8w7ugvs7s/ay3wuxnbr2s9a+p7b/1l1+6z9k9jg="
        }
    ]
}

But by default hash has wrong data, I want to get something like this:

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

0x2d5788f30eee815b3bb3f018dd65319db476b3d6be3fb6ffd65d7ee99f4af638

I tried making a scanner/valuer but so far that didn't help

Workaround

Based on the suggestion from cerise limón, I Did this:

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
}

The response becomes like this:

{
    "result": [
        {
            "hash": "0x2d5788f30eee815b3bb3f018dd65319db476b3d6be3fb6ffd65d7ee99f4af638"
        }
    ]
}

Maybe there is a better way, I'd be happy to see other suggestions

The above is the detailed content of GORM: Serialize bytea to hex string. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:stackoverflow.com. If there is any infringement, please contact admin@php.cn delete