本文整理汇总了Golang中github.com/lib/pq.ParseURL函数的典型用法代码示例。如果您正苦于以下问题:Golang ParseURL函数的具体用法?Golang ParseURL怎么用?Golang ParseURL使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了ParseURL函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的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
示例16: SetupPostgres
func SetupPostgres() error {
dbUrl := env.StringDefault("DATABASE_URL", "postgres://")
dsn, err := pq.ParseURL(dbUrl)
if err != nil {
return err
}
db, err := sql.Open("postgres", dsn)
if err != nil {
return err
}
dbmap.Db = db
dbmap.Dialect = gorp.PostgresDialect{}
return nil
}
开发者ID:jmcvetta,项目名称:lgtts,代码行数:14,代码来源:service.go
示例17: NewPostgres
func NewPostgres() gorm.DB {
var err error
databaseUrl, _ := pq.ParseURL(os.Getenv("DATABASE_URL"))
Postgres, err = gorm.Open("postgres", databaseUrl)
if err != nil {
log.Fatalln(err.Error())
}
Postgres.LogMode(true)
Postgres.AutoMigrate(models.App{})
Postgres.AutoMigrate(models.User{})
return Postgres
}
开发者ID:zannet,项目名称:api,代码行数:15,代码来源:postgres.go
示例18: initDb
func initDb() error {
parsed_url, err := pq.ParseURL(*db_url)
if err != nil {
return err
}
db, err = sql.Open("postgres", parsed_url)
if err != nil {
return err
}
dbmap = &gorp.DbMap{Db: db, Dialect: gorp.PostgresDialect{}}
err = logs.InitTables(dbmap)
if err != nil {
return err
}
return nil
}
开发者ID:rf-,项目名称:gologs,代码行数:16,代码来源:gologs.go
示例19: ParseURL
func ParseURL(mod mb.Module, rawURL string) (mb.HostData, error) {
c := struct {
Username string `config:"username"`
Password string `config:"password"`
}{}
if err := mod.UnpackConfig(&c); err != nil {
return mb.HostData{}, err
}
if parts := strings.SplitN(rawURL, "://", 2); len(parts) != 2 {
// Add scheme.
rawURL = fmt.Sprintf("postgres://%s", rawURL)
}
u, err := url.Parse(rawURL)
if err != nil {
return mb.HostData{}, fmt.Errorf("error parsing URL: %v", err)
}
parse.SetURLUser(u, c.Username, c.Password)
if timeout := mod.Config().Timeout; timeout > 0 {
q := u.Query()
q.Set("connect_timeout", strconv.Itoa(int(timeout.Seconds())))
u.RawQuery = q.Encode()
}
// https://www.postgresql.org/docs/current/static/libpq-connect.html#LIBPQ-CONNSTRING
connString, err := pq.ParseURL(u.String())
if err != nil {
return mb.HostData{}, err
}
h := parse.NewHostDataFromURL(u)
// Store the connection string instead of URL to avoid the cost of sql.Open
// parsing the URL on each call.
h.URI = connString
// Postgres URLs can use a host query param to specify the host. This is
// used for unix domain sockets (postgres:///dbname?host=/var/lib/postgres).
if host := u.Query().Get("host"); u.Host == "" && host != "" {
h.Host = host
}
return h, nil
}
开发者ID:ruflin,项目名称:beats,代码行数:47,代码来源:postgresql.go
示例20: DbConnect
func DbConnect() {
var err error
DATABASE_URL := os.Getenv("DATABASE_URL")
if DATABASE_URL == "" {
DATABASE_URL = "postgres://totoro:[email protected]:5432/quiet?sslmode=disable"
}
connStr, err := pq.ParseURL(DATABASE_URL)
if err != nil {
log.Fatal(err)
}
Db, err = sql.Open("postgres", connStr)
if err != nil {
log.Fatal(err)
}
}
开发者ID:postfix,项目名称:quiet-1,代码行数:18,代码来源:db.go
注:本文中的github.com/lib/pq.ParseURL函数示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论