gofiber / fiber

⚡️ Express inspired web framework written in Go
https://gofiber.io
MIT License
33.18k stars 1.64k forks source link

🤗 [Question]: How to implement internationalization for parameter validation in V3 #3117

Open layxyer opened 2 weeks ago

layxyer commented 2 weeks ago

Question Description

I tried some methods, but the binding validators provided by version 3 lack context information, making it impossible to obtain the user's preferred language information and perform internationalization translations during validation. Although translation can be done in each route, this approach is somewhat repetitive and cumbersome.It would be great if a context parameter could be added to the validator interface, or if there is a better way that I haven't discovered yet.

Code Snippet (optional)

type structValidator struct {
    validate *validator.Validate
}

// Validate needs to implement the Validate method
func (v *structValidator) Validate(out any, c fiber.Ctx) error {
    langs := c.GetReqHeaders()["Accept-Language"]
    lang := "en"
    if len(langs) > 0 {
        lang = langs[0]
    }
    trans, err := getTranslator(lang)
    if err != nil {
        return err
    }
    err = validate.Struct(out)
    i18nError := []string{}
    if err != nil {
        if errs, ok := err.(validator.ValidationErrors); ok {
            for _, e := range errs {
                i18nError = append(i18nError, e.Translate(trans))
            }
        } else {
            fmt.Println(err)
        }
    }
    return errors.New(fmt.Sprintf("%v", i18nError))
}

Checklist:

welcome[bot] commented 2 weeks ago

Thanks for opening your first issue here! 🎉 Be sure to follow the issue template! If you need help or want to chat with us, join us on Discord https://gofiber.io/discord

gaby commented 2 weeks ago

@layxyer What do you mean by but the binding validators provided by version 3 lack context information ?

Btw you can use this, to check if en is in the headers.

ctx.AcceptsLanguages("en")

This will return "en", if the request has the value in the Header.

layxyer commented 1 week ago

@layxyer你的意思是什么but the binding validators provided by version 3 lack context information

顺便说一句,您可以使用它来检查是否en在标题中。

ctx.AcceptsLanguages("en")

"en"如果请求的 Header 中有值,则将返回。 I mean the validator method does not have a ctx parameter, so it cannot obtain language information.

layxyer commented 1 week ago

@layxyer你的意思是but the binding validators provided by version 3 lack context information

顺便说一句,你可以用它来检查是否en在标题中。

ctx.AcceptsLanguages("en")

"en"如果请求的 Header 包含值,则将返回。

I added the ctx parameter to the Validate method in the example code, but in fact, the official method does not include this parameter.

Skyenought commented 1 week ago

@layxyer 我认为在现在的阶段, 你只能用额外的方法进行参数的校验和替换了

I think at this situatiom, you can only use additional methods for parameter checking and substitution