小编Ama*_*aur的帖子

如何在 Golang 结构中使用 omitempty 标志更新 Mongodb 字段

我正在处理优惠券表格,其中有一些可选字段。

介绍:

所有表单字段值都作为 JSON 接收并映射到 Golang 结构中。在结构中,我为每个字段添加了一个“omitempty”标志。因此,只有那些具有适当值的表单值才会被映射,其余的值(如 0、“”、false)将被结构忽略。

这是Golang的结构

type Coupon struct {
    Id               int    `json:"id,omitempty" bson:"_id,omitempty"`
    Name             string `json:"name,omitempty" bson:"name,omitempty"`
    Code             string `json:"code,omitempty" bson:"code,omitempty"`
    Description      string `json:"description,omitempty" bson:"description,omitempty"`
    Status           bool   `json:"status" bson:"status"`
    MaxUsageLimit    int    `json:"max_usage_limit,omitempty" bson:"max_usage_limit,omitempty"`
    SingleUsePerUser bool   `json:"single_use_per_user,omitempty" bson:"single_use_per_user,omitempty"`
}
Run Code Online (Sandbox Code Playgroud)

问题:

  1. 当我第一次保存这个表单时,合适的表单值会保存到 Mongodb 中。

  2. 现在我想更新该表单并假设有一个复选框,该复选框在保存数据时已选中。更新表单时,未选中该复选框并提交表单以保存。现在因为我在结构中应用了“omitempty”标志,所以它没有将空值映射到复选框字段。由于该值未映射到结构中,因此不会保存到数据库中。

  3. 当用户第二次编辑表单时,它会看到相同的复选框被选中。(但实际上,该值应更新到数据库中,并且复选框应显示为未选中状态。)

  4. 我在 REST API 中使用相同的表单数据(JSON 格式)。在 API 中,在更新表单数据时,如果我只提到那些必需的值并且不传递我不想更新的值,那么 MongoDB 就会使用提供的必需值覆盖整个文档(即使这些值是也被覆盖,我不想更新也不想传入 API)。

要求:

将来,我想公开 REST API,所以我不希望这件事发生在那里。这就是为什么我不想从结构字段中删除“omitempty”标志。

在结构中使用 omitempty 标志时,有什么方法可以将空表单值或 API 数据字段保存到数据库中?

谢谢!

forms json struct go mongodb

6
推荐指数
1
解决办法
5917
查看次数

从接口获取接口字段值,而无需在Golang中声明结构

我正在尝试从Golang中的接口获取字段值。该接口最初是一个空接口,正在从数据库结果中获取其值。数据库查询工作正常。

我唯一需要做的就是获取接口的字段值。这是我的代码:

s := reflect.ValueOf(t)
    for i := 0; i < s.Len(); i++ {
        fmt.Println(s.Index(i))
    }
Run Code Online (Sandbox Code Playgroud)

其中t是具有以下值的接口:

map[id:null count:1]
Run Code Online (Sandbox Code Playgroud)

我想要"count"简单的价值1。

我的问题是Index()方法正在返回紧急消息,因为它需要一个结构,而我在这里没有任何结构。那么我该怎么做才能获得接口价值?有没有解决方案可以在有或没有Golang的反射包的情况下遍历接口以获取字段值?

编辑

获取计数值后,我需要将其解析为json。

这是我的代码:

type ResponseControllerList struct{
    Code            int             `json:"code"`
    ApiStatus       int             `json:"api_status"`
    Message         string          `json:"message"`
    Data            interface{}     `json:"data,omitempty"`
    TotalRecord     interface{}     `json:"total_record,omitempty"`
}
response := ResponseControllerList{}
ratingsCount := reflect.ValueOf(ratingsCountInterface).MapIndex(reflect.ValueOf("count"))
fmt.Println(ratingsCount)

response = ResponseControllerList{
                200,
                1,
                "success",
                nil,
                ratingsCount,
            }
GetResponseList(c, response)

func GetResponseList(c *gin.Context, response ResponseControllerList) {
    c.JSON(200, gin.H{
        "response": response,
    })
}
Run Code Online (Sandbox Code Playgroud)

上面的代码用于获取ratingCountJSON格式,以将此响应用作API响应。在这段代码中,我正在使用GIN框架向API发出HTTP请求。

现在的问题是,当我打印变量时ratingsCount …

reflection interface go

4
推荐指数
1
解决办法
1万
查看次数

在 Golang 中的两个不同结构字段中映射 Mongo _id

我正在开发一个使用 Go 和 MongoDB 组合的项目。我被困在我有一个结构的地方:

