Skip to content

Instantly share code, notes, and snippets.

@potix2
Created November 21, 2017 05:56
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 potix2/433fb945b34c8466e1905b7815b264aa to your computer and use it in GitHub Desktop.
Save potix2/433fb945b34c8466e1905b7815b264aa to your computer and use it in GitHub Desktop.
escape invalid utf8 bytes
package main
import (
"fmt"
"strings"
"unicode/utf8"
)
func escape(s string) string {
return strings.Trim(fmt.Sprintf("%q", s), "\"")
}
func check(s string) {
fmt.Printf("%s is ", s)
if utf8.ValidString(s) {
fmt.Println("valid utf8")
} else {
fmt.Println("invalid utf8")
}
}
func main() {
x := "a\xc5z"
check(x)
check(escape(x))
}
%go run main.go
a is invalid utf8
a\xc5z is valid utf8
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment