options.go 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. package kos
  2. import (
  3. "context"
  4. "git.nspix.com/golang/kos/util/env"
  5. "git.nspix.com/golang/kos/util/ip"
  6. "git.nspix.com/golang/kos/util/sys"
  7. "os"
  8. "strings"
  9. "syscall"
  10. )
  11. type (
  12. Options struct {
  13. Name string
  14. Version string
  15. Address string
  16. Port int
  17. EnableDebug bool //开启调试模式
  18. DisableHttp bool //禁用HTTP入口
  19. DisableCommand bool //禁用命令行入口
  20. DisableStateApi bool //禁用系统状态接口
  21. Metadata map[string]string //原数据
  22. Context context.Context
  23. Signals []os.Signal
  24. server Server
  25. shortName string
  26. }
  27. Option func(o *Options)
  28. )
  29. func (o *Options) ShortName() string {
  30. if o.shortName != "" {
  31. return o.shortName
  32. }
  33. if pos := strings.LastIndex(o.Name, "/"); pos != -1 {
  34. o.shortName = o.Name[pos+1:]
  35. } else {
  36. o.shortName = o.Name
  37. }
  38. return o.shortName
  39. }
  40. func WithName(name string, version string) Option {
  41. return func(o *Options) {
  42. o.Name = name
  43. o.Version = version
  44. }
  45. }
  46. func WithPort(port int) Option {
  47. return func(o *Options) {
  48. o.Port = port
  49. }
  50. }
  51. func WithServer(s Server) Option {
  52. return func(o *Options) {
  53. o.server = s
  54. }
  55. }
  56. func WithDebug() Option {
  57. return func(o *Options) {
  58. o.EnableDebug = true
  59. }
  60. }
  61. func NewOptions() *Options {
  62. opts := &Options{
  63. Name: env.Get(EnvAppName, sys.Hostname()),
  64. Version: env.Get(EnvAppVersion, "0.0.1"),
  65. Context: context.Background(),
  66. Metadata: make(map[string]string),
  67. Signals: []os.Signal{syscall.SIGTERM, syscall.SIGINT, syscall.SIGQUIT, syscall.SIGKILL},
  68. }
  69. opts.Port = int(env.Integer(EnvAppPort, 80))
  70. opts.Address = env.Get(EnvAppAddress, ip.Internal())
  71. return opts
  72. }