Home > Blockchain >  Go string format fill only part of the arguments
Go string format fill only part of the arguments

Time:10-09

I have a standard string format for calling an external api. e.g. https://%s?client=%s&password=%s.

Here is the first %s endpoint of the request which depends on the business logic. While I can always determine the client and password in advance.

func getApiUrl(clientId int) string {
    urlFormat := "https://%s?client=%s&password=%s"
    clientname, clientpass := getByClientId(clientId)
    return fmt.Sprintf(urlFormat, _, clientname, clientpass) // https://%s?client=clientname&password=clientpass
}

I would like to write something like a function that will fill in some of the parameters. In this form, it does not work, of course.

CodePudding user response:

You can use "%s" in the placeholder.

package main

import "fmt"

func getByClientId(clientId int) (string, string) {
    return "user", "password"
}

func getApiUrl(clientId int) string {
    urlFormat := "https://%s?client=%s&password=%s"
    clientname, clientpass := getByClientId(clientId)
    return fmt.Sprintf(urlFormat, "%s", clientname, clientpass) // https://%s?client=clientname&password=clientpass
}

func main() {
    userPasswordFilled := getApiUrl(3)
    fmt.Println(fmt.Sprintf(userPasswordFilled, "example.com"))
}

Go Playground

CodePudding user response:

For another approach, you could return a URL instead:

package hello
import "net/url"

func get_by_client_ID(int) (string, string) {
   return "client_name", "client_pass"
}

func get_API_URL(client_ID int) url.URL {
   client_name, client_pass := get_by_client_ID(client_ID)
   var ref url.URL
   ref.Scheme = "https"
   ref.RawQuery = url.Values{
      "client": {client_name},
      "password": {client_pass},
   }.Encode()
   return ref
}

https://stackoverflow.com/users/1002260

  •  Tags:  
  • go
  • Related