From da0b4403601d92cb162cc76080d191f9c67cfb45 Mon Sep 17 00:00:00 2001 From: awkj Date: Mon, 17 Mar 2025 23:22:54 +0800 Subject: [PATCH] Fix garbled/mojibake text display issues for non-English Unicode characters in browsers. (#441) * Update util.go Fix garbled/mojibake text display issues for non-English Unicode characters in browsers. * add Content-Disposition, help handle file name on download Author: awkj --- internal/web/handlers/gist/download.go | 2 ++ internal/web/handlers/util.go | 18 ++++++++++++++---- 2 files changed, 16 insertions(+), 4 deletions(-) diff --git a/internal/web/handlers/gist/download.go b/internal/web/handlers/gist/download.go index 86593ed..c797a84 100644 --- a/internal/web/handlers/gist/download.go +++ b/internal/web/handlers/gist/download.go @@ -21,7 +21,9 @@ func RawFile(ctx *context.Context) error { return ctx.NotFound("File not found") } contentType := handlers.GetContentTypeFromFilename(file.Filename) + ContentDisposition := handlers.GetContentDisposition(file.Filename) ctx.Response().Header().Set("Content-Type", contentType) + ctx.Response().Header().Set("Content-Disposition", ContentDisposition) return ctx.PlainText(200, file.Content) } diff --git a/internal/web/handlers/util.go b/internal/web/handlers/util.go index af39240..3bda0e5 100644 --- a/internal/web/handlers/util.go +++ b/internal/web/handlers/util.go @@ -2,13 +2,14 @@ package handlers import ( "errors" - "github.com/gorilla/schema" "html/template" "net/url" "path/filepath" "strconv" "strings" + "github.com/gorilla/schema" + "github.com/thomiceli/opengist/internal/web/context" ) @@ -141,12 +142,21 @@ func ParseSearchQueryStr(query string) (string, map[string]string) { return content, metadata } -func GetContentTypeFromFilename(filename string) string { +func GetContentTypeFromFilename(filename string) (ret string) { ext := strings.ToLower(filepath.Ext(filename)) + switch ext { case ".css": - return "text/css" + ret = "text/css" default: - return "text/plain" + ret = "text/plain" } + + // add charset=utf-8, if not, unicode charset will be broken + ret += "; charset=utf-8" + return +} + +func GetContentDisposition(filename string) string { + return "inline; filename=\"" + filename + "\"" }