Home > Backend Development > Golang > How to Embed a Struct in Another Struct in Golang for Admin-Only Requests with MongoDB?

How to Embed a Struct in Another Struct in Golang for Admin-Only Requests with MongoDB?

Patricia Arquette
Release: 2024-11-17 07:50:03
Original
407 people have browsed it

How to Embed a Struct in Another Struct in Golang for Admin-Only Requests with MongoDB?

Embedding a Struct in Another Struct in Golang MongoDB

In this scenario, when a user makes a GET request for the user resource, only relevant fields are returned as JSON. Specifically, the Secret field is excluded due to its json:"-". However, for admin-only requests, returning the secret field is required.

Duplicating the User struct for admin requests is not ideal. The following solution attempts to embed User into adminUser:

type adminUser struct {      
  User
  Secret  string        `json:"secret,omitempty" bson:"secret,omitempty"`
}
Copy after login

However, this implementation returns only the Secret field, which is not the desired behavior. To achieve the desired result, utilize the bson package's inline flag:

type adminUser struct {
    User `bson:",inline"`
    Secret string `json:"secret,omitempty" bson:"secret,omitempty"`
}
Copy after login

Note that this may lead to duplicate key errors when reading from the database if both adminUser and User contain the Secret key.

An alternative approach is to remove the Secret field from User and only include it in adminUser. This ensures that writing to the secret field is restricted to admin users.

The above is the detailed content of How to Embed a Struct in Another Struct in Golang for Admin-Only Requests with MongoDB?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template