MSP-8438 Add setting for overriding standart json content-header to "application/json; charset=utf-8"

This commit is contained in:
Синельник Тимур Романович committed 2026-08-28 14:07:53 +03:00
1 parent 72f2d37920
commit 2fb58a7195
5 files changed
+50

No files matched your search

+6
View File
@@ -124,6 +124,11 @@ func (l Locator) Handler(config conf.Remote, locations []conf.Location) (http.Ha
forwardReqIdByAppId[setting.ApplicationId] = setting.ForwardRequestId forwardReqIdByAppId[setting.ApplicationId] = setting.ForwardRequestId
} }
enableUtf8JsonCharsetByApp := make(map[int]bool, len(config.ResponseContentTypeSettings))
for _, setting := range config.ResponseContentTypeSettings {
enableUtf8JsonCharsetByApp[setting.ApplicationId] = setting.AddJsonUtf8Charset
}
metricsStorage := http_metrics.NewServerStorage(metrics.DefaultRegistry) metricsStorage := http_metrics.NewServerStorage(metrics.DefaultRegistry)
handler := middleware.Chain( handler := middleware.Chain(
@@ -140,6 +145,7 @@ func (l Locator) Handler(config conf.Remote, locations []conf.Location) (http.Ha
middleware.Authenticate(authentication), middleware.Authenticate(authentication),
middleware.AdminAuthenticate(adminService), middleware.AdminAuthenticate(adminService),
middleware.ClientRequestId(config.EnableClientRequestIdForwarding, forwardReqIdByAppId), middleware.ClientRequestId(config.EnableClientRequestIdForwarding, forwardReqIdByAppId),
middleware.JsonResponseUtf8Charset(enableUtf8JsonCharsetByApp),
middleware.Authorize(authorization, l.logger), middleware.Authorize(authorization, l.logger),
middleware.AdminAuthorize(adminService), middleware.AdminAuthorize(adminService),
middleware.Throttling(throttlingService), middleware.Throttling(throttlingService),
+6
View File
@@ -30,6 +30,7 @@ type Remote struct {
EnableClientRequestIdForwarding bool `schema:"Включить проброс requestId из заголовка запроса"` EnableClientRequestIdForwarding bool `schema:"Включить проброс requestId из заголовка запроса"`
ForwardReqIdClientSettings []ForwardReqIdClientSettings `schema:"Настройки проброcа requestId для приложений"` ForwardReqIdClientSettings []ForwardReqIdClientSettings `schema:"Настройки проброcа requestId для приложений"`
CustomAuth CustomAuth `schema:"Настройка кастомной аутентификации/авторизации"` CustomAuth CustomAuth `schema:"Настройка кастомной аутентификации/авторизации"`
ResponseContentTypeSettings []ResponseContentTypeSetting `schema:"Настройки Content-Type ответов"`
} }
type ForwardReqIdClientSettings struct { type ForwardReqIdClientSettings struct {
@@ -98,3 +99,8 @@ type UserAuthSetting struct {
CacheDataInSec int `schema:"Время кеширования данных аутентификации/авторизации пользователя,отключен при значениях <=0,в секундах"` CacheDataInSec int `schema:"Время кеширования данных аутентификации/авторизации пользователя,отключен при значениях <=0,в секундах"`
SkipAppAuth bool `schema:"Пропустить аутентификацию и авторизацию приложения"` SkipAppAuth bool `schema:"Пропустить аутентификацию и авторизацию приложения"`
} }
type ResponseContentTypeSetting struct {
ApplicationId int `validate:"required" schema:"ID приложения"`
AddJsonUtf8Charset bool `schema:"Добавлять charset=utf-8 в Content-Type ответа: application/json для locations с protocol=http"`
}
+15
View File
@@ -0,0 +1,15 @@
package middleware
import (
"isp-gate-service/request"
)
func JsonResponseUtf8Charset(applicationIds map[int]bool) Middleware {
return func(next Handler) Handler {
return HandlerFunc(func(ctx *request.Context) error {
authData, _ := ctx.GetAuthData()
ctx.EnableHttpJsonUtf8Charset(applicationIds[authData.ApplicationId])
return next.Handle(ctx)
})
}
}
+13
View File
@@ -9,6 +9,7 @@ import (
"net/http/httputil" "net/http/httputil"
"net/url" "net/url"
"strconv" "strconv"
"strings"
"time" "time"
"isp-gate-service/httperrors" "isp-gate-service/httperrors"
@@ -79,6 +80,9 @@ func (p Http) Handle(ctx *request.Context) error {
errors.WithMessagef(err, "http proxy to %s", host), errors.WithMessagef(err, "http proxy to %s", host),
) )
} }
if ctx.IsJsonUtf8CharsetEnabled() {
reverseProxy.ModifyResponse = addJsonUtf8Charset
}
context, cancel := context.WithTimeout(request.Context(), p.timeout) context, cancel := context.WithTimeout(request.Context(), p.timeout)
defer cancel() defer cancel()
@@ -124,3 +128,12 @@ func setHttpHeaders(ctx *request.Context, header http.Header, skipAuth bool) {
func defaultTransportDialContext(dialer *net.Dialer) func(context.Context, string, string) (net.Conn, error) { func defaultTransportDialContext(dialer *net.Dialer) func(context.Context, string, string) (net.Conn, error) {
return dialer.DialContext return dialer.DialContext
} }
func addJsonUtf8Charset(response *http.Response) error {
contentType := response.Header.Get("Content-Type")
if strings.EqualFold(contentType, "application/json") {
response.Header.Set("Content-Type", "application/json; charset=utf-8")
}
return nil
}
+10
View File
@@ -30,6 +30,8 @@ type Context struct {
adminToken string adminToken string
queryParams map[string]string queryParams map[string]string
httpJsonUtf8Charset bool
} }
func NewContext( func NewContext(
@@ -114,6 +116,14 @@ func (c *Context) SetContext(ctx context.Context) {
c.request = c.request.WithContext(ctx) c.request = c.request.WithContext(ctx)
} }
func (c *Context) EnableHttpJsonUtf8Charset(enable bool) {
c.httpJsonUtf8Charset = enable
}
func (c *Context) IsJsonUtf8CharsetEnabled() bool {
return c.httpJsonUtf8Charset
}
func (c *Context) Param(name string) string { func (c *Context) Param(name string) string {
value := c.request.Header.Get(name) value := c.request.Header.Get(name)
if value != "" { if value != "" {