contrib: πŸ› [Bug]: I have upgraded i18n/v2, but there will still be problems.

Bug Description

Because I started with air, I can see the specific panic information only when the project stops. The contents are as follows:

panic: interface conversion: interface {} is nil, not *fiberi18n.Config

goroutine 6396 [running]:
github.com/gofiber/contrib/fiberi18n/v2.Localize(0x0?, {0x192c520?, 0xc00231f6f0})
        C:/Users/Administrator/go/pkg/mod/github.com/gofiber/contrib/fiberi18n/v2@v2.0.0/i18n.go:106 +0x2cc
github.com/gofiber/contrib/fiberi18n/v2.MustLocalize(...)
        C:/Users/Administrator/go/pkg/mod/github.com/gofiber/contrib/fiberi18n/v2@v2.0.0/i18n.go:85
github.com/biuaxia/crawling_FLiNGTrainer/pkg/i18n.Msg(0x9045ff?, {0x1a0f386, 0xf})
        C:/Users/Administrator/GolandProjects/crawling_FLiNGTrainer/pkg/i18n/i18n.go:11 +0x33
github.com/biuaxia/crawling_FLiNGTrainer/pkg/resp.(*Resp).Build(0xc00231f910)
        C:/Users/Administrator/GolandProjects/crawling_FLiNGTrainer/pkg/resp/resp.go:76 +0x3f
github.com/biuaxia/crawling_FLiNGTrainer/bootstrap.NewApplication.func2(0xc004080300, {0x1ca21a0, 0xc00029eb70})
        C:/Users/Administrator/GolandProjects/crawling_FLiNGTrainer/bootstrap/bootstrap.go:109 +0xe49
github.com/gofiber/fiber/v2.(*App).ErrorHandler(0xc0004d0a00, 0xc004080300, {0x1ca21a0, 0xc00029eb70})
        C:/Users/Administrator/go/pkg/mod/github.com/gofiber/fiber/v2@v2.49.1/app.go:1061 +0x1ff
github.com/gofiber/fiber/v2.(*App).serverErrorHandler(0xc0004d0a00, 0xc00231fc20?, {0x1ca3460, 0xc008fff590})
        C:/Users/Administrator/go/pkg/mod/github.com/gofiber/fiber/v2@v2.49.1/app.go:1093 +0x2fb
github.com/valyala/fasthttp.(*Server).writeErrorResponse(0xc0002a6c00?, 0x0, 0xc001601800, {0x0, 0x0}, {0x1ca3460?, 0xc008fff590?})
        C:/Users/Administrator/go/pkg/mod/github.com/valyala/fasthttp@v1.49.0/server.go:2850 +0x57
github.com/valyala/fasthttp.(*Server).serveConn(0xc0002a6c00, {0x1ca93c0?, 0xc002afbc00})
        C:/Users/Administrator/go/pkg/mod/github.com/valyala/fasthttp@v1.49.0/server.go:2285 +0x1de5
github.com/valyala/fasthttp.(*workerPool).workerFunc(0xc0002b0500, 0xc002f83580)
        C:/Users/Administrator/go/pkg/mod/github.com/valyala/fasthttp@v1.49.0/workerpool.go:224 +0xa4
github.com/valyala/fasthttp.(*workerPool).getCh.func1()
        C:/Users/Administrator/go/pkg/mod/github.com/valyala/fasthttp@v1.49.0/workerpool.go:196 +0x32
created by github.com/valyala/fasthttp.(*workerPool).getCh in goroutine 1
        C:/Users/Administrator/go/pkg/mod/github.com/valyala/fasthttp@v1.49.0/workerpool.go:195 +0x1ab
panic: interface conversion: interface {} is nil, not *fiberi18n.Config

goroutine 6331 [running]:
github.com/gofiber/contrib/fiberi18n/v2.Localize(0x0?, {0x192c520?, 0xc001ac16f0})
        C:/Users/Administrator/go/pkg/mod/github.com/gofiber/contrib/fiberi18n/v2@v2.0.0/i18n.go:106 +0x2cc
