Skip to content

Instantly share code, notes, and snippets.

@lithdew
Created May 27, 2020 11:19
Show Gist options
  • Save lithdew/662510e83c416f731828988716189211 to your computer and use it in GitHub Desktop.
Save lithdew/662510e83c416f731828988716189211 to your computer and use it in GitHub Desktop.
Unescape strings in Go.
func unescape(s string) (string, error) {
if !strings.ContainsRune(s, '\\') && utf8.ValidString(s) {
return s, nil
}
tmp := make([]byte, utf8.UTFMax)
buf := make([]byte, 0, 3*len(s)/2)
for len(s) > 0 {
c, mb, t, err := strconv.UnquoteChar(s, '"')
if err != nil {
return "", err
}
s = t
if c < utf8.RuneSelf || !mb {
buf = append(buf, byte(c))
} else {
n := utf8.EncodeRune(tmp[:], c)
buf = append(buf, tmp[:n]...)
}
}
return string(buf), nil
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment