1
0

db_config.go 1.7 KB

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