包含可以动态更改的变量的字符串

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

String with variable inside that can dynamically change

问题

我正在尝试在golang中设置一个API,根据特定需求,我希望能够有一个环境变量,其中包含一个URL字符串(例如:"https://subdomain.api.com/version/query"),并且我希望能够在API调用中修改加粗的部分。

对于如何实现这一点,我一点头绪也没有。

谢谢你的时间,

Paul

英文:

I'm trying to setup an API in golang, for specific needs, I want to be able to have an environment variable that would contain an URL as string (i.e : "https://subdomain.api.com/version/query") and I want to be able to modify the bold parts within an API call.

I have no clue on how I could achieve this.

Thanks for your time,

Paul

答案1

得分: 1

有很多方法可以实现从环境中配置URL,并在运行时动态配置URL,其中一种方法是使用模板。

你可以从环境变量中获取一个模板:

apiUrlFromEnv := "https://{{.Subdomin}}.api.com/{{.Version}}/query" // 从环境变量获取

根据文档进行修改:

type API struct {
    Subdomain string
    Version   string
}
api := API{"testapi", "1.1"}
tmpl, err := template.New("api").Parse(apiUrlFromEnv)
if err != nil { panic(err) }
err = tmpl.Execute(os.Stdout, api) // 写入缓冲区,以便获取字符串?
if err != nil { panic(err) }
英文:

There are many ways, one which allows the URL to be configured from the environment, then to have the url configured dynamically at runtime, would be to use a template.

You could expect a template from the ENV:

apiUrlFromEnv := "https://{{.Subdomin}}.api.com/{{.Version}}/query" // get from env

Modified From the docs:

type API struct {
	Subdomain string
	Version   string
}
api := API{"testapi", "1.1"}
tmpl, err := template.New("api").Parse(apiUrlFromEnv)
if err != nil { panic(err) }
err = tmpl.Execute(os.Stdout, api) // write to buffer so you can get a string?
if err != nil { panic(err) }

答案2

得分: 0

最简单的方法是使用fmt.Sprintf

fmt.Sprintf(format string, a ...interface{}) string

如你所见,这个函数返回一个新的格式化字符串,这是内置库。此外,你可以使用索引将参数放置在模板中:

> 在Printf、Sprintf和Fprintf中,默认行为是对调用中传递的连续参数进行格式化。然而,[n]符号紧跟在动词之前表示应该格式化第n个从1开始的参数。

fmt.Sprintf("%[2]d %[1]d %d[2]\n", 11, 22)

但是,如果你想使用命名变量,你应该使用text/template包。

英文:

The simplest way is to use fmt.Sprintf.

fmt.Sprintf(format string, a ...interface{}) string

As you see this function returns a new formatted string and this is built-in library. Furthermore you can use indexing to place arguments in a template:

> In Printf, Sprintf, and Fprintf, the default behavior is for each formatting verb to format successive arguments passed in the call. However, the notation [n] immediately before the verb indicates that the nth one-indexed argument is to be formatted instead.

fmt.Sprintf("%[2]d %[1]d %d[2]\n", 11, 22)

But if you want to use named variables you should use text/template package.

huangapple
  • 本文由 发表于 2016年11月26日 23:40:14
  • 转载请务必保留本文链接:https://go.coder-hub.com/40820004.html
匿名

发表评论

匿名网友

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

确定