github.com/gofiber/contrib/fiberi18n/v2.MustLocalize(...)
        C:/Users/Administrator/go/pkg/mod/github.com/gofiber/contrib/fiberi18n/v2@v2.0.0/i18n.go:85
github.com/biuaxia/crawling_FLiNGTrainer/pkg/i18n.Msg(0x9045ff?, {0x1a0f386, 0xf})
        C:/Users/Administrator/GolandProjects/crawling_FLiNGTrainer/pkg/i18n/i18n.go:11 +0x33
github.com/biuaxia/crawling_FLiNGTrainer/pkg/resp.(*Resp).Build(0xc001ac1910)
        C:/Users/Administrator/GolandProjects/crawling_FLiNGTrainer/pkg/resp/resp.go:76 +0x3f
github.com/biuaxia/crawling_FLiNGTrainer/bootstrap.NewApplication.func2(0xc004080000, {0x1ca21a0, 0xc00029eb70})
        C:/Users/Administrator/GolandProjects/crawling_FLiNGTrainer/bootstrap/bootstrap.go:109 +0xe49
github.com/gofiber/fiber/v2.(*App).ErrorHandler(0xc0004d0a00, 0xc004080000, {0x1ca21a0, 0xc00029eb70})
        C:/Users/Administrator/go/pkg/mod/github.com/gofiber/fiber/v2@v2.49.1/app.go:1061 +0x1ff
github.com/gofiber/fiber/v2.(*App).serverErrorHandler(0xc0004d0a00, 0xc001ac1c20?, {0x1ca3460, 0xc00051b680})
        C:/Users/Administrator/go/pkg/mod/github.com/gofiber/fiber/v2@v2.49.1/app.go:1093 +0x2fb
github.com/valyala/fasthttp.(*Server).writeErrorResponse(0xc0002a6c00?, 0x0, 0xc005f81800, {0x0, 0x0}, {0x1ca3460?, 0xc00051b680?})
        C:/Users/Administrator/go/pkg/mod/github.com/valyala/fasthttp@v1.49.0/server.go:2850 +0x57
github.com/valyala/fasthttp.(*Server).serveConn(0xc0002a6c00, {0x1ca93c0?, 0xc002901c00})
        C:/Users/Administrator/go/pkg/mod/github.com/valyala/fasthttp@v1.49.0/server.go:2285 +0x1de5

This is the error message from fiber.Config 's ErrorHandler before I stopped the project:

2023-09-07 09:35:55     WARN    bootstrap/bootstrap.go:93       ErrorHandler    {"marshalString": "{\"error\":{\"code\":502,\"message\":\"Bad Gateway\"},\"errorMsg\":\"Bad Gateway\",\"exception\":{\"protocol\":\"https\",\"port\":\"62080\",\"route\":\"/\",\"resBody\":null,\"ips\":\"\",\"ua\":\"\",\"bytesSent\":0,\"queryParams\":\"\",\"requestid\":null,\"ip\":\"127.0.0.1\",\"host\":\"\",\"path\":\"/\",\"url\":\"/\",\"bytesReceived\":0,\"referer\":\"\",\"body\":\"{}\",\"reqHeaders\":{}}}"}
2023-09-07 09:35:55     WARN    bootstrap/bootstrap.go:93       ErrorHandler    {"marshalString": "{\"error\":{\"code\":502,\"message\":\"Bad Gateway\"},\"errorMsg\":\"Bad Gateway\",\"exception\":{\"body\":\"{}\",\"bytesReceived\":0,\"resBody\":null,\"requestid\":null,\"protocol\":\"https\",\"ua\":\"\",\"reqHeaders\":{},\"port\":\"61938\",\"path\":\"/\",\"bytesSent\":0,\"route\":\"/\",\"queryParams\":\"\",\"ips\":\"\",\"host\":\"\",\"url\":\"/\",\"referer\":\"\",\"ip\":\"127.0.0.1\"}}"}

This is my code for using i18n:

package i18n

