return_handler.go 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. // Copyright 2013 Martini Authors
  2. // Copyright 2014 The Macaron Authors
  3. //
  4. // Licensed under the Apache License, Version 2.0 (the "License"): you may
  5. // not use this file except in compliance with the License. You may obtain
  6. // a copy of the License at
  7. //
  8. // http://www.apache.org/licenses/LICENSE-2.0
  9. //
  10. // Unless required by applicable law or agreed to in writing, software
  11. // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
  12. // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
  13. // License for the specific language governing permissions and limitations
  14. // under the License.
  15. package macaron
  16. import (
  17. "net/http"
  18. "reflect"
  19. "github.com/go-macaron/inject"
  20. )
  21. // ReturnHandler is a service that Martini provides that is called
  22. // when a route handler returns something. The ReturnHandler is
  23. // responsible for writing to the ResponseWriter based on the values
  24. // that are passed into this function.
  25. type ReturnHandler func(*Context, []reflect.Value)
  26. func canDeref(val reflect.Value) bool {
  27. return val.Kind() == reflect.Interface || val.Kind() == reflect.Ptr
  28. }
  29. func isError(val reflect.Value) bool {
  30. _, ok := val.Interface().(error)
  31. return ok
  32. }
  33. func isByteSlice(val reflect.Value) bool {
  34. return val.Kind() == reflect.Slice && val.Type().Elem().Kind() == reflect.Uint8
  35. }
  36. func defaultReturnHandler() ReturnHandler {
  37. return func(ctx *Context, vals []reflect.Value) {
  38. rv := ctx.GetVal(inject.InterfaceOf((*http.ResponseWriter)(nil)))
  39. resp := rv.Interface().(http.ResponseWriter)
  40. var respVal reflect.Value
  41. if len(vals) > 1 && vals[0].Kind() == reflect.Int {
  42. resp.WriteHeader(int(vals[0].Int()))
  43. respVal = vals[1]
  44. } else if len(vals) > 0 {
  45. respVal = vals[0]
  46. if isError(respVal) {
  47. err := respVal.Interface().(error)
  48. if err != nil {
  49. ctx.internalServerError(ctx, err)
  50. }
  51. return
  52. } else if canDeref(respVal) {
  53. if respVal.IsNil() {
  54. return // Ignore nil error
  55. }
  56. }
  57. }
  58. if canDeref(respVal) {
  59. respVal = respVal.Elem()
  60. }
  61. if isByteSlice(respVal) {
  62. resp.Write(respVal.Bytes())
  63. } else {
  64. resp.Write([]byte(respVal.String()))
  65. }
  66. }
  67. }