如何在Golang的lib/pq PostgreSQL驱动中设置应用程序名称?

huangapple go评论73阅读模式
英文:

How to set application name in golang lib/pq postgresql driver?

问题

我正在编写一个使用golang postgres驱动程序的应用程序 - https://github.com/lib/pq/

我使用的连接字符串如下:

'name:pass@host:port/dbname'

我尝试在连接字符串中添加application_name参数,但这并不起作用

'name:pass@host:port/dbname?application_name=myapp'

是否可能从golang中设置应用程序名称?(标准方式)

英文:

I'm writing a golang application and using the golang postgres driver - https://github.com/lib/pq/

I use a connection string like this

'name:pass@host:port/dbname'

I try to add aplication_name param in conn string, but this doesn't work

'name:pass@host:port/dbname?application_name=myapp'

Is it possible to set the application name from golang? (standard way)

答案1

得分: 9

尽管文档中没有提到,但如果你查看lib/pq源代码,你会发现它支持application_name

以下是使用这种连接方式的示例代码:

connstring := fmt.Sprintf("user='%s' password='%s' dbname='%s' host='%s' application_name='%s'", user, password, dbname, host, application_name)
db, err := sql.Open("postgres", connstring)

请注意,这是一个示例代码,你需要根据实际情况进行适当的修改。

英文:

Even though it's not mentioned in the documentation, if you look at the lib/pq source code you will find that application_name is supported.

This style connection works as desired:

connstring := fmt.Sprintf("user='%s' password='%s' dbname='%s' host='%s' application_name='%s'", user, password, dbname, host, application_name)
db, err := sql.Open("postgres", connstring)

答案2

得分: 6

如果你查看文档,会发现不支持application_name选项。也许你可以使用:

fallback_application_name - 如果没有提供应用程序名称,则回退到的应用程序名称。

name:pass@host:port/dbname?fallback_application_name=myapp
英文:

If you look to the documentation a application_name option is not suuported. Maybe you could use:

> fallback_application_name - An application_name to fall back to if
> one isn't provided.

name:pass@host:port/dbname?fallback_application_name=myapp

答案3

得分: 1

你可以通过两种方式设置应用程序名称。

// 将应用程序名称作为以空格分隔的选项列表。
sql.Open("postgres", "user=myuser password=mypass host=localhost port=5432 dbname=mydb sslmode=disable application_name=myapp")

或者

// 将应用程序名称作为查询参数。
sql.Open("postgres", "postgres://myuser:mypass@localhost:5432/mydb?sslmode=disable&application_name=myapp")
英文:

You can set the application name one of two ways.

// Application name as space-separated list of options.
sql.Open("postgres", "user=myuser password=mypass host=localhost port=5432 dbname=mydb sslmode=disable application_name=myapp")

or

// Application name as query param.
sql.Open("postgres", "postgres://myuser:mypass@localhost:5432/mydb?sslmode=disable&application_name=myapp")

huangapple
  • 本文由 发表于 2017年3月15日 00:09:11
  • 转载请务必保留本文链接:https://go.coder-hub.com/42791005.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定