import (
	"github.com/duke-git/lancet/strutil"
	"github.com/gofiber/contrib/fiberi18n/v2"
	"github.com/gofiber/fiber/v2"
	"github.com/nicksnyder/go-i18n/v2/i18n"
)

func Msg(c *fiber.Ctx, key string) string {
	i18nMsg := fiberi18n.MustLocalize(c, key)
	if !strutil.IsBlank(i18nMsg) {
		return i18nMsg
	}
	return key
}

func MsgByTemplate(c *fiber.Ctx, msgKey string, msgParamMap map[string]string) string {
	params := &i18n.LocalizeConfig{
		MessageID:    msgKey,
		TemplateData: msgParamMap,
	}
	i18nMsg := fiberi18n.MustLocalize(c, params)
	if !strutil.IsBlank(i18nMsg) {
		return i18nMsg
	}

	return msgKey
}

Say hello to the maintainers of the entire open source software, and sincerely seek relevant solutions, if you need source code reproduction problems, you can provide an email, I will send it to you.

How to Reproduce

I’m not sure about the recurrence of this problem, which is usually caused by the use of the application process.

Expected Behavior

I want him to run normally, instead of staying in 502, and the whole application stops running completely.

Fiber Version

v2.49.1

Code Snippet (optional)

ErrorHandler:


ErrorHandler: func(c *fiber.Ctx, err error) error {
	var body map[string]any
	exceptionErr := c.BodyParser(&body)
	if exceptionErr != nil {
		body = make(map[string]any)
	}
	marshalBody, exceptionErr := encoder.Encode(body, encoder.SortMapKeys)
	if exceptionErr != nil {
		marshalBody = []byte(constant.ErrorDefaultMarshalBody)
	}
	exceptionMap := fiber.Map{
		constant.ErrorExceptionMapKeyForError:    err,
		constant.ErrorExceptionMapKeyForErrorMsg: err.Error(),
		constant.ErrorExceptionMapKeyForException: fiber.Map{
			constant.FiberRequestId: c.Locals(constant.FiberRequestId),

			logger.TagReferer:           c.Get(fiber.HeaderReferer),
			logger.TagProtocol:          c.Protocol(),
			logger.TagPort:              c.Port(),
			logger.TagIP:                c.IP(),
			logger.TagIPs:               c.Get(fiber.HeaderXForwardedFor),
			logger.TagHost:              c.Hostname(),
			logger.TagPath:              c.Path(),
			logger.TagURL:               c.OriginalURL(),
			logger.TagUA:                c.Get(fiber.HeaderUserAgent),
			logger.TagBody:              string(marshalBody),
			logger.TagBytesReceived:     len(c.Request().Body()),
			logger.TagBytesSent:         len(c.Response().Body()),
			logger.TagRoute:             c.Route().Path,
			logger.TagResBody:           c.Response().Body(),
			logger.TagReqHeaders:        c.GetReqHeaders(),
			logger.TagQueryStringParams: c.Request().URI().QueryArgs().String(),
		},
	}
	marshalString, _ := sonic.MarshalString(exceptionMap)
	zap.L().Warn("ErrorHandler", zap.String("marshalString", marshalString))

	respData := resp.ERR(c).Data(exceptionMap)

	var e *fiber.Error
	if errors.As(err, &e) {
		if e.Code == fiber.StatusNotFound {
			return c.Status(fiber.StatusNotFound).SendString(i18n2.Msg(c, constant.I18N_RespPageNotFound))
		}
	}

	return respData.Build()
}

Checklist:

  • I agree to follow Fiber’s Code of Conduct.
  • I have checked for existing issues that describe my problem prior to opening this one.
  • I understand that improperly formatted bug reports may be closed without explanation.

About this issue

  • Original URL
  • State: closed
  • Created 10 months ago
  • Comments: 15 (8 by maintainers)

Most upvoted comments

pls try https://github.com/gofiber/contrib/releases/tag/fiberi18n%2Fv2.0.1

Thank you. I think this problem should be solved. I have been under stress testing since the day before yesterday. There are no more problems.

