0

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

0x01
  • 885
  • 7
  • 17
  • 1
    Possible duplicate: the answer is in this question: [Golang: format a string without printing?](http://stackoverflow.com/questions/11123865/golang-format-a-string-without-printing/31742265#31742265) – icza Nov 26 '16 at 16:55
  • Well not really, I might not be detailed enough, but my goal here would be to build a function that would allow me to build custom URLs easily and in a sane/readable way – 0x01 Nov 26 '16 at 17:14

2 Answers2

1

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) }
dm03514
  • 54,664
  • 18
  • 108
  • 145
0

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.

I159
  • 29,741
  • 31
  • 97
  • 132