diff --git a/dsn.go b/dsn.go new file mode 100644 index 00000000..19bd8d15 --- /dev/null +++ b/dsn.go @@ -0,0 +1,31 @@ +package gorm + +import ( + "net/url" + "strconv" +) + +type DSN struct { + Host string + Port int + User string + Pass string + Db string + Options map[string]string +} + +func (d DSN) String() string { + dsn := d.User + ":" + d.Pass + "@tcp(" + d.Host + ":" + strconv.Itoa(d.Port) + ")/" + d.Db + + if d.Options != nil { + value := url.Values{} + + for k, v := range d.Options { + value.Add(k, v) + } + + dsn += "?" + value.Encode() + } + + return dsn +} diff --git a/dsn_test.go b/dsn_test.go new file mode 100644 index 00000000..77f2c845 --- /dev/null +++ b/dsn_test.go @@ -0,0 +1,30 @@ +package gorm + +import "testing" + +func TestDsn(t *testing.T) { + dsn := DSN{ + Host: "127.0.0.1", + Port: 3306, + User: "root", + Pass: "password", + Db: "gorm", + } + + t.Run("dsn string", func(t *testing.T) { + if dsn.String() != "root:password@tcp(127.0.0.1:3306)/gorm" { + t.Error("dsn string error") + } + }) + + t.Run("dsn string with options", func(t *testing.T) { + dsn.Options = map[string]string{ + "charset": "utf8mb4", + "parseTime": "True", + } + + if dsn.String() != "root:password@tcp(127.0.0.1:3306)/gorm?charset=utf8mb4&parseTime=True" { + t.Error("dsn string with options error") + } + }) +}