Skip to content

Commit

Permalink
Fix possible problem with UTF-8 symbols
Browse files Browse the repository at this point in the history
  • Loading branch information
airenas committed Dec 23, 2022
1 parent 624be54 commit d22bc1b
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 4 deletions.
14 changes: 10 additions & 4 deletions pkg/goapp/utils.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import (
"time"
)

//HidePass removes pass from URL
// HidePass removes pass from URL
func HidePass(link string) string {
u, err := url.Parse(link)
if err != nil {
Expand All @@ -22,7 +22,7 @@ func HidePass(link string) string {
return u.String()
}

//Estimate estimates and logs execution duration
// Estimate estimates and logs execution duration
// sample: defer goapp.Estimate("function")()
func Estimate(name string) func() {
start := time.Now()
Expand All @@ -31,7 +31,7 @@ func Estimate(name string) func() {
}
}

//ValidateHTTPResp returns error if code is not in [200, 299]
// ValidateHTTPResp returns error if code is not in [200, 299]
// bodyLen - size of bytes to try read body
func ValidateHTTPResp(resp *http.Response, bodyLen int) error {
if !(resp.StatusCode >= 200 && resp.StatusCode <= 299) {
Expand All @@ -47,7 +47,13 @@ func getBodyStr(rd io.Reader, l int) string {
Log.Warn().Err(err).Send()
}
if len(bytes) > l {
return "\n" + string(bytes[:l]) + "..."
// use runes to make sure we don't crack utf-8
// and drop last symbol
rns := []rune(string(bytes))
if len(rns) > 0 {
rns = rns[:len(rns)-1]
}
return "\n" + string(rns) + "..."
}
if len(bytes) > 0 {
return "\n" + string(bytes)
Expand Down
1 change: 1 addition & 0 deletions pkg/goapp/utils_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,7 @@ func Test_getBodyStr(t *testing.T) {
{name: "Trim", rd: strings.NewReader(strings.Repeat("a", 20)), l: 10, want: "\n" + strings.Repeat("a", 10) + "..."},
{name: "Full", rd: strings.NewReader(strings.Repeat("a", 20)), l: 20, want: "\n" + strings.Repeat("a", 20)},
{name: "Long", rd: strings.NewReader(strings.Repeat("a", 20000)), l: 20000, want: "\n" + strings.Repeat("a", 20000)},
{name: "UTF-8 symbols", rd: strings.NewReader("ĄČĘĖĮĄČĘĖĮ"), l: 5, want: "\nĄČ..."},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
Expand Down

0 comments on commit d22bc1b

Please sign in to comment.