I am trying to create a rest API with golang. Each time a user is created, I would like to create a 'Profile' which is associated with that user.
My initial thought was to first create the user, and then separately create the profile referencing the user ID and inserting that into the database.
I'm not sure if this kind of thinking aligns with the way go should be used as i'm just starting with the language.
Using below code, I create the user, but cannot create the profile. I receive this error: using unaddressable value
var db *gorm.DB
func GetDB() *gorm.DB {
return db
}
type User struct {
gorm.Model
Email string `gorm:"type:varchar(100);unique_index"`
Password string `json:"password"`
Name string `json:"name"`
Token string `json:"token";sql:"-"`
}
type Profile struct {
gorm.Model
User User `gorm:"foreignkey:UserRefer"` // use UserRefer as foreign key
UserRefer uint
FirstName string `gorm:"default:'John'"`
LastName string `gorm:"default:'Doe'"`
Description string `gorm:"default:'Mysterious'"`
}
func (user *User) Create() (map[string]interface{}) {
if resp, ok := user.Validate(); !ok {
return resp
}
hashedPassword, _ := bcrypt.GenerateFromPassword([]byte(user.Password), bcrypt.DefaultCost)
user.Password = string(hashedPassword)
GetDB().Create(user)
profile := Profile{}
profile.UserRefer = user.ID
GetDB().Create(profile)
if user.ID <= 0 {
return u.Message(false, "Failed to create account, connection error.")
}
response := u.Message(true, "Account has been created")
response["user"] = user
return response
}
I'm hoping someone will be able to help me understand what is going wrong here?