@biuaxia Whats the code creating the Fiber app and the i18n middleware?

panic: interface conversion: interface {} is nil, not *fiberi18n.Config

Code:


import(
	"github.com/apcera/termtables"
	"github.com/bytedance/sonic"
	"github.com/bytedance/sonic/encoder"
	"github.com/duke-git/lancet/v2/strutil"
	"github.com/gofiber/contrib/fiberi18n/v2"
	"github.com/gofiber/contrib/fiberzap/v2"
	"github.com/gofiber/fiber/v2"
	fiberlog "github.com/gofiber/fiber/v2/log"
	"github.com/gofiber/fiber/v2/middleware/cors"
	"github.com/gofiber/fiber/v2/middleware/favicon"
	"github.com/gofiber/fiber/v2/middleware/logger"
	"github.com/gofiber/fiber/v2/middleware/monitor"
	"github.com/gofiber/fiber/v2/middleware/recover"
	"github.com/gofiber/fiber/v2/middleware/requestid"
	"github.com/spf13/viper"
	"go.uber.org/zap"
	"golang.org/x/text/language"
	"gopkg.in/yaml.v2"
)

app := fiber.New(fiber.Config{
	ErrorHandler: func(c *fiber.Ctx, err error) error {
		var body map[string]any
		exceptionErr := c.BodyParser(&body)
		if exceptionErr != nil {
			body = make(map[string]any)
		}
		marshalBody, exceptionErr := encoder.Encode(body, encoder.SortMapKeys)
		if exceptionErr != nil {
			marshalBody = []byte(constant.ErrorDefaultMarshalBody)
		}
		exceptionMap := fiber.Map{
			constant.ErrorExceptionMapKeyForError:    err,
			constant.ErrorExceptionMapKeyForErrorMsg: err.Error(),
			constant.ErrorExceptionMapKeyForException: fiber.Map{
				constant.FiberRequestId: c.Locals(constant.FiberRequestId),

				logger.TagReferer:           c.Get(fiber.HeaderReferer),
				logger.TagProtocol:          c.Protocol(),
				logger.TagPort:              c.Port(),
				logger.TagIP:                c.IP(),
				logger.TagIPs:               c.Get(fiber.HeaderXForwardedFor),
				logger.TagHost:              c.Hostname(),
				logger.TagPath:              c.Path(),
				logger.TagURL:               c.OriginalURL(),
				logger.TagUA:                c.Get(fiber.HeaderUserAgent),
				logger.TagBody:              string(marshalBody),
				logger.TagBytesReceived:     len(c.Request().Body()),
				logger.TagBytesSent:         len(c.Response().Body()),
				logger.TagRoute:             c.Route().Path,
				logger.TagResBody:           c.Response().Body(),
				logger.TagReqHeaders:        c.GetReqHeaders(),
				logger.TagQueryStringParams: c.Request().URI().QueryArgs().String(),
			},
		}
		marshalString, _ := sonic.MarshalString(exceptionMap)
		zap.L().Warn("ErrorHandler", zap.String("marshalString", marshalString))

		respData := resp.ERR(c).Data(exceptionMap)

		var e *fiber.Error
		if errors.As(err, &e) {
			if e.Code == fiber.StatusNotFound {
				return c.Status(fiber.StatusNotFound).SendString(i18n2.Msg(c, constant.I18N_RespPageNotFound))
			}
		}

		return respData.Build()
	}
})

app.Use(fiberi18n.New(&fiberi18n.Config{
	RootPath:         constant.I18NRootPath,
	AcceptLanguages:  []language.Tag{language.Chinese, language.English},
	FormatBundleFile: constant.I18NBundleFile,
	DefaultLanguage:  language.English,
	Loader:           fiberi18n.LoaderFunc(os.ReadFile),
	UnmarshalFunc:    yaml.Unmarshal,
	LangHandler: func(c *fiber.Ctx, defaultLang string) string {
		lang := util.Lang(c)
		if strutil.IsBlank(lang) {
			return defaultLang
		}
		return lang
	},
}))