options.go 1.7 KB

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