How to create multiline strings in Golang

in #programming7 years ago (edited)

I had the next problem:

How to create a multiline string in go to print a line like this:

curl -u elastic:changeme -XPUT http://localhost:9200/my_index/users/1?pretty -d '{
    "firstname" : "Rodolfo",
    "lastname" : "Guzmán Huerta",
    "alias" : "El Santo"
}'

The first solution was use fmt.Println function like this:

fmt.Println("curl -u elastic:changeme -XPUT http://localhost:9200/my_index/users/1?pretty -d '{")
fmt.Println("   \"firstname\" : \"Rodolfo\",")
fmt.Println("   \"lastname\" : \"Guzmán Huerta\",")
fmt.Println("   \"alias\" : \"El Santo\"")
fmt.Println("}'")

and it works, but i don’t like it :(

The second solution was use `` to create a raw string and only one fmt.Println function like this:

curl1 :=
    `
curl -u elastic:changeme -XPUT http://localhost:9200/my_index/users/1?pretty -d '{
    "firstname" : "Rodolfo",
    "lastname" : "Guzmán Huerta",
    "alias" : "El Santo"
}'
`
fmt.Println(curl1)

It looks much better!

But now, i need to insert variables inside the multiline string, one possible solution is to use fmt.Printf function like this:

fmt.Println("The second solution:\n")
fmt.Printf("curl -u elastic:changeme -XPUT http://localhost:9200/my_index/users/%v?pretty -d '{", id)
fmt.Printf("    \"firstname\" : \"%v\",", firstname)
fmt.Printf("    \"lastname\" : \"%v\",", lastname)
fmt.Printf("    \"alias\" : \"%v\"", alias)
fmt.Printf("}'")

And also works!

But finally i found the best solution like this:

id := 2
firstname := "Daniel"
lastname := "García Arteaga"
alias := "Huracán Ramírez"

curl2 :=
    `
curl -u elastic:changeme -XPUT http://localhost:9200/my_index/users/` + strconv.Itoa(id) + `?pretty -d '{
    "firstname" : "` + firstname + `",
    "lastname" : "` + lastname + `",
    "alias" : "` + alias + `"
}'
`
fmt.Println(curl2)

Here i only use the Itoa function of the package strconv to convert an int value to string

Works and looks much better
I think it's the best solution, what do you think?

Here leave the code

The Go Playground

Sort:  

yep, last one the cleanest :)

And easier to understand :)

Coin Marketplace

STEEM 0.19
TRX 0.12
JST 0.027
BTC 64928.52
ETH 3525.30
USDT 1.00
SBD 2.36