php editor Yuzai introduces you to a method of importing a structure in JSON and renaming it, that is, using the "GO" keyword. In JSON, we often need to use a defined structure, but sometimes we need to rename it to suit specific needs. Using the "GO" keyword, we can rename the structure while importing it to better meet our needs. This method is simple and easy to use, allowing us to process JSON data more flexibly. Next, let’s learn about the specific steps!
I used gorm to create a database. To do this, I created a structure and created a table using that structure. So far, so good. On the backend, everything works fine, but on the frontend, the problem is that the json call always returns an uppercase id, while swagger generates a lowercase id. Is there a way in go to override a struct imported from gorm using a json identifier?
import "gorm.io/gorm" type report struct { gorm.model createdby user `gorm:"foreignkey:createdbyuserid" json:"createdby"` archived bool `json:"archived"` }
This structure gives me the following response
{ "ID": 8, "CreatedAt": "2022-11-15T20:45:16.83+01:00", "UpdatedAt": "2022-12-27T21:34:17.871+01:00", "DeletedAt": null "createdBy": { "ID": 1, "CreatedAt": "2022-11-15T20:02:17.497+01:00", "UpdatedAt": "2022-11-15T20:02:17.497+01:00", ... }, "archived": true, }
Is there a way to make the id lowercase (like archived
)? Or I could adjust it in swaggo so that it generates in uppercase.
What I see is that you can make the table without this gorm.model
and define all the properties yourself. The problem is that I have to create all the functionality of these columns myself (delete, update, index, primary key...).
I create my own gorm-model-struct:
type gormmodel struct { id uint `gorm:"primarykey" json:"id"` createdat time.time `json:"createdat"` updatedat time.time `json:"updatedat"` deletedat gorm.deletedat `gorm:"index" json:"deletedat"` } //@name models.gormmodel
I import this structure into other structures:
type Report struct { GormModel CreatedBy User `gorm:"foreignKey:CreatedByUserID" json:"createdBy"` Archived bool `json:"archived"` }
It is important that you add json-key and set the property name.
The above is the detailed content of GO: import a struct and rename it in json. For more information, please follow other related articles on the PHP Chinese website!