Set tags for imported structure in Go

I am using gorm ( g o orm ) to fetch data from my database to be JSON encoded. Gorm provides a default structure for primary keys and time tracking, whose DeletedAt attribute does not need to be JSON encoded.

I wrote a small example that doesn't display the password, but the DeletedAt attribute is still displayed.

package main

import (

    _ ""
    _ ""

// Struct from the gorm package:
// type Model struct {
//     ID        uint `gorm:"primary_key"`
//     CreatedAt time.Time
//     UpdatedAt time.Time
//     DeletedAt *time.Time
// }

// Defines the database model for gorn
type User struct {
    Username string `json:"username" sql:"size:32; not null; unique"`
    Password string `json:"password" sql:"not null"`
    Locale   string `json:"locale"   sql:"not null"`

// Public JSON version of database model
type PublicUser struct {
    DeletedAt bool `json:"deletedAt,omitempty"`
    Password  bool `json:"password,omitempty"`

func main() {
    db, err := gorm.Open("sqlite3", "storage.db")

    if err != nil {

    u := &User{}
    db.Where("id = ?", 3).Find(&u)

        User: u,


This will be our error if I run my script:



I modified Alfred Rossi's example to mimic his behavior and I got the same result.


source to share

1 answer

You can just shade the field with bool set to false and mark it omitempty

for example

type User struct {
    Username  string `json:"username"`
    DeletedAt int    `json:"deleted_at"`

type PublicUser struct {
    DeletedAt bool `json:"deleted_at,omitempty"`


Feel free to play with it here . Also see this post on Attila Ola's blog .



All Articles