Go Series: Learning How to Build a Web Service Using Go from Scratch Pt. 11 — Gorm and Repos

Jonathan Chao
4 min readJun 16, 2023

Last time we’ve created a model that we can use to marshal and unmarshal for JSON. It also acts as the object part of ORM for GORM.

type User struct {
UUID string `gorm:"primaryKey"`
Name string `gorm:"column:user_name"` // set name to `user_name`
Email *string `gorm:"column:user_email"` // set name to `user_email`
Age uint8
Birthday *time.Time
MemberNumber sql.NullString `gorm:"index"`
ActivatedAt sql.NullTime
CreatedAt time.Time `json:"userCreatedAt" gorm:"column:createdAt"`
UpdatedAt time.Time `json:"userUpdatedAt" gorm:"column:UpdatedAt; autoCreateTime"` // note that these configs are separated by ;
}

We’ve also talked about embedded structure. From the above, the CreatedAt and UpdatedAt can be used for all sorts of models, so it makes sense to separate them. Say we create a struct called Base that contains these two attributes. Then we embed it to our User struct

type Base struct {
CreatedAt time.Time `json:"userCreatedAt" gorm:"column:createdAt"`
UpdatedAt time.Time `json:"userUpdatedAt" gorm:"column:UpdatedAt; autoCreateTime"`
}

type User struct {
Base // embedded Base struct
UUID string `gorm:"primaryKey"`
Name string…

--

--

Jonathan Chao
Jonathan Chao

Written by Jonathan Chao

I am a software developer who has been in this industry for close to a decade. I share my experience to people who are or want to get into the industry

No responses yet