pgweb/pkg/connection/connection_string.go

101 lines
2.1 KiB
Go
Raw Normal View History

2015-04-30 19:47:07 +03:00
package connection
2014-12-18 06:32:50 +03:00
import (
"errors"
"fmt"
"os"
2014-12-18 06:32:50 +03:00
"os/user"
"strings"
2015-04-30 19:47:07 +03:00
"github.com/sosedoff/pgweb/pkg/command"
2014-12-18 06:32:50 +03:00
)
func currentUser() (string, error) {
u, err := user.Current()
if err == nil {
return u.Username, nil
}
name := os.Getenv("USER")
if name != "" {
return name, nil
}
return "", errors.New("Unable to detect OS user")
}
2015-04-30 19:47:07 +03:00
func FormatUrl(opts command.Options) (string, error) {
2014-12-18 06:32:50 +03:00
url := opts.Url
// Make sure to only accept urls in a standard format
if !strings.HasPrefix(url, "postgres://") && !strings.HasPrefix(url, "postgresql://") {
2014-12-18 06:32:50 +03:00
return "", errors.New("Invalid URL. Valid format: postgres://user:password@host:port/db?sslmode=mode")
}
// Special handling for local connections
if strings.Contains(url, "localhost") || strings.Contains(url, "127.0.0.1") {
if !strings.Contains(url, "?sslmode") {
if opts.Ssl == "" {
url += fmt.Sprintf("?sslmode=%s", "disable")
} else {
url += fmt.Sprintf("?sslmode=%s", opts.Ssl)
}
}
}
// Append sslmode parameter only if its defined as a flag and not present
// in the connection string.
if !strings.Contains(url, "?sslmode") && opts.Ssl != "" {
url += fmt.Sprintf("?sslmode=%s", opts.Ssl)
}
return url, nil
}
2015-04-30 19:47:07 +03:00
func IsBlank(opts command.Options) bool {
2014-12-18 06:56:15 +03:00
return opts.Host == "" && opts.User == "" && opts.DbName == "" && opts.Url == ""
}
2015-04-30 19:47:07 +03:00
func BuildString(opts command.Options) (string, error) {
2014-12-18 06:32:50 +03:00
if opts.Url != "" {
2015-04-30 19:47:07 +03:00
return FormatUrl(opts)
2014-12-18 06:32:50 +03:00
}
// Try to detect user from current OS user
if opts.User == "" {
u, err := currentUser()
2014-12-18 06:32:50 +03:00
if err == nil {
opts.User = u
2014-12-18 06:32:50 +03:00
}
}
// Disable ssl for localhost connections, most users have it disabled
if opts.Host == "localhost" || opts.Host == "127.0.0.1" {
if opts.Ssl == "" {
opts.Ssl = "disable"
}
}
url := "postgres://"
if opts.User != "" {
url += opts.User
}
if opts.Pass != "" {
url += fmt.Sprintf(":%s", opts.Pass)
}
url += fmt.Sprintf("@%s:%d", opts.Host, opts.Port)
if opts.DbName != "" {
url += fmt.Sprintf("/%s", opts.DbName)
}
if opts.Ssl != "" {
url += fmt.Sprintf("?sslmode=%s", opts.Ssl)
}
return url, nil
}