Skip to content

Instantly share code, notes, and snippets.

@mash
Created August 2, 2013 09:15
Show Gist options
  • Save mash/6138557 to your computer and use it in GitHub Desktop.
Save mash/6138557 to your computer and use it in GitHub Desktop.
package strings
import (
"fmt"
"unicode/utf8"
)
func MultibyteToEntityString(in string) string {
ret := ""
for _, c := range in {
if c < utf8.RuneSelf {
ret = ret + string(c)
} else {
ret = ret + fmt.Sprintf("&#x%x;", c)
}
}
return ret
}
package strings
import (
"testing"
)
func TestConvert(t *testing.T) {
tests := []struct {
In string
Out string
}{
{
In: "a",
Out: "a",
}, {
In: "あい",
Out: "&#x3042;&#x3044;",
}, {
In: "&gt;",
Out: "&gt;",
},
}
for _, test := range tests {
out := MultibyteToEntityString(test.In)
if out != test.Out {
t.Errorf("in: %s expected: %s but got: %s", test.In, test.Out, out)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment