fmt.Fprint or io.WriteString for http.ResponseWriter write?

2,475 views
Skip to first unread message

José Colón

unread,
Apr 21, 2019, 9:59:23 AM4/21/19
to golang-nuts
Hi gophers! Is it better to (w is an http.ResponseWriter)

fmt.Fprint(w, "Hello world")


or to 

io.WriteString(w, "Hello world")


or doesfmt.Fprint use io.WriteString behind the scenes, and thus they are equivalent?

Christian Staffa

unread,
Apr 21, 2019, 11:44:54 AM4/21/19
to José Colón, golang-nuts
When you check out the source code both, fmt.Fprint and io.WriteString, need a writer as the first argument. Writer is an interface type which provides an Write method. And thats exactly what that functions are calling.. the Write method of your provided w (which is http.ResponseWriter in your case).

The difference is that fmt.Fprint is formatting the arguments provided first in a buffer before calling w.Write.
And io.WriteString is checking if w provides the StringWriter interface and calls that instead.


https://golang.org/src/io/io.go?s=10163:10218#L279

But to answer your question. In your simple case I would use io.WriteString. If you have more arguments than you could only use fmt.Fprint or you prepare your string by yourself before calling io.WriteString.

Hope that helps (;

Christian

Sent from my iPhone
--
You received this message because you are subscribed to the Google Groups "golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.
Reply all
Reply to author
Forward
0 new messages