Skip to content

Instantly share code, notes, and snippets.

@wubin1989
Forked from brandonrachal/html_entities.go
Created May 5, 2023 11:42
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 wubin1989/0d983acd006fdfe201cb4ecc700bb76c to your computer and use it in GitHub Desktop.
Save wubin1989/0d983acd006fdfe201cb4ecc700bb76c to your computer and use it in GitHub Desktop.
A Go Lang Program to Convert Special Symbols to HTML Entities
package main
import (
"fmt"
"bufio"
"os"
"strconv"
)
func ReadLinesFromFile(file_path string) ([]string, error) {
var lines []string
src_file, err := os.Open(file_path)
if err != nil { panic(err) }
defer func() {
src_file.Close()
}()
reader := bufio.NewScanner(src_file)
for reader.Scan() {
lines = append(lines, LineToHTMLEntities(reader.Text()))
}
return lines, reader.Err()
}
func WriteLinesToFile(file_path string, lines []string) error {
dst_file, err := os.Create(file_path)
if err != nil { panic(err) }
defer func() {
dst_file.Close()
}()
writer := bufio.NewWriter(dst_file)
for i := 0; i < len(lines); i++ {
fmt.Fprintln(writer, lines[i])
}
return writer.Flush()
}
func LineToHTMLEntities(line string) string {
var converted string = ""
for _, rune_value := range line {
converted += RuneToHTMLEntity(rune_value)
}
return converted
}
func RuneToHTMLEntity(entity rune) string {
if (entity < 128) {
return string(entity)
} else {
return "&#" + strconv.FormatInt(int64(entity), 10) + ";"
}
}
func main() {
var srcFile string = "input.txt"
var dstFile string = "output.txt"
convertedLines, err := ReadLinesFromFile(srcFile)
if (err != nil) { fmt.Println(err) }
if err := WriteLinesToFile(dstFile, convertedLines); err != nil {
fmt.Println(err)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment