ZH_Return

Lunny Xiao edited this page Apr 11, 2017 · 2 revisions

返回值

根据函数或者结构体方法的返回值,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()
}
You can’t perform that action at this time.
You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session.
Press h to open a hovercard with more details.