mongo.go 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. package config
  2. import (
  3. "fmt"
  4. "strings"
  5. )
  6. type Mongo struct {
  7. Coll string `json:"coll" yaml:"coll" mapstructure:"coll"` // collection name
  8. Options string `json:"options" yaml:"options" mapstructure:"options"` // mongodb options
  9. Database string `json:"database" yaml:"database" mapstructure:"database"` // database name
  10. Username string `json:"username" yaml:"username" mapstructure:"username"` // 用户名
  11. Password string `json:"password" yaml:"password" mapstructure:"password"` // 密码
  12. AuthSource string `json:"auth-source" yaml:"auth-source" mapstructure:"auth-source"` // 验证数据库
  13. MinPoolSize uint64 `json:"min-pool-size" yaml:"min-pool-size" mapstructure:"min-pool-size"` // 最小连接池
  14. MaxPoolSize uint64 `json:"max-pool-size" yaml:"max-pool-size" mapstructure:"max-pool-size"` // 最大连接池
  15. SocketTimeoutMs int64 `json:"socket-timeout-ms" yaml:"socket-timeout-ms" mapstructure:"socket-timeout-ms"` // socket超时时间
  16. ConnectTimeoutMs int64 `json:"connect-timeout-ms" yaml:"connect-timeout-ms" mapstructure:"connect-timeout-ms"` // 连接超时时间
  17. IsZap bool `json:"is-zap" yaml:"is-zap" mapstructure:"is-zap"` // 是否开启zap日志
  18. Hosts []*MongoHost `json:"hosts" yaml:"hosts" mapstructure:"hosts"` // 主机列表
  19. }
  20. type MongoHost struct {
  21. Host string `json:"host" yaml:"host" mapstructure:"host"` // ip地址
  22. Port string `json:"port" yaml:"port" mapstructure:"port"` // 端口
  23. }
  24. // Uri .
  25. func (x *Mongo) Uri() string {
  26. length := len(x.Hosts)
  27. hosts := make([]string, 0, length)
  28. for i := 0; i < length; i++ {
  29. if x.Hosts[i].Host != "" && x.Hosts[i].Port != "" {
  30. hosts = append(hosts, x.Hosts[i].Host+":"+x.Hosts[i].Port)
  31. }
  32. }
  33. if x.Options != "" {
  34. return fmt.Sprintf("mongodb://%s/%s?%s", strings.Join(hosts, ","), x.Database, x.Options)
  35. }
  36. return fmt.Sprintf("mongodb://%s/%s", strings.Join(hosts, ","), x.Database)
  37. }