3

w is of type http.ResponseWriter

This is fine:

fmt.Fprintf(w, statusPercentage + " " + mostUpToDateStatusDownloaded + "/"+ mostUpToDateStatusOverallData)

output: 100 488 MB/488 MB

This causes a problem:

fmt.Fprintf(w, statusPercentage + "% " + mostUpToDateStatusDownloaded + "/"+ mostUpToDateStatusOverallData)

output: 100%! (MISSING)MB/488 MB

Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
Bruce
  • 181
  • 4
  • 11
  • Problem solved! It turned out that I have to escape the percentage sign by using double %. Please refer to https://stackoverflow.com/questions/1860159/how-to-escape-the-percent-sign-in-cs-printf for further information. – Bruce Oct 20 '17 at 03:24
  • 1
    You might have heard of Println. – Volker Oct 20 '17 at 08:29

3 Answers3

10

% is a special placeholder symbol. If you want to put it into a string as a symbol itself - duplicate it. Like:

fmt.Fprintf(w, "Growth %v %%", "50")

Output:

Growth 50%
kostix
  • 51,517
  • 14
  • 93
  • 176
Eugene Lisitsky
  • 12,113
  • 5
  • 38
  • 59
  • Your code makes use of wrong quotation marks. More specifically: `invalid identifier character U+201C '“'` and `invalid identifier character U+201D '”'` – tgogos Oct 20 '17 at 08:18
  • Sorry, I sent from mobile phone - and looks like autocorrection decided to change symbols. – Eugene Lisitsky Oct 20 '17 at 12:12
4

It is usually not a good practice to use arbitrary application strings as the format specifier to fmt.Fprintf and friends. The application should either using a fixed format string or convert the string to bytes and write the bytes directly to the response.

Here's how to do it with a format string:

// note that '%' is quoted as %%
fmt.Fprintf(w, "%s%% %s/%s", statusPercentage, mostUpToDateStatusDownloaded, mostUpToDateStatusOverallData)

Here's how to skip the formatting and write directly to the response:

io.WriteString(w, statusPercentage + "% " + mostUpToDateStatusDownloaded + "/"+ mostUpToDateStatusOverallData)
Charlie Tumahai
  • 113,709
  • 12
  • 249
  • 242
0

Why are you using fmt.Fprintf if you're not doing any string formatting? Just use fmt.Fprint instead.

John Gibb
  • 10,603
  • 2
  • 37
  • 48