[Golang] Convert File Encoding From Big5 to UTF-8


Convert file encoding from Big5 encoding to UTF-8 via Golang. Only for demonstration purpose. It will be much easier to use iconv command to convert encoding of one file.

Install Go iconv binding:

$ go get -u github.com/djimenez/iconv-go

Source code:

package main

import (
      "flag"
      "fmt"
      iconv "github.com/djimenez/iconv-go"
      "io"
      "os"
)

func big5ToUTF8(path, outpath string) {
      fmt.Println("Converting " + path + " from Big5 to UTF-8 ...")

      f, err := os.Open(path)
      if err != nil {
              panic(err)
      }
      defer f.Close()

      reader, err := iconv.NewReader(f, "big5", "utf-8")
      if err != nil {
              panic(err)
      }

      fo, err := os.Create(outpath)
      if err != nil {
              panic(err)
      }
      defer fo.Close()

      io.Copy(fo, reader)
}

func main() {
      pPath := flag.String("input", "", "Path of file to be processed")
      pOutpath := flag.String("output", "", "Output path of processed file")
      flag.Parse()
      path := *pPath
      outpath := *pOutpath
      if path == "" || outpath == "" {
              fmt.Fprintf(os.Stderr, "Error: empty path!\n")
              return
      }
      big5ToUTF8(path, outpath)
      fmt.Println(outpath + " saved")
}

Command line usage:

$ go run big5ToUTF8.go -input=big5.html -output=utf8.html

Tested on: Ubuntu Linux 15.10, Go 1.6.


References:

[1]big5 to utf-8 · twnanda/twnanda@5681c8b · GitHub
[2][Bash] Convert Files in Directory From Big5 to UTF-8