deprecation.go 2.1 KB

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