type Booking struct {
    // booking fields
    Id                          int                 `json:"_id,omitempty" bson:"_id,omitempty"`
    Uid                         int                 `json:"uid,omitempty" bson:"uid,omitempty"`
    IndustryId                  int                 `json:"industry_id,omitempty" bson:"industry_id,omitempty"`
    LocationId                  int                 `json:"location_id,omitempty" bson:"location_id,omitempty"`
    BaseLocationId              int                 `json:"base_location_id,omitempty" bson:"base_location_id,omitempty"`
    }
Run Code Online (Sandbox Code Playgroud)

在这个结构中,字段Idint类型的。但是我们知道 MongoDB 的默认 id 是bsonObject类型。有时,系统会在Id字段中生成默认的 MongoDB id 。

为了克服这个问题,我修改了结构如下:

type Booking struct {
        // booking fields
        Id                          int                 `json:"_id,omitempty" bson:"_id,omitempty"`
        BsonId              bson.ObjectId       `json:"bson_id" bson:"_id,omitempty"`
        Uid                         int                 `json:"uid,omitempty" bson:"uid,omitempty"`
        IndustryId                  int                 `json:"industry_id,omitempty" bson:"industry_id,omitempty"`
        LocationId                  int                 `json:"location_id,omitempty" bson:"location_id,omitempty"`
        BaseLocationId              int                 `json:"base_location_id,omitempty" …
Run Code Online (Sandbox Code Playgroud)

struct go mongodb mgo

4
推荐指数
1
解决办法
3271
查看次数

将 MongoDb 连接池与 Go 应用程序一起使用

我正在与 Mongodb 一起开发 Golang SAAS 应用程序。以前我在没有池的情况下使用数据库连接。因此,当一些流量进入​​时,我的数据库会挂起或关闭。

然后我开始了解连接池。我对此进行了探索,但我有些怀疑它是否适合我的应用程序结构。

我在这里提供了我的应用程序中的一些代码示例。

创建与数据库的连接的函数:

func ConnectDb(merchantDb string) (mongoSession *mgo.Session) {
    mongoDBDialInfo := &mgo.DialInfo{
        Addrs:     []string{DatabaseIpPort},
        Username:  DbUsername,
        Password:  DbPassword,
        Source:    DbSource,
        Database:  merchantDb,
        Timeout:   60 * time.Second,
        PoolLimit: 4096,
    }
    mongoSession, err := mgo.DialWithInfo(mongoDBDialInfo)
    if err != nil {
        fmt.Printf("CreateSession: %s\n", err)
        defer mongoSession.Close()
        return mongoSession
    }
    mongoSession.SetMode(mgo.Monotonic, true)
    return mongoSession
}
Run Code Online (Sandbox Code Playgroud)

连接到数据库的模型函数示例:

func (MerchantDb *MerchantDatabase) UpdateCustomer(uid int, query interface{}) (err error) {
    mongoSession := config.ConnectDb(MerchantDb.Database)
    defer mongoSession.Close()

    sessionCopy := mongoSession.Copy()
    defer sessionCopy.Close()

    getCollection := …
Run Code Online (Sandbox Code Playgroud)

connection connection-pooling go mongodb

1
推荐指数
1
解决办法
2722
查看次数

reflect.DeepEqual() 返回 false 但切片相同

我正在比较两个切片,都是 type []int。一种是以json的形式进入API并解析为go struct的。在 struct 中,它被初始化为 empty []int{}。第二个保存在数据库(MongoDb)中,并被提取并映射到相同的结构类型。

在某些情况下,两个切片是完全空白的。但比较正在回归false

reflect.DeepEqual(oldSettings.S1, newSettings.S1)

我还使用检查了两个字段类型 reflect.TypeOf(newSettings.S1). []int两者都在重新调整。

请考虑此游乐场链接以获取结构示例。

https://play.golang.org/p/1JTUCPImxwq

type OldSettings struct {
    S1 []int
}

type NewSettings struct {
    S1 []int
}

func main() {
    oldSettings := OldSettings{}
    newSettings := NewSettings{}

    if reflect.DeepEqual(oldSettings.S1, newSettings.S1) == false {
        fmt.Println("not equal")
    } else {
        fmt.Println("equal")
    }
}
Run Code Online (Sandbox Code Playgroud)

谢谢!

go slice reflect

1
推荐指数
1
解决办法
590
查看次数

定义一个常量会消耗一些内存吗?

我正在使用 Go 构建一个应用程序。

我需要为架构目的定义很多常量。就像我们有一个名为的部分posts,我想对其执行一些操作。其日志将以 类型保存在系统中posts

问题

我有大约 50 个这样的部分。为了便于使用节类型,我想将节类型定义为常量。但是像变量一样在 Go 中消耗了一些空间,常量也是吗?我应该像这样定义它们用于多用途还是用posts字符串在任何地方引用类型。

我应该遵循什么来满足我的要求?

go

-1
推荐指数
1
解决办法
55
查看次数