Hello, I’m new to Go and I’m trying to setup a backend server that returns JSON API spec Json to a Javascript front end. But I’m unsure how I structure the Json in a way that follows the specifications set by Json Api.
I just need to be pointed in the right direction and a little help figuring it out. Right now I have a User struct and a method that creates a user. If it matters I’m currently using mgo for my database and Gin for a web framework.
If anyone can help that’d be great.
Thanks
User Struct:
type User struct {
ID bson.ObjectId `json:"id" bson:"_id"`
Email string `json:"email" bson:"email" valid:"email"`
FirstName string `json:"firstname" bson:"firstName" valid:"alphanum"`
LastName string `json:"lastname" bson:"lastName" valid:"alphanum"`
Password string `json:"password" bson:"password"`
Token string `json:"token" bson:"token"`
}
CreateUser Method:
func CreateUser(c *gin.Context) {
col := s.DB("MattsLab-Backend").C("Users")
email := c.PostForm("email")
firstname := c.PostForm("firstname")
lastname := c.PostForm("lastname")
password := c.PostForm("password")
hashedPassword, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
if err != nil {
panic(err)
}
user := &User{
ID: bson.NewObjectId(),
Email: email,
FirstName: firstname,
LastName: lastname,
Password: string(hashedPassword),
}
count, err := col.Find(bson.M{"email": user.Email}).Limit(1).Count()
if err != nil {
fmt.Println(err)
} else if count > 0 {
fmt.Printf("User %v already exists\n", user.Email)
} else {
col.Insert(user)
c.JSON(200, user)
}
}