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

GORM: Serialize bytea to hex string

WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB
Release: 2024-02-12 16:24:05
forward
519 people have browsed it

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

Question content

I have such a table in psql:

table transactions (
    hash bytea not null
)
Copy after login

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"`
}
Copy after login
func getalltransactions(c *gin.context) {
    var transactions []models.transaction
    initializers.database.limit(10).find(&transactions)

    c.json(http.statusok, gin.h{"result": transactions})
}
Copy after login

Response:

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

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
Copy after login

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
}
Copy after login

The response becomes like this:

{
    "result": [
        {
            "hash": "0x2d5788f30eee815b3bb3f018dd65319db476b3d6be3fb6ffd65d7ee99f4af638"
        }
    ]
}
Copy after login

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!

Related labels:
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template