Destination Handler

包路径: github.com/caicloud/nirvana/service

Nirvana 默认提供了 3 种类型的 Destination:Meta,Data,Error。

每种 Destination 对应一个 Handler。这些 Handler 负责一种类型的返回结果的数据转换工作。

  1. // DestinationHandler is used to handle the results from API handlers.
  2. type DestinationHandler interface {
  3. // Type returns definition.Type which the type handler can handle.
  4. Destination() definition.Destination
  5. // Priority returns priority of the type handler. Type handler with higher priority will prior execute.
  6. Priority() int
  7. // Validate validates whether the type handler can handle the target type.
  8. Validate(target reflect.Type) error
  9. // Handle handles a value. If the handler has something wrong, it should return an error.
  10. // The handler descides how to deal with value by producers and status code.
  11. // The status code is a success status code. If everything is ok, the handler should use the status code.
  12. //
  13. // There are three cases for return values (goon means go on or continue):
  14. // 1. go on is true, err is nil.
  15. // It means that current type handler did nothing (or looks like did nothing) and next type handler
  16. // should take the context.
  17. // 2. go on is false, err is nil.
  18. // It means that current type handler has finished the context and next type handler should not run.
  19. // 3. err is not nil
  20. // It means that current type handler handled the context but something wrong. All subsequent type
  21. // handlers should not run.
  22. Handle(ctx context.Context, producers []Producer, code int, value interface{}) (goon bool, err error)
  23. }

如果 Nirvana 默认提供的 Handler 不能满足实际的业务需求,可以通过 service 包提供的方法注册自定义的 Handler:

  1. // RegisterDestinationHandler registers a type handler.
  2. func RegisterDestinationHandler(handler DestinationHandler) error

Definition Handler 存在优先级,优先级高的 Handler 先执行。并且执行之后会返回 goon,用来确定是否需要执行下一个 Handler。