I host my dart server in heroku. I provisioned heroku postgres for this app. I referenced the library postgres to access the data.
In this library the constructor for object PostgreSQLConnection requires three parameters: url, port and db name.
Heroku gives me just one connection string. I tried to pass different parts of this string to the constructor, but it failed:
SocketException: Failed host lookup: 'postgres://isbmdx...
This is my code:
import 'package:postgres/postgres.dart';
class DataAccess {
static Future<Object> ProcessRequest() async {
var valueFromHeroku =
Platform.environment["DATABASE_URL"];
var dbPort = 5432;
var dbName = "d8hqb682glgsf0";
var connection = PostgreSQLConnection(valueFromHeroku, dbPort, dbName);
await connection.open();
...
}
}
Any ideas?
您尝试使用外部道具并在云Web控制台中进行配置,例如DATABASE_URL = $(heroku config:get DATABASE_URL -your-app)your_process
The format of the connection string provided via DATABASE_URL in heroku is the following:
postgres://<USER>:<PASSWORD>@<DATABASE_HOST>:<PORT>/<DATABASE_NAME>
This is how the string can be parsed in dart:
class PostgresInstance {
final String host;
final int port;
final String database;
final String user;
final String password;
PostgresInstance(
this.host, this.port, this.database, this.user, this.password);
factory PostgresInstance.fromString(String connectionString) {
RegExp pattern = RegExp(
"^postgres:\\\/\\\/(?<user>[^:]*):(?<pass>[^@]*)@(?<host>[^:]*):(?<port>[^\\\/]*)\\\/(?<db>[^\/]*)\$");
RegExpMatch match = pattern.firstMatch(connectionString);
if (match == null)
throw Exception("Could not parse Postgres connection string.");
int port = int.parse(match.namedGroup('port'));
return PostgresInstance(
match.namedGroup('host'),
port,
match.namedGroup('db'),
match.namedGroup('user'),
match.namedGroup('pass'),
);
}
}
Here is the test to validate correctness:
test('Parse connection string', () async {
String conn = "postgres://user:password@a.bc.d:5555/db";
PostgresInstance i = PostgresInstance.fromString(conn);
expect(i.host, "a.bc.d");
expect(i.port, 5555);
expect(i.database, "db");
expect(i.password, "password");
expect(i.user, "user");
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.