17
17
package postgres
18
18
19
19
import (
20
- "fmt "
20
+ "net "
21
21
"net/url"
22
+ "strconv"
22
23
23
24
"github.com/clidey/whodb/core/src/engine"
24
25
"gorm.io/driver/postgres"
@@ -31,24 +32,27 @@ func (p *PostgresPlugin) DB(config *engine.PluginConfig) (*gorm.DB, error) {
31
32
return nil , err
32
33
}
33
34
34
- // Use URL format for PostgreSQL connection
35
- dsn := fmt . Sprintf ( "postgresql://%s:%s@%s:%v/%s?sslmode=prefer" ,
36
- url . QueryEscape ( connectionInput . Username ) ,
37
- url .QueryEscape ( connectionInput .Password ),
38
- url . QueryEscape (connectionInput .Hostname ),
39
- connectionInput .Port ,
40
- url . QueryEscape ( connectionInput . Database ))
35
+ // Construct PostgreSQL URL securely using url.URL struct
36
+ u := & url. URL {
37
+ Scheme : "postgresql" ,
38
+ User : url .UserPassword ( connectionInput . Username , connectionInput .Password ),
39
+ Host : net . JoinHostPort (connectionInput .Hostname , strconv . Itoa ( connectionInput . Port ) ),
40
+ Path : "/" + connectionInput .Database ,
41
+ }
41
42
42
- // Add extra options as URL parameters
43
+ // Add query parameters securely
44
+ q := u .Query ()
45
+ q .Set ("sslmode" , "prefer" )
46
+
47
+ // Add extra options as query parameters
43
48
if connectionInput .ExtraOptions != nil {
44
- params := url.Values {}
45
49
for key , value := range connectionInput .ExtraOptions {
46
- params .Add (key , value )
47
- }
48
- if len (params ) > 0 {
49
- dsn += "&" + params .Encode ()
50
+ q .Set (key , value )
50
51
}
51
52
}
53
+
54
+ u .RawQuery = q .Encode ()
55
+ dsn := u .String ()
52
56
53
57
db , err := gorm .Open (postgres .Open (dsn ), & gorm.Config {})
54
58
if err != nil {
0 commit comments