# 请求参数与返回值

## 请求参数

### Header参数

可以通过如下的方式获取basic auth中的username与password

```
func (controller *YourController) youFunc() {
    username, password, ok := controller.Ctx.Request.BasicAuth()
}
```

### Query参数

query参数都是key-value对，key都为string，可以通过如下的方法获取不同类型的value：

```
GetString(key string) string            # 若key不存在，返回空串
GetStrings(key string) []string        # 若key不存在，返回nil
GetInt(key string) (int64, error)        # 若key不存在?
GetBool(key string) (bool, error)        # 若key不存在?
GetFloat(key string) (float64, error)    # 若key不存在?
```

**示例：**

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

### Path参数

假设有如下的路由规则：

```
beego.Router("/api/users/:id", &api.UserAPI{})
```

我们可以通过下面的方法获取Path参数`:id`的值，返回的是一个string

```
func (controller *YourController) youFunc() {
    id := controller.Ctx.Input.Param(":id")
}
```

### body参数

body参数一般都是Json对象，假设Body参数的示例如下：

```
{
    "param1" : string,
    "param2" : integer
}
```

则在先要定义一个`Struct`来接收来匹配这个Json对象：

```
type Param struct {
    Param1 string `json:"param1"`
    Param2 int    `json:"param2"`
}
```

然后在Controller的相应方法（比如`Post()`）中，使用如下方法来获取参数：

```
func (c *MainController) Post() {
    var param Param
    err := json.Unmarshal(c.Ctx.Input.CopyBody(1<<32), &param)    // 参考harbor
    if err != nil {
        // do something and abort
    }
    // fmt.Print(param.Param1)
}
```

当然，我们的`Param`结构体定义了两个变量，但如果请求body中只传了一个参数呢？或者body中多传了一个参数呢？

针对这两种情况，实际的结果如下：

* body中少传了参数

这种情况下，少传的那个参数在接收体`param`中会默认被设为"零值"

* body中多传了参数

多传的参数会被忽略，在接收体`param`中拿不到

## 返回值

### json

通过以下的方式可以返回一个Json串，其中Object要为一个可以转化为Json串的对象，比如struct、array。

```
func (controller *YourController) yourFunc() {
    // code 
    controller.Data["json"] = Object
    controller.ServeJSON()
}
```

### string

```
func (controller *YourController) yourFunc() {
    // code 
    controller.Ctx.WriteString("hello world")
}
```

### 无返回值

如果处理函数没有返回值，那么默认会去到模板目录下查找 `<Controller名>/<方法名>.tpl` 文件进行渲染，例如上面的方法会去寻找 yourcontroller/yourfunc.tpl (文件、文件夹必须小写)。如果不想进行渲染，则需要在函数中显示设置 `controller.EnableRender = false`


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://pshizhsysu.gitbook.io/beego/controller/qing-qiu-can-shu.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
