Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Encoding detection fix #788

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 2 additions & 9 deletions response.go
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This needs a unit test.

Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,6 @@ import (
"net/http"
"strings"

"github.com/saintfish/chardet"
"golang.org/x/net/html/charset"
)

Expand Down Expand Up @@ -74,7 +73,6 @@ func (r *Response) fixCharset(detectCharset bool, defaultEncoding string) error
return nil
}
contentType := strings.ToLower(r.Headers.Get("Content-Type"))

if strings.Contains(contentType, "image/") ||
strings.Contains(contentType, "video/") ||
strings.Contains(contentType, "audio/") ||
Expand All @@ -88,12 +86,8 @@ func (r *Response) fixCharset(detectCharset bool, defaultEncoding string) error
if !detectCharset {
return nil
}
d := chardet.NewTextDetector()
r, err := d.DetectBest(r.Body)
if err != nil {
return err
}
contentType = "text/plain; charset=" + r.Charset
_, nameOfEncoding, _ := charset.DetermineEncoding(r.Body, contentType) //name of charset/encoding
contentType = "text/plain; charset=" + nameOfEncoding
Comment on lines +89 to +90
Copy link
Collaborator

@WGH- WGH- Oct 16, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

charset.DetermineEncoding returns the detected encoding, so I think this entire function can be greatly simplified and largely replaced with rougly this:

enc, _, certain := charset.DetermineEncoding(r.Body, contentType)
if !certain && !detectCharset {
	return nil
}
var err error
r.Body, err = ioutil.ReadAll(enc.NewDecoder().Reader(bytes.NewReader(r.Body)))
return err

}
if strings.Contains(contentType, "utf-8") || strings.Contains(contentType, "utf8") {
return nil
Expand All @@ -105,7 +99,6 @@ func (r *Response) fixCharset(detectCharset bool, defaultEncoding string) error
r.Body = tmpBody
return nil
}

func encodeBytes(b []byte, contentType string) ([]byte, error) {
r, err := charset.NewReader(bytes.NewReader(b), contentType)
if err != nil {
Expand Down
Loading