Efficiently Converting io.Reader to String
Problem:
Consider an io.ReadCloser object obtained from an http.Response. How can one efficiently convert the entire stream into a string?
Solution:
Using Strings.Builder (For Go 1.10 and Later):
This is the preferred and most efficient method for Go 1.10 and above:
import "strings" func ioReaderToString(r io.ReadCloser) (string, error) { buf := new(strings.Builder) if _, err := io.Copy(buf, r); err != nil { return "", err } return buf.String(), nil }
Legacy Method (For Go <= 1.9):
[Note: This solution is outdated and not recommended in favor of Strings.Builder.]
import "bytes" buf := new(bytes.Buffer) if _, err := buf.ReadFrom(r); err != nil { return "", err }
s := buf.String()
Unsafe Method (Advanced and Risky):
[Use with extreme caution]
import "bytes" buf := new(bytes.Buffer) if _, err := buf.ReadFrom(r); err != nil { return "", err }
b := buf.Bytes()
import "unsafe" s := *(*string)(unsafe.Pointer(&b))
Caveats of Unsafe Method:
Recommendation:
Stick with the Strings.Builder method as it is efficient, safe, and avoids the pitfalls of the unsafe method.
The above is the detailed content of How Can I Efficiently Convert an io.Reader to a String in Go?. For more information, please follow other related articles on the PHP Chinese website!