本文整理匯總了Golang中github.com/lib/pq.ParseURL函數的典型用法代碼示例。如果您正苦於以下問題:Golang ParseURL函數的具體用法?Golang ParseURL怎麽用?Golang ParseURL使用的例子?那麽, 這裏精選的函數代碼示例或許可以為您提供幫助。
在下文中一共展示了ParseURL函數的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Golang代碼示例。
示例1: NewRealDB
func NewRealDB(url string) (DB, error) {
pgUrl, err := pq.ParseURL(url)
if err != nil {
return nil, err
}
db, err := sql.Open("postgres", pgUrl)
if err != nil {
return nil, err
}
if err = db.Ping(); err != nil {
return nil, err
}
jobIdFind, err := db.Prepare("SELECT id FROM logs WHERE job_id=$1")
if err != nil {
return nil, err
}
logPartsCreate, err := db.Prepare("INSERT INTO log_parts (log_id, number, content, final, created_at) VALUES ($1, $2, $3, $4, $5) RETURNING id")
if err != nil {
return nil, err
}
return &RealDB{db, jobIdFind, logPartsCreate}, nil
}
示例2: Run
func (s *Sprint) Run() error {
var err error
dsn, _ := pq.ParseURL(os.Getenv("DATABASE_URL"))
db, err := xorm.NewEngine("postgres", dsn)
if err != nil {
return err
}
err = db.Sync(Project{})
if err != nil {
return err
}
s.Db = db
s.Validator = validator.New(&validator.Config{TagName: "validate"})
port := os.Getenv("PORT")
r := gin.Default()
r.GET("/api/projects", s.GetProjects)
r.GET("/api/projects/:id", s.GetProjectsOne)
r.POST("/api/projects", s.CreateProjects)
r.DELETE("/api/projects/:id", s.DeleteProjects)
r.Run(":" + port)
return nil
}
示例3: NewPostgresStorage
// Connect to the database.
func NewPostgresStorage() *PostgresStorage {
postgresUrlString := os.Getenv("STORAGE_URL")
if glog.V(2) {
glog.Infoln("postgresUrlString: ", postgresUrlString)
}
if postgresUrlString == "" {
glog.Fatal("STORAGE_URL cannot be empty.\nexport STORAGE_URL=postgres://user:[email protected]:port/db_name")
}
dataSource, err := pq.ParseURL(postgresUrlString)
if err != nil {
glog.Fatal("Could not read database string", err)
}
db, err := sql.Open("postgres", dataSource+" sslmode=disable fallback_application_name=bot")
if err != nil {
glog.Fatal("Could not connect to database.", err)
}
// The following 2 lines mitigate the leak of postgresql connection leak
// explicitly setting a maximum number of postgresql connections
db.SetMaxOpenConns(10)
// explicitly setting a maximum number of Idle postgresql connections
db.SetMaxIdleConns(2)
return &PostgresStorage{db}
}
示例4: Connect
func Connect() gorm.DB {
url := os.Getenv("DATABASE_URL")
werckerDbUrl := os.Getenv("WERCKER_POSTGRESQL_URL")
if werckerDbUrl != "" {
url = werckerDbUrl
}
connection, err := pq.ParseURL(url)
if err != nil {
log.Fatalf("Failed to parse database URL: %s", err)
}
connection += " sslmode=disable" // TODO: Use require in production
db, err := gorm.Open("postgres", connection)
if err != nil {
log.Fatalf("Failed to connecto to database: %s", err)
}
db.AutoMigrate(models.Project{})
if martini.Env == martini.Dev {
db.LogMode(true)
}
return db
}
示例5: NewDatabase
// NewDatabase creates a (postgres) *Database from a database URL string
func NewDatabase(url string, log *logrus.Logger) (*Database, error) {
db := &Database{
url: url,
st: &dbStatements{},
log: log,
migrations: defaultMigrations,
unpreparedStatements: defaultStatements,
}
if db.log == nil {
db.log = logrus.New()
}
parsedURL, err := pq.ParseURL(url)
if err != nil {
return nil, err
}
conn, err := sql.Open("postgres", parsedURL)
if err != nil {
return nil, err
}
db.conn = conn
return db, nil
}
示例6: Connect
func Connect() (*sqlx.DB, error) {
open := os.Getenv("DATABASE_URL")
fmt.Println("connecting to", open)
if parsedURL, err := pq.ParseURL(open); err == nil && parsedURL != "" {
open = parsedURL
}
con, err := sqlx.Connect("postgres", open)
if err != nil {
fmt.Println(err)
return nil, err
}
err = con.Ping()
if err != nil {
fmt.Println(err)
return nil, err
}
return con, err
}
示例7: Open
// Open creates a new connection to the Arco database.
// URL is a Postgres connection string in the form:
// "postgres://bob:[email protected]:5432/mydb?option=value"
func Open(url string) (*DB, error) {
dsn, err := pq.ParseURL(url)
if err != nil {
return nil, err
}
db, err := sql.Open("postgres", dsn)
return &DB{db}, err
}
示例8: SetupDb
func SetupDb() (*sql.DB, *gorp.DbMap) {
parsedUrl, _ := pq.ParseURL(dbUrl)
db, err := sql.Open("postgres", parsedUrl)
if err != nil {
panic(err.Error())
}
dbmap := &gorp.DbMap{Db: db, Dialect: gorp.PostgresDialect{}}
return db, dbmap
}
示例9: NewDBConf
func NewDBConf(conf, p, env string) (*DBConf, error) {
if !filepath.IsAbs(conf) {
dir, file := filepath.Split(conf)
if dir == "" {
// Path is neither relative nor absolute (just filename)
conf = filepath.Join(p, file)
}
}
f, err := yaml.ReadFile(conf)
if err != nil {
return nil, err
}
drv, err := f.Get(fmt.Sprintf("%s.driver", env))
if err != nil {
return nil, err
}
open, err := f.Get(fmt.Sprintf("%s.open", env))
if err != nil {
return nil, err
}
open = os.ExpandEnv(open)
// Automatically parse postgres urls
if drv == "postgres" {
// Assumption: If we can parse the URL, we should
if parsedURL, err := pq.ParseURL(open); err == nil && parsedURL != "" {
open = parsedURL
}
}
d := newDBDriver(drv, open)
// allow the configuration to override the Import for this driver
if imprt, err := f.Get(fmt.Sprintf("%s.import", env)); err == nil {
d.Import = imprt
}
// allow the configuration to override the Dialect for this driver
if dialect, err := f.Get(fmt.Sprintf("%s.dialect", env)); err == nil {
d.Dialect = dialectByName(dialect)
}
if !d.IsValid() {
return nil, errors.New(fmt.Sprintf("Invalid DBConf: %v", d))
}
return &DBConf{
MigrationsDir: filepath.Join(p, "migrations"),
Env: env,
Driver: d,
}, nil
}
示例10: testAccStepDropTable
func testAccStepDropTable(t *testing.T, b logical.Backend, s logical.Storage, name string, connURL string) logicaltest.TestStep {
return logicaltest.TestStep{
Operation: logical.ReadOperation,
Path: path.Join("creds", name),
Check: func(resp *logical.Response) error {
var d struct {
Username string `mapstructure:"username"`
Password string `mapstructure:"password"`
}
if err := mapstructure.Decode(resp.Data, &d); err != nil {
return err
}
log.Printf("[TRACE] Generated credentials: %v", d)
conn, err := pq.ParseURL(connURL)
if err != nil {
t.Fatal(err)
}
conn += " timezone=utc"
db, err := sql.Open("postgres", conn)
if err != nil {
t.Fatal(err)
}
_, err = db.Exec("DROP TABLE test;")
if err != nil {
t.Fatal(err)
}
resp, err = b.HandleRequest(&logical.Request{
Operation: logical.RevokeOperation,
Storage: s,
Secret: &logical.Secret{
InternalData: map[string]interface{}{
"secret_type": "creds",
"username": d.Username,
},
},
})
if err != nil {
return err
}
if resp != nil {
if resp.IsError() {
return fmt.Errorf("Error on resp: %#v", *resp)
}
}
return nil
},
}
}
示例11: SetupSuite
func (me *postgresTest) SetupSuite() {
uri, err := pq.ParseURL(db_uri)
if err != nil {
panic(err)
}
db, err := sql.Open("postgres", uri)
if err != nil {
panic(err)
}
me.db = goqu.New("postgres", db)
}
示例12: NewDBConf
// extract configuration details from the given file
func NewDBConf(p, env string, pgschema string) (*DBConf, error) {
cfgFile := filepath.Join(p, "dbconf.yml")
f, err := yaml.ReadFile(cfgFile)
if err != nil {
return nil, err
}
drv, err := f.Get(fmt.Sprintf("%s.driver", env))
if err != nil {
return nil, err
}
drv = os.ExpandEnv(drv)
open, err := f.Get(fmt.Sprintf("%s.open", env))
if err != nil {
return nil, err
}
open = os.ExpandEnv(open)
// Automatically parse postgres urls
if drv == "postgres" {
// Assumption: If we can parse the URL, we should
if parsedURL, err := pq.ParseURL(open); err == nil && parsedURL != "" {
open = parsedURL
}
}
d := newDBDriver(drv, open)
// allow the configuration to override the Import for this driver
if imprt, err := f.Get(fmt.Sprintf("%s.import", env)); err == nil {
d.Import = imprt
}
// allow the configuration to override the Dialect for this driver
if dialect, err := f.Get(fmt.Sprintf("%s.dialect", env)); err == nil {
d.Dialect = dialectByName(dialect)
}
if !d.IsValid() {
return nil, errors.New(fmt.Sprintf("Invalid DBConf: %v", d))
}
return &DBConf{
MigrationsDir: filepath.Join(p, "migrations"),
Env: env,
Driver: d,
PgSchema: pgschema,
}, nil
}
示例13: SetupDB
func SetupDB() *sql.DB {
url := os.Getenv("DATABASE_URL")
connection, _ := pq.ParseURL(url)
connection += " sslmode=require"
db, err := sql.Open("postgres", connection)
if err != nil {
log.Println(err)
}
return db
}
示例14: DB
// DB returns the database connection.
func (b *backend) DB(s logical.Storage) (*sql.DB, error) {
b.lock.Lock()
defer b.lock.Unlock()
// If we already have a DB, we got it!
if b.db != nil {
return b.db, nil
}
// Otherwise, attempt to make connection
entry, err := s.Get("config/connection")
if err != nil {
return nil, err
}
if entry == nil {
return nil,
fmt.Errorf("configure the DB connection with config/connection first")
}
var connConfig connectionConfig
if err := entry.DecodeJSON(&connConfig); err != nil {
return nil, err
}
conn := connConfig.ConnectionString
if len(conn) == 0 {
conn = connConfig.ConnectionURL
}
// Ensure timezone is set to UTC for all the conenctions
if strings.HasPrefix(conn, "postgres://") || strings.HasPrefix(conn, "postgresql://") {
var err error
conn, err = pq.ParseURL(conn)
if err != nil {
return nil, err
}
}
conn += " timezone=utc"
b.db, err = sql.Open("postgres", conn)
if err != nil {
return nil, err
}
// Set some connection pool settings. We don't need much of this,
// since the request rate shouldn't be high.
b.db.SetMaxOpenConns(connConfig.MaxOpenConnections)
b.db.SetMaxIdleConns(connConfig.MaxIdleConnections)
return b.db, nil
}
示例15: SanitizedAddress
func (p *Postgresql) SanitizedAddress() (_ string, err error) {
var canonicalizedAddress string
if strings.HasPrefix(p.Address, "postgres://") || strings.HasPrefix(p.Address, "postgresql://") {
canonicalizedAddress, err = pq.ParseURL(p.Address)
if err != nil {
return p.sanitizedAddress, err
}
} else {
canonicalizedAddress = p.Address
}
p.sanitizedAddress = passwordKVMatcher.ReplaceAllString(canonicalizedAddress, "")
return p.sanitizedAddress, err
}