options.go 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  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. "strconv"
  9. "strings"
  10. "syscall"
  11. )
  12. type (
  13. Options struct {
  14. Name string //名称
  15. Version string //版本号
  16. Address string //绑定地址
  17. Port int //端口
  18. EnableDebug bool //开启调试模式
  19. DisableHttp bool //禁用HTTP入口
  20. EnableDirectHttp bool //启用HTTP直连模式
  21. DisableCommand bool //禁用命令行入口
  22. EnableDirectCommand bool //启用命令行直连模式
  23. DisableStateApi bool //禁用系统状态接口
  24. Metadata map[string]string //原数据
  25. Context context.Context
  26. Signals []os.Signal
  27. server Server
  28. shortName string
  29. }
  30. Option func(o *Options)
  31. )
  32. func (o *Options) ShortName() string {
  33. if o.shortName != "" {
  34. return o.shortName
  35. }
  36. if pos := strings.LastIndex(o.Name, "/"); pos != -1 {
  37. o.shortName = o.Name[pos+1:]
  38. } else {
  39. o.shortName = o.Name
  40. }
  41. return o.shortName
  42. }
  43. func WithName(name string, version string) Option {
  44. return func(o *Options) {
  45. o.Name = name
  46. o.Version = version
  47. }
  48. }
  49. func WithPort(port int) Option {
  50. return func(o *Options) {
  51. o.Port = port
  52. }
  53. }
  54. func WithServer(s Server) Option {
  55. return func(o *Options) {
  56. o.server = s
  57. }
  58. }
  59. func WithDebug() Option {
  60. return func(o *Options) {
  61. o.EnableDebug = true
  62. }
  63. }
  64. func WithDirectHttp() Option {
  65. return func(o *Options) {
  66. o.DisableCommand = true
  67. o.EnableDirectHttp = true
  68. }
  69. }
  70. func WithDirectCommand() Option {
  71. return func(o *Options) {
  72. o.DisableHttp = true
  73. o.EnableDirectCommand = true
  74. }
  75. }
  76. func NewOptions(cbs ...Option) *Options {
  77. opts := &Options{
  78. Name: env.Get(EnvAppName, sys.Hostname()),
  79. Version: env.Get(EnvAppVersion, "0.0.1"),
  80. Context: context.Background(),
  81. Metadata: make(map[string]string),
  82. Signals: []os.Signal{syscall.SIGTERM, syscall.SIGINT, syscall.SIGQUIT, syscall.SIGKILL},
  83. }
  84. opts.Port = int(env.Integer(18080, EnvAppPort, "HTTP_PORT", "KOS_PORT"))
  85. opts.Address = env.Getter(ip.Internal(), EnvAppAddress, "KOS_ADDRESS")
  86. opts.EnableDebug, _ = strconv.ParseBool(env.Getter("false", EnvAppDebug, "KOS_DEBUG"))
  87. for _, cb := range cbs {
  88. cb(opts)
  89. }
  90. return opts
  91. }