modrevision.go 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. package modrevision
  2. import (
  3. "fmt"
  4. "strings"
  5. "time"
  6. "github.com/kataras/iris/v12/context"
  7. )
  8. func init() {
  9. context.SetHandlerName("iris/middleware/modrevision.*", "iris.modrevision")
  10. }
  11. // Options holds the necessary values to render the server name, environment and build information.
  12. // See the `New` package-level function.
  13. type Options struct {
  14. // The ServerName, e.g. Iris Server.
  15. ServerName string
  16. // The Environment, e.g. development.
  17. Env string
  18. // The Developer, e.g. kataras.
  19. Developer string
  20. // True to display the build time as unix (seconds).
  21. UnixTime bool
  22. // A non nil time location value to customize the display of the build time.
  23. TimeLocation *time.Location
  24. }
  25. // New returns an Iris Handler which renders
  26. // the server name (env), build information (if available)
  27. // and an OK message. The handler displays simple debug information such as build commit id and time.
  28. // It does NOT render information about the Go language itself or any operating system confgiuration
  29. // for security reasons.
  30. //
  31. // Example Code:
  32. //
  33. // app.Get("/health", modrevision.New(modrevision.Options{
  34. // ServerName: "Iris Server",
  35. // Env: "development",
  36. // Developer: "kataras",
  37. // TimeLocation: time.FixedZone("Greece/Athens", 7200),
  38. // }))
  39. func New(opts Options) context.Handler {
  40. buildTime, buildRevision := context.BuildTime, context.BuildRevision
  41. if opts.UnixTime {
  42. if t, err := time.Parse(time.RFC3339, buildTime); err == nil {
  43. buildTime = fmt.Sprintf("%d", t.Unix())
  44. }
  45. } else if opts.TimeLocation != nil {
  46. if t, err := time.Parse(time.RFC3339, buildTime); err == nil {
  47. buildTime = t.In(opts.TimeLocation).String()
  48. }
  49. }
  50. var buildInfo string
  51. if buildInfo = opts.ServerName; buildInfo != "" {
  52. if env := opts.Env; env != "" {
  53. buildInfo += fmt.Sprintf(" (%s)", env)
  54. }
  55. }
  56. if buildRevision != "" && buildTime != "" {
  57. buildTitle := ">>>> build"
  58. tab := strings.Repeat(" ", len(buildTitle))
  59. buildInfo += fmt.Sprintf("\n\n%s\n%[2]srevision %[3]s\n%[2]sbuildtime %[4]s\n%[2]sdeveloper %[5]s",
  60. buildTitle, tab, buildRevision, buildTime, opts.Developer)
  61. }
  62. contents := []byte(buildInfo)
  63. if len(contents) > 0 {
  64. contents = append(contents, []byte("\n\nOK")...)
  65. } else {
  66. contents = []byte("OK")
  67. }
  68. return func(ctx *context.Context) {
  69. ctx.Write(contents)
  70. }
  71. }