Skip to content

Instantly share code, notes, and snippets.

@ficapy
Created July 11, 2022 09:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ficapy/75f8e61534606fbb8ee943e1ffb79372 to your computer and use it in GitHub Desktop.
Save ficapy/75f8e61534606fbb8ee943e1ffb79372 to your computer and use it in GitHub Desktop.
chang the encoding of a file
package main
import (
"fmt"
"io/ioutil"
"os"
)
func checkBOM(filepath string) bool {
file, err := os.Open(filepath)
if err != nil {
fmt.Println("Error:", err)
os.Exit(1)
}
defer file.Close()
buffer := make([]byte, 3)
_, err = file.Read(buffer)
if err != nil {
fmt.Println("Error:", err)
os.Exit(1)
}
correct := []byte{0xEF, 0xBB, 0xBF}
for i := range buffer {
if buffer[i] != correct[i] {
return false
}
}
return true
}
func UTF8_TO_BOM(filepath string) {
// Add the BOM at the beginning of the file
b, err := ioutil.ReadFile(filepath)
if err != nil {
fmt.Println("Error:", err)
os.Exit(1)
}
b = append([]byte{0xEF, 0xBB, 0xBF}, b...)
err = ioutil.WriteFile(filepath, b, 0644)
if err != nil {
fmt.Println("Error:", err)
os.Exit(1)
}
}
func BOM_TO_UTF8(filepath string) {
// Remove the first three bytes
b, err := ioutil.ReadFile(filepath)
if err != nil {
fmt.Println("Error:", err)
os.Exit(1)
}
b = b[3:]
err = ioutil.WriteFile(filepath, b, 0644)
if err != nil {
fmt.Println("Error:", err)
os.Exit(1)
}
}
// 0xEF, 0xBB, 0xBF
func main() {
if len(os.Args) != 3 {
fmt.Println("command not enough arguments")
os.Exit(1)
}
cmd := os.Args[1]
filepath := os.Args[2]
if cmd == "check" {
fmt.Println(checkBOM(filepath))
return
} else if cmd == "transform" {
if checkBOM(filepath) {
fmt.Println("current is BOM")
BOM_TO_UTF8(filepath)
} else {
fmt.Println("current is UTF-8")
UTF8_TO_BOM(filepath)
}
} else {
fmt.Println("command not support")
os.Exit(1)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment