duanpo2813 2015-05-10 12:51
浏览 62
已采纳

在Go中设置导入结构的标签

I'm using gorm (go orm) to retrieve data from my database that will be encoded in JSON. Gorm provides a default struct for primary keys and time tracking, whose DeletedAt attribute should not be encoded in JSON.

I've written a small example, that doesn't output the password but the DeletedAt attribute is still visible.

package main

import (
    "encoding/json"
    "fmt"
    "os"

    "github.com/jinzhu/gorm"
    _ "github.com/lib/pq"
    _ "github.com/mattn/go-sqlite3"
)

// 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 {
    gorm.Model
    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 {
    *User
    DeletedAt bool `json:"deletedAt,omitempty"`
    Password  bool `json:"password,omitempty"`
}

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

    if err != nil {
        fmt.Println(err)
    }

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

    json.NewEncoder(os.Stdout).Encode(PublicUser{
        User: u,
    })
}

This is the ourput I get if I run my script:

{
    "ID":3,
    "CreatedAt":"2015-05-13T14:54:23.5577227Z",
    "UpdatedAt":"2015-05-13T14:54:23.5577227Z",
    "DeletedAt":null,
    "username":"dan",
    "locale":"en_US"
}

I modified the example of Alfred Rossi to imitate the behavior and I got the same result.

  • 写回答

1条回答 默认 最新

  • dongli8862 2015-05-10 13:15
    关注

    You can just shadow the field with a bool set to false and tag it with omitempty

    For example

    type User struct {
        Username  string `json:"username"`
        DeletedAt int    `json:"deleted_at"`
    }
    
    type PublicUser struct {
        *User
        DeletedAt bool `json:"deleted_at,omitempty"`
    }
    

    Feel free to play with it here. Also see this blog post of Attila Oláh.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 关于#目标检测#的问题:大概就是类似后台自动检测某下架商品的库存,在他监测到该商品上架并且可以购买的瞬间点击立即购买下单
  • ¥15 神经网络怎么把隐含层变量融合到损失函数中?
  • ¥30 自适应 LMS 算法实现 FIR 最佳维纳滤波器matlab方案
  • ¥15 lingo18勾选global solver求解使用的算法
  • ¥15 全部备份安卓app数据包括密码,可以复制到另一手机上运行
  • ¥20 测距传感器数据手册i2c
  • ¥15 RPA正常跑,cmd输入cookies跑不出来
  • ¥15 求帮我调试一下freefem代码
  • ¥15 matlab代码解决,怎么运行
  • ¥15 R语言Rstudio突然无法启动