How to encode and decode MIME headers with non-ASCII characters (e.g., UTF-8) in Go?

To encode and decode MIME headers with non-ASCII characters (such as UTF-8) in Go, you can use the "mime" package in the standard library. The package provides functions for encoding and decoding MIME headers using the specified character encoding.

Here's an example that demonstrates encoding and decoding a MIME header using UTF-8 encoding:

  1. Import the "mime" package:
import ( "fmt" "mime" )
  1. Encode a non-ASCII string into a MIME-Header encoded string:
name := "日本語" encoded := mime.QEncoding.Encode("UTF-8", name) fmt.Println(encoded) // =?UTF-8?Q?=E6=97=A5=E6=9C=AC=E8=AA=9E?=

In the above example, the mime.QEncoding.Encode function is used to encode the non-ASCII string name using the UTF-8 encoding. The result is a string in the format =?charset?encoding?encodedtext?=, where charset is the character set, encoding is the encoding method, and encodedtext is the encoded string.

  1. Decode a MIME-Header encoded string back to the original value:
decoded, err := mime.QEncoding.Decode(encoded) if err != nil { fmt.Println("Decoding error:", err) } else { fmt.Println(decoded) // 日本語 }

The mime.QEncoding.Decode function is used to decode the previously encoded string encoded. If decoding is successful, the original non-ASCII value can be obtained.

Note: The example above demonstrates using the "Q-encoding" method, as indicated by mime.QEncoding. There are other encoding methods available in the package, such as "B-encoding". Depending on your use case, you may need to use a different encoding method.

Remember to handle any potential errors that may occur during encoding or decoding to ensure the proper execution of your code.