Open-source LLM knowledge platform: turn raw documents into a queryable RAG, an autonomous reasoning agent, and a self-maintaining Wiki.
Go agentagenticaichatbotdsh-pluginembeddingsevaluationgenerative-aigolangknowledge-basellmmulti-tenantollamaopenaiquestion-answeringragrerankingsemantic-searchvector-searchwiki
fix(web_fetch): decode non-UTF-8 HTML pages by declared charset (#4556)
Clint5839a611c0b1
diff --git a/internal/infrastructure/web_fetch/fetcher.go b/internal/infrastructure/web_fetch/fetcher.goindex 56214ccc3..f9b0ab37d 100644--- a/internal/infrastructure/web_fetch/fetcher.go+++ b/internal/infrastructure/web_fetch/fetcher.go@@ -21,6 +21,8 @@ import ("github.com/Tencent/WeKnora/internal/logger""github.com/Tencent/WeKnora/internal/utils""github.com/chromedp/chromedp"+ "golang.org/x/net/html/charset"+ "golang.org/x/text/encoding")const (@@ -270,10 +272,14 @@ func (f *Fetcher) fetchHTTP(ctx context.Context, rawURL string, parsedURL *url.Uif f.markdown && int64(len(body)) > f.maxBodySize {return nil, newFetchError(ErrorBodyTooLarge, false, "page exceeds the %d byte download limit", f.maxBodySize)}- contentType, _, _ := mime.ParseMediaType(resp.Header.Get("Content-Type"))+ rawContentType := resp.Header.Get("Content-Type")+ contentType, _, _ := mime.ParseMediaType(rawContentType)if contentType == "" {contentType, _, _ = mime.ParseMediaType(http.DetectContentType(body))}+ if isHTMLContent(contentType) {+ body = decodeHTMLBody(body, rawContentType)+ }finalURL := rawURLif resp.Request != nil && resp.Request.URL != nil {finalURL = resp.Request.URL.String()@@ -281,6 +287,25 @@ func (f *Fetcher) fetchHTTP(ctx context.Context, rawURL string, parsedURL *url.Ureturn &httpFetchResult{body: body, finalURL: finalURL, contentType: contentType}, nil}+// decodeHTMLBody converts an HTML body to UTF-8 when the page declares a+// different charset through a BOM, the Content-Type header, or a <meta> tag.+// Valid UTF-8 and undeclared bodies are returned unchanged: the HTML default+// (windows-1252) would corrupt undeclared UTF-8 pages with an ASCII-only head.+func decodeHTMLBody(body []byte, contentType string) []byte {+ if utf8.Valid(body) {+ return body+ }+ enc, name, certain := charset.DetermineEncoding(body, contentType)+ if enc == encoding.Nop || (!certain && name == "windows-1252") {+ return body+ }+ decoded, err := enc.NewDecoder().Bytes(body)+ if err != nil {+ return body+ }+ return decoded+}+func (f *Fetcher) pinnedDialContext() func(context.Context, string, string) (net.Conn, error) {return func(ctx context.Context, network, address string) (net.Conn, error) {host, port, err := net.SplitHostPort(address)diff --git a/internal/infrastructure/web_fetch/fetcher_charset_test.go b/internal/infrastructure/web_fetch/fetcher_charset_test.gonew file mode 100644index 000000000..015048552--- /dev/null+++ b/internal/infrastructure/web_fetch/fetcher_charset_test.go@@ -0,0 +1,75 @@+package web_fetch++import (+ "context"+ "net/http"+ "net/http/httptest"+ "strings"+ "testing"++ "github.com/stretchr/testify/assert"+ "github.com/stretchr/testify/require"+ "golang.org/x/text/encoding/simplifiedchinese"+)++func TestFetcherDecodesHTMLCharset(t *testing.T) {+ const text = "腾讯知识库网页正文"+ gbk := func(html string) []byte {+ encoded, err := simplifiedchinese.GBK.NewEncoder().String(html)+ require.NoError(t, err)+ return []byte(encoded)+ }+ // An ASCII-only first KB with no declared charset must still be read as UTF-8.+ asciiPrefix := "<!-- " + strings.Repeat("x", 1100) + " -->"++ for _, tc := range []struct {+ name string+ contentType string+ body []byte+ }{+ {+ name: "gbk header",+ contentType: "text/html; charset=gbk",+ body: gbk("<html><body><main>" + text + "</main></body></html>"),+ },+ {+ name: "gbk meta only",+ contentType: "text/html",+ body: gbk(`<html><head><meta charset="gbk"></head><body><main>` + text + "</main></body></html>"),+ },+ {+ name: "utf-8 header",+ contentType: "text/html; charset=utf-8",+ body: []byte("<html><body><main>" + text + "</main></body></html>"),+ },+ {+ name: "undeclared utf-8",+ contentType: "text/html",+ body: []byte("<html>" + asciiPrefix + "<body><main>" + text + "</main></body></html>"),+ },+ } {+ for _, markdown := range []bool{false, true} {+ name := tc.name + "/pipeline"+ if markdown {+ name = tc.name + "/agent"+ }+ t.Run(name, func(t *testing.T) {+ server := httptest.NewServer(http.HandlerFunc(func(writer http.ResponseWriter, _ *http.Request) {+ writer.Header().Set("Content-Type", tc.contentType)+ _, _ = writer.Write(tc.body)+ }))+ defer server.Close()++ fetcher := newTestFetcher(server.Client())+ if markdown {+ fetcher.markdown = true+ fetcher.maxBodySize = maxAgentBodySize+ }+ content, err := fetcher.Fetch(context.Background(), server.URL)++ require.NoError(t, err)+ assert.Contains(t, content, text)+ })+ }+ }+}