options.go 2.2 KB

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