Help Sending JSON API Spec. Json

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.


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 {
	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 {
	} else if count > 0 {
		fmt.Printf("User %v already exists\n", user.Email)
	} else {
		c.JSON(200, user)
} might be what you are looking for.


That looks like it will do it, I’ll give it a shot and see if I can get it working. Thanks!

1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.