Convert Encodings to UTF-8 with Go's encoding Package
The encoding package in Go provides support for converting text from one encoding to another, including UTF-8. Here's how you can utilize this package for text conversion:
To convert from one encoding to UTF-8, you can use the following steps:
Import the encoding package:
import ( "encoding/json" "fmt" "io/ioutil" "strings" )
Here's an example that converts a UTF-8 string to ShiftJIS and back:
// Convert String from UTF-8 to another encoding func convertEncoding(s string, encoding string) string { encoder := json.NewEncoder(new(bytes.Buffer)) if err := encoder.Encode(s); err != nil { fmt.Println("Encoding failed:", err) return "" } encodedStr, err := ioutil.ReadAll(encoder.Buffered()) if err != nil { fmt.Println("Reading encoded string failed:", err) return "" } return strings.TrimSpace(string(encodedStr)) } func main() { original := "日本語" encoded := convertEncoding(original, "shift_jis") fmt.Println("Encoded:", encoded) decoded := convertEncoding(encoded, "utf-8") fmt.Println("Decoded:", decoded) }
The above is the detailed content of How Can I Convert Text Encodings to UTF-8 Using Go\'s `encoding` Package?. For more information, please follow other related articles on the PHP Chinese website!