Reading/writing a different charset
It is not an exception that the input from various sources could come in various charsets. Note that a lot of systems use the Windows operating system but there are others. Go, by default, expects that the strings used in the program are UTF-8 based. If they are not, then decoding from the given charset must be done to be able to work with the string. This recipe will show the reading and writing of the file in a charset other than UTF-8.
How to do it...
- Open the console and create the folder
chapter05/recipe05
. - Navigate to the directory.
- Create the
charset.go
file with the following content:
package main import ( "fmt" "io/ioutil" "os" "golang.org/x/text/encoding/charmap" ) func main() { // Write the string // encoded to Windows-1252 encoder := charmap.Windows1252.NewEncoder() s, e := encoder.String("This is sample text with runes Š") ...