db_config.go 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  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 WithDriver(driver string) ConfigOption {
  30. return func(s *Config) {
  31. s.driver = driver
  32. }
  33. }
  34. func WithUsername(username string) ConfigOption {
  35. return func(s *Config) {
  36. s.username = username
  37. }
  38. }
  39. func WithDatabase(dbname string) ConfigOption {
  40. return func(s *Config) {
  41. s.dbname = dbname
  42. }
  43. }
  44. func WithPassword(password string) ConfigOption {
  45. return func(s *Config) {
  46. s.password = password
  47. }
  48. }
  49. func WithHost(host string) ConfigOption {
  50. return func(s *Config) {
  51. s.host = host
  52. }
  53. }
  54. func WithPort(port uint16) ConfigOption {
  55. return func(s *Config) {
  56. s.port = port
  57. }
  58. }
  59. func WithSSLMode(sslMode string) ConfigOption {
  60. return func(s *Config) {
  61. s.sslMode = sslMode
  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. }