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
+13.1k CodeIgniter : "Fatal error: Cannot use object of type stdClass as array" message
+20.7k Golang : Underscore or snake_case to camel case example
+10k Golang : Compare files modify date example
+14k Javascript : Prompt confirmation before exit
+21.7k Golang : Upload big file (larger than 100MB) to AWS S3 with multipart upload
+12.5k Golang : Send data to /dev/null a.k.a blackhole with ioutil.Discard
+25.5k Golang : Daemonizing a simple web server process example
+10.4k RPM : error: db3 error(-30974) from dbenv->failchk: DB_RUNRECOVERY: Fatal error, run database recovery
+6.7k Default cipher that OpenSSL used to encrypt a PEM file
+15.7k Golang : Get current time from the Internet time server(ntp) example
+20.6k Golang : Convert date string to variants of time.Time type examples
+6.7k Golang : Muxing with Martini example