[go]beego獲取參數/返回參數

獲取前端傳來的參數

獲取數據並轉爲對應的類型

- ?id=111&id=122
c.GetInt("id")
int,111

- ?id=111&id=122
c.GetBool("id")
bool,false


- ?id=111&id=122
c.GetString("id")
string,"111"

- ?id=111&id=122
c.GetStrings("id")
[]string,[]string{"111", "122"}


- ?id=111&id=122
c.Input().Get("id")
string,"111"

解析表單

  • c.ParseForm 直接解析到 struct
type user struct {
    Id    int         `form:"-"`
    Name  interface{} `form:"name"`
    Age   int         `form:"age"`
    Email string
}

func (c *MainController) Post() {
    u := user{}
    c.ParseForm(&u)

    fmt.Printf("%T,%#v\n", u, u)
    c.Ctx.WriteString("hello")
}

解析Request Body

  • 獲取 Request Body 裏的內容
type user struct {
    Id    int         `json:"-"`
    Name  interface{} `json:"name"`
    Age   int         `json:"age"`
    Email string
}

func (c *MainController) Post() {
    var u user
    json.Unmarshal(c.Ctx.Input.RequestBody, &u)
    fmt.Printf("%T,%#v\n", u, u)
    c.Ctx.WriteString("hello")
}

上傳文件

<form enctype="multipart/form-data" method="post" action="http://localhost:8080/">
    <input type="file" name="uploadname" />
    <input type="submit">
</form>

func (c *MainController) Post() {
    f, h, err := c.GetFile("uploadname")
    if err != nil {
        log.Fatal("getfile err ", err)
    }
    fmt.Printf("%T,%#v\n", f, f)
    defer f.Close()
    c.SaveToFile("uploadname", "static/upload/" + h.Filename) // 保存位置在 static/upload, 沒有文件夾要先建立
    c.Ctx.WriteString("post")
}

後端返回數據到前端

  • 返回字符串
c.Ctx.WriteString("<h1>hello world</h1>")
  • 返回模板html
c.Data["name"] = "mm"
c.Data["age"] = 22
c.TplName = "user.html"

<body>
    <h1>user</h1>
    {{.name}}
    {{.age}}
</body>
  • 返回json
type user struct {
    Name  string    `json:"name"`
    Age   int       `json:"age"`
    Birth time.Time `json:"birth"`
}

func (u *UserController) Get() {
    var p1 = &user{
        Name:  "mm",
        Age:   22,
        Birth: time.Now(),
    }

    u.Data["json"] = p1
    u.ServeJSON()
}
相關文章
相關標籤/搜索