2 ZH_Return
Lunny Xiao edited this page 6 years ago
This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

返回值

根据函数或者结构体方法的返回值returnHandle 插件将自动将内容写入到 ResponseWriter. 目前支持的返回值及对应的行为如下:

  • string 返回string将会把string转为[]byte同时写入到ResponseWriter

  • []byte 返回[]byte将会直接写入ResponseWriter

  • error 返回错误如果error不为nil, 则写入返回头500内容为error.Error()

  • AbortError 如果返回AbortError, 则写入返回头AbortError.Code内容为AbortError.Error()

如果包含了匿名结构体tango.JSON或者tango.XML,则返回值的行为将会发生变化:

  • error 返回值为error如果是Json则会生成{"err": err.Error()}的Json格式

  • map, slice, structs 返回值为map如果是Json则会自动序列化为Json格式。

例子代码如下:

type Action struct {
    tango.JSON
}

var i int
func (Action) Get() interface{} {
   if i == 0 {
       i = i + 1
       return map[string]interface{}{"i":i}
   }
   return errors.New("could not visit")
}

func main() {
    t := tango.Classic()
    t.Any("/", new(Action))
    t.Run()
}
Table of Contents