Elliot
Elliot

Reputation: 580

beego api post insert data

First of all. I use postman to POST data. How to take data from the postman key. It works by using this way (in my code I set it by myself).

I want to get firstname, lastname, email in form-data. I want to use as below.

func InsertOneUser(user User) *User {
   o := orm.NewOrm()
   qs := o.QueryTable(new(User))
   i, _ := qs.PrepareInsert()
   var u User
   user.FirstName = "firstname"                          <----- this
   user.LastName = "lastname"                            <----- this
   user.Email = "[email protected]"                    <----- this
   user.Password, _ = hashPassword(user.Password)
   user.RegDate = time.Now()
   id, err := i.Insert(&user)
   return &u
}

enter image description here

Upvotes: 1

Views: 742

Answers (1)

sh.seo
sh.seo

Reputation: 1610

You need beego.Controller in func. if func has beego.Controller, there are two ways(key, parseform).

package main

import (
    "fmt"

    "github.com/astaxie/beego"
)

type User struct {
    Firstname string `form:"firstname"`
    Lastname  string `form:"lastname"`
    Email     string `form:"email"`
}

type MainController struct {
    beego.Controller
}

func (this *MainController) Post() {
    // using key
    firstname := this.GetString("firstname")
    lastname := this.GetString("lastname")
    email := this.GetString("email")

    // using Parseform
    u := User{}
    if err := this.ParseForm(&u); err != nil {
        fmt.Println(err)
    }

    fmt.Println(u)
    this.Ctx.WriteString(fmt.Sprintf("%s %s %s", firstname, lastname, email))
}

func main() {
    beego.Router("/api/v1/user", &MainController{})
    beego.Run()
}

Upvotes: 1

Related Questions