Search code examples
postgresqlgogo-gorm

GORM: Serialize bytea to hex string


I have such table in psql:

TABLE transactions (
    hash bytea NOT NULL
)

And I want to get data from DB and return it as a response to 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 would like to get something like this:

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

0x2d5788f30eee815b3bb3f018dd65319db476b3d6be3fb6ffd65d7ee99f4af638

I tried to make Scanner / Valuer, but so far it hasn't helped


Solution

  • With an advice from Cerise Limón, I made this one:

    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
    }
    

    And the response became like this:

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

    Maybe there is a better way, I'll be glad to see other suggestions