Golang : Fix cannot convert buffer (type *bytes.Buffer) to type string error
Encountered these similar error messages while working on the previous tutorials on how to reset buffer and writing to http.ResponseWriter :
cannot convert buffer (type *bytes.Buffer) to type string
and
cannot use buffer (type *bytes.Buffer) as type []byte in argument to w.Write
1. Cannot convert buffer (type *bytes.Buffer) to type string solution
the error message is generated because of attempt to convert the bytes.Buffer directly to string type with string()
function.
fmt.Println(string(buffer))
to fix this error. Use buffer.String()
or string(buffer.Bytes())
package main
import (
"bytes"
"fmt"
)
func main() {
buffer := bytes.NewBuffer([]byte("Hello World!"))
fmt.Println(buffer.String())
// or
// fmt.Println(string(buffer.Bytes())
}
2. Cannot use buffer (type *bytes.Buffer) as type []byte in argument to w.Write solution
Writing buffer directly to http.ResponseWriter will cause error
func SayHelloWorld(w http.ResponseWriter, r *http.Request) {
buffer := bytes.NewBuffer([]byte("Hello World!"))
w.Write(buffer) // <--- wrong!
}
the solution is to use
w.Write(buffer.Bytes())
or use Buffer.WriteTo() function.
func SayHelloWorld(w http.ResponseWriter, r *http.Request) {
buffer := bytes.NewBuffer([]byte("Hello World!"))
buffer.WriteTo(w)
}
By Adam Ng
IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.
Advertisement
Tutorials
+7.5k Golang : Hue, Saturation and Value(HSV) with OpenCV example
+30.4k Golang : How to redirect to new page with net/http?
+14.5k Golang : How to pass map to html template and access the map's elements
+5k Golang : Constant and variable names in native language
+9.5k Facebook : Getting the friends list with PHP return JSON format
+14.5k Golang : Find network of an IP address
+18.9k Golang : How to make function callback or pass value from function as parameter?
+10.1k Golang : Channels and buffered channels examples
+12.4k Golang : 2 dimensional array example
+14.7k Golang : GUI with Qt and OpenCV to capture image from camera
+6.8k Golang : Experimental emojis or emoticons icons programming language
+23.8k Find and replace a character in a string in Go