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
+28.1k Golang : Change a file last modified date and time
+12k Golang : 2 dimensional array example
+5.5k Javascript : How to replace HTML inside <div>?
+5.9k Golang : How to write backslash in string?
+6.7k Golang : Fibonacci number generator examples
+5.2k How to check with curl if my website or the asset is gzipped ?
+10.8k Golang : Create S3 bucket with official aws-sdk-go package
+10k Golang : cannot assign type int to value (type uint8) in range error
+8.8k Golang : Intercept and compare HTTP response code example
+4.3k Java : Generate multiplication table example
+5.7k Fontello : How to load and use fonts?