當前位置: 首頁>>代碼示例>>Golang>>正文


Golang pq.ParseURL函數代碼示例

本文整理匯總了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
}
開發者ID:joshk,項目名稱:travis-logs-in-go,代碼行數:27,代碼來源:database.go

示例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
}
開發者ID:mikoim,項目名稱:codecheck-1015,代碼行數:31,代碼來源:main.go

示例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}
}
開發者ID:barkinet,項目名稱:botbot-bot,代碼行數:26,代碼來源:storage.go

示例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
}
開發者ID:jerryclinesmith,項目名稱:notabbble,代碼行數:25,代碼來源:db.go

示例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
}
開發者ID:hamfist,項目名稱:artifacts-service,代碼行數:27,代碼來源:database.go

示例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
}
開發者ID:zqzca,項目名稱:back,代碼行數:25,代碼來源:db.go

示例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
}
開發者ID:kisielk,項目名稱:gorge,代碼行數:11,代碼來源:arco.go

示例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
}
開發者ID:rf-,項目名稱:gologs,代碼行數:9,代碼來源:tests.go

示例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
}
開發者ID:simonz05,項目名稱:goose,代碼行數:56,代碼來源:dbconf.go

示例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
		},
	}
}
開發者ID:mhurne,項目名稱:vault,代碼行數:54,代碼來源:backend_test.go

示例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)
}
開發者ID:dustinsmith1024,項目名稱:goqu,代碼行數:11,代碼來源:postgres_test.go

示例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
}
開發者ID:abourget,項目名稱:goose,代碼行數:54,代碼來源:dbconf.go

示例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
}
開發者ID:newellworldorder,項目名稱:GoFundYourself,代碼行數:12,代碼來源:main.go

示例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
}
開發者ID:thomaso-mirodin,項目名稱:vault,代碼行數:52,代碼來源:backend.go

示例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
}
開發者ID:jeichorn,項目名稱:telegraf,代碼行數:14,代碼來源:postgresql.go


注:本文中的github.com/lib/pq.ParseURL函數示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。