fmt.Fprintln
- Go course
- Intermediate
- Lesson 57/80
- 4 min
Learn to write to a Writer with Fprintln.
fmt.Fprintln
The Fprint family writes output to any io.Writer: a file, an HTTP response, a buffer or os.Stderr.
fmt.Fprintln(os.Stderr, "uyarı:", err)
fmt.Fprintf(w, "<h1>%s</h1>", baslik) // http.ResponseWriterEach returns the number of bytes written and an error. When writing to a file or the network this error matters; the disk may fill up or the connection may drop.
Aligned output with tabwriter
text/tabwriter is a Writer that aligns tab-separated text into columns; ideal for command-line tables:
tw := tabwriter.NewWriter(os.Stdout, 0, 0, 2, ' ', 0)
fmt.Fprintln(tw, "AD\tFİYAT")
fmt.Fprintln(tw, "Kalem\t12.50")
fmt.Fprintln(tw, "Defter\t7.00")
tw.Flush()Nothing is written unless Flush is called at the end.
Practice Table output
Write an aligned table to os.Stdout with text/tabwriter: header AD\tADET, rows Kalem\t3 and Defter\t12. Use NewWriter(os.Stdout, 0, 0, 2, ' ', 0) and call Flush.
Starter code
package main
import (
"fmt"
"os"
"text/tabwriter"
)
func main() {
// buraya yaz
}Sample solution
package main
import (
"fmt"
"os"
"text/tabwriter"
)
func main() {
tw := tabwriter.NewWriter(os.Stdout, 0, 0, 2, ' ', 0)
fmt.Fprintln(tw, "AD\tADET")
fmt.Fprintln(tw, "Kalem\t3")
fmt.Fprintln(tw, "Defter\t12")
tw.Flush()
}Expected output
AD ADET Kalem 3 Defter 12
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What is the risk of writing user data directly with <code>Fprintf</code> when generating HTML?
- It's slower
- It doesn't compile
- There is no risk
- XSS: data isn't escaped, scripts can run Correct answer
Explanation: fmt knows nothing about HTML; html/template or html.EscapeString must be used for user data.
2 Write to the error stream
fmt.____(os.Stderr, "hata:", err)
fmt.Fprintln(os.Stderr, "hata:", err)
Explanation: Fprintln writes to the Writer in its first argument; stderr here.
3 Writer target
| Term | Meaning |
|---|---|
os.Stderr |
Error messages |
http.ResponseWriter |
Web response |
tabwriter |
Aligned table |
bytes.Buffer |
Collecting in memory |