---
title: "beego中路由（Router）参数和表单（Form）参数的区别和获取"
author: "hnus"
date: "2015-03-18T17:31:00Z"
tags: []
slug: "beego-router-form"
draft: false
lastmod: "2015-05-11T11:49:44Z"
id: 2210121
url: "https://hnus.iteye.com/blog/2210121"
---

在beego中，视图层有两种叫做参数的东西，有时候很让人困惑。它们分别是路由参数和表单参数。

beego的路由映射支持灵活的结构，比如对于这种`/blog/:catName`可以表示的是某一个分类下的blog列表，那么这里的`:catName`就是`路由参数`；如果说我们要对这个分类下面的blog进行分页，想查看第10页的blog，那么我们的url可能变成了`/blog/:catName?page=10`这种格式，那么这里的`page`就是`表单参数`。表单参数既可以是GET类型的参数也可以是POST类型的参数，总之都叫做表单参数。

1\. 获取路由参数的方法

可以使用下面的方法来获取路由参数：

方法 原型 GetInt func (c \*Controller) GetInt(key string) (int64, error) GetBool func (c \*Controller) GetBool(key string) (bool, error) GetFloat func (c \*Controller) GetFloat(key string) (float64, error) GetString func (c \*Controller) GetString(key string) string

我们为了演示这些方法构建了一个路径:

```
beego.Router("/blog/:catId/:catName:/:catPublish:/:catPrice", &controllers.MainController{}, "get:Blog")
```

然后我们可以用下面的方法获取路径参数：

```
func (this *MainController) Blog() {
    catId, _ := this.GetInt(":catId")
    catName := this.GetString(":catName")
    catPublish, _ := this.GetBool(":catPublish")
    catPrice, _ := this.GetFloat(":catPrice")
    beego.Debug(fmt.Sprintf("Category Id:%d Name:%s Publish:%v Price:%f", catId, catName, catPublish, catPrice))
}
```

然后访问`http://localhost:8080/blog/30/beego/true/98.45`，可以得到下面的输出：

> 2014/09/02 14:25:04 \[D] Category Id:30 Name:beego Publish:true Price:98.450000  
> 2014/09/02 14:25:04 \[C] the request url is /blog/30/beego/true/98.45

其实我们可以去看看这些Get方法，比如GetString（github.com/astaxie/beego/controller.go 367行）:

```
func (c *Controller) GetString(key string) string {
    return c.Ctx.Input.Query(key)
}
```

从上面的代码可以看到实际上这些路径参数都是从`c.Ctx.Input`里面获取的，而这个参数类型是`Context`，定义在`github.com/astaxie/beego/context/context.go`里面。

```
type Context struct {
    Input          *BeegoInput
    Output         *BeegoOutput
    Request        *http.Request
    ResponseWriter http.ResponseWriter
    _xsrf_token    string
}
```

然后我们再看看`Context`里面的`Input`,这是一个`*BeegoInput`类型（定义在`github.com/astaxie/beego/context/input.go`）里面：

```
type BeegoInput struct {
    CruSession    session.SessionStore
    Params        map[string]string
    Data          map[interface{}]interface{} // store some values in this context when calling context in filter or controller.
    Request       *http.Request
    RequestBody   []byte
    RunController reflect.Type
    RunMethod     string
}
```

然后我们再看这个结构体的`Query`方法的定义：

```
// Query returns input data item string by a given string.
func (input *BeegoInput) Query(key string) string {
    if val := input.Param(key); val != "" {
        return val
    }
    if input.Request.Form == nil {
        input.Request.ParseForm()
    }
    return input.Request.Form.Get(key)
}
```

我们惊奇地发现这个`Query`方法并不单纯，它同时支持查询路由参数和表单参数。所以一般情况下你也可以用来查询表单参数。

2\. 获取表单参数的方法  
上面我们看过了获取路由参数的方法，这里我们再看一下获取表单参数的方法。在上面的获取路由参数的讲解最后，我们发现可以使用和上面相同的方法来获取表单参数。

方法 原型 GetInt func (c \*Controller) GetInt(key string) (int64, error) GetBool func (c \*Controller) GetBool(key string) (bool, error) GetFloat func (c \*Controller) GetFloat(key string) (float64, error) GetString func (c \*Controller) GetString(key string) string

验证很简单，使用这样的url：`http://localhost:8080/blog/30/beego/true/98.45?page=10`和代码：

```
page, _ := this.GetInt("page")
beego.Debug("Page", page)
```

输出:

> 2014/09/02 14:41:07 \[D] Page 10

当然除了上面的方法之外，还有两个方法可以用来获取表单参数：

名称 原型 描述 GetStrings func (c \*Controller) GetStrings(key string) \[]string 用来获取比如多选框的值 GetFile func (c \*Controller) GetFile(key string) (multipart.File, \*multipart.FileHeader, error) 用来获取上传的文件

好了，其实一般情况下，获取路由参数和表单参数不会对用户如此透明，直接用`GetXXX`方法获取就可以了。

作者[jemygraw](http://golanghome.com/user/jemygraw)•2014-09-02•[](http://golanghome.com/user/jemygraw)

http://golanghome.com/post/327