beego框架获取http请求内容

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

copyrequestbody = true


获取参数

我们经常需要获取用户传递的数据,包括 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

获取 Request Body 里的内容

在 API 的开发中,我们经常会用到JSONXML来作为数据交互的格式,如何在 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


你可能感兴趣的:(http)