deprecation.go 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. package versioning
  2. import (
  3. "time"
  4. "github.com/kataras/iris/context"
  5. )
  6. // DeprecationOptions describes the deprecation headers key-values.
  7. // - "X-API-Warn": options.WarnMessage
  8. // - "X-API-Deprecation-Date": context.FormatTime(ctx, options.DeprecationDate))
  9. // - "X-API-Deprecation-Info": options.DeprecationInfo
  10. type DeprecationOptions struct {
  11. WarnMessage string
  12. DeprecationDate time.Time
  13. DeprecationInfo string
  14. }
  15. // ShouldHandle reports whether the deprecation headers should be present or no.
  16. func (opts DeprecationOptions) ShouldHandle() bool {
  17. return opts.WarnMessage != "" || !opts.DeprecationDate.IsZero() || opts.DeprecationInfo != ""
  18. }
  19. // DefaultDeprecationOptions are the default deprecation options,
  20. // it defaults the "X-API-Warn" header to a generic message.
  21. var DefaultDeprecationOptions = DeprecationOptions{
  22. WarnMessage: "WARNING! You are using a deprecated version of this API.",
  23. }
  24. // WriteDeprecated writes the deprecated response headers
  25. // based on the given "options".
  26. // It can be used inside a middleware.
  27. //
  28. // See `Deprecated` to wrap an existing handler instead.
  29. func WriteDeprecated(ctx *context.Context, options DeprecationOptions) {
  30. if options.WarnMessage == "" {
  31. options.WarnMessage = DefaultDeprecationOptions.WarnMessage
  32. }
  33. ctx.Header("X-API-Warn", options.WarnMessage)
  34. if !options.DeprecationDate.IsZero() {
  35. ctx.Header("X-API-Deprecation-Date", context.FormatTime(ctx, options.DeprecationDate))
  36. }
  37. if options.DeprecationInfo != "" {
  38. ctx.Header("X-API-Deprecation-Info", options.DeprecationInfo)
  39. }
  40. }
  41. // Deprecated marks a specific handler as a deprecated.
  42. // Deprecated can be used to tell the clients that
  43. // a newer version of that specific resource is available instead.
  44. func Deprecated(handler context.Handler, options DeprecationOptions) context.Handler {
  45. return func(ctx *context.Context) {
  46. WriteDeprecated(ctx, options)
  47. handler(ctx)
  48. }
  49. }