---
title: "beego框架获取http请求内容"
author: "hnus"
date: "2015-03-06T15:03:00Z"
tags: []
slug: "beego-http"
draft: false
lastmod: "2015-05-11T11:49:45Z"
id: 2210123
url: "https://hnus.iteye.com/blog/2210123"
---

使用beego api生成项目，没有使用swagger作为文档测试工具，采用postman发送请求后台接收到的参数全部为空，参考文档后发现postman发送的内容在通过request body获取的时候需要在app.conf中增加配置：

copyrequestbody = true

# 获取参数[](http://beego.me/docs/mvc/controller/params.md#%E8%8E%B7%E5%8F%96%E5%8F%82%E6%95%B0)

我们经常需要获取用户传递的数据，包括 Get、POST 等方式的请求，beego 里面会自动解析这些数据，你可以通过如下方式获取数据：

- GetString(key string) string
- GetStrings(key string) \[]string
- GetInt(key string) (int64, error)
- GetBool(key string) (bool, error)
- GetFloat(key string) (float64, error)

使用例子如下：

```
func (this *MainController) Post() {
    jsoninfo := this.GetString("jsoninfo")
    if jsoninfo == "" {
        this.Ctx.WriteString("jsoninfo is empty")
        return
    }
}
```

如果你需要的数据可能是其他类型的，例如是 int 类型而不是 int64，那么你需要这样处理：

```
func (this *MainController) Post() {
    id := this.Input().Get("id")
    intid, err := strconv.Atoi(id)
}
```

更多其他的 request 的信息，用户可以通过`this.Ctx.Request`获取信息，关于该对象的属性和方法参考手册[Request](http://gowalker.org/net/http#Request)。

## **获取 Request Body 里的内容[](http://beego.me/docs/mvc/controller/params.md#%E8%8E%B7%E5%8F%96-request-body-%E9%87%8C%E7%9A%84%E5%86%85%E5%AE%B9)**

在 API 的开发中，我们经常会用到`JSON`或`XML`来作为数据交互的格式，如何在 beego 中获取 Request Body 里的 JSON 或 XML 的数据呢？

1. 在配置文件里设置`copyrequestbody = true`
2. 在 Controller 中

```
func (this *ObejctController) Post() {
    var ob models.Object
    json.Unmarshal(this.Ctx.Input.RequestBody, &ob)
    objectid := models.AddOne(ob)
    this.Data["json"] = "{\"ObjectId\":\"" + objectid + "\"}"
    this.ServeJson()
}
```

原文来自：http://floss.zoomquiet.io/data/20131230001408/index.html