1
0

db_config.go 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112
  1. package db
  2. import (
  3. "time"
  4. )
  5. const (
  6. defaultDriver = "mysql"
  7. defaultHost = "localhost"
  8. defaultPort = 3306
  9. defaultSslMode = "disabled"
  10. )
  11. type Config struct {
  12. driver string
  13. username string
  14. password string
  15. dbname string
  16. host string
  17. port uint16
  18. sslMode string
  19. maxOpenConns uint16
  20. maxIdleConns uint16
  21. maxConnLifetime *time.Duration
  22. maxIdleConnLifetime *time.Duration
  23. }
  24. type ConfigOption func(*Config)
  25. type ConfigOptions []ConfigOption
  26. func (s *ConfigOptions) Add(option ConfigOption) {
  27. *s = append(*s, option)
  28. }
  29. func NewConfig(opts ...ConfigOption) Config {
  30. c := &Config{}
  31. for _, opt := range opts {
  32. opt(c)
  33. }
  34. return *c
  35. }
  36. func WithDriver(driver string) ConfigOption {
  37. return func(s *Config) {
  38. s.driver = driver
  39. }
  40. }
  41. func WithUsername(username string) ConfigOption {
  42. return func(s *Config) {
  43. s.username = username
  44. }
  45. }
  46. func WithDatabase(dbname string) ConfigOption {
  47. return func(s *Config) {
  48. s.dbname = dbname
  49. }
  50. }
  51. func WithPassword(password string) ConfigOption {
  52. return func(s *Config) {
  53. s.password = password
  54. }
  55. }
  56. func WithHost(host string) ConfigOption {
  57. return func(s *Config) {
  58. s.host = host
  59. }
  60. }
  61. func WithPort(port uint16) ConfigOption {
  62. return func(s *Config) {
  63. s.port = port
  64. }
  65. }
  66. func WithSSLMode(sslMode string) ConfigOption {
  67. return func(s *Config) {
  68. s.sslMode = sslMode
  69. }
  70. }
  71. func WithMaxOpenConns(maxOpenConns uint16) ConfigOption {
  72. return func(s *Config) {
  73. s.maxOpenConns = maxOpenConns
  74. }
  75. }
  76. func WithMaxIdleConns(maxIdleConns uint16) ConfigOption {
  77. return func(s *Config) {
  78. s.maxIdleConns = maxIdleConns
  79. }
  80. }
  81. func WithMaxConnLifetime(lifetime time.Duration) ConfigOption {
  82. return func(s *Config) {
  83. s.maxConnLifetime = &lifetime
  84. }
  85. }
  86. func WithMaxIdleConnLifetime(lifetime time.Duration) ConfigOption {
  87. return func(s *Config) {
  88. s.maxIdleConnLifetime = &lifetime
  89. }
  90. }