Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

proposal: x/text/cmd/gotext: enhance gotext to support automatic text extraction from functions for Internationalization #64736

Open
mzmuer opened this issue Dec 15, 2023 · 0 comments
Labels
Milestone

Comments

@mzmuer
Copy link

mzmuer commented Dec 15, 2023

Proposal Details

I am developing a simple web application in Go and need to provide internationalized error descriptions. I attempted to use the x/text package along with its gotext command-line tool to achieve this.

What I'm trying to achieve:

I have multiple instances of the same error message, and I aim to avoid code duplication by using a function. Below is the relevant code snippet:

type Error struct {
	Code    int    `json:"code"`
	Message string `json:"message"`
}

type i18nFactory func(lang string, a ...any) Error

func factory(code int, key string) i18nFactory {
	return func(lang string, a ...any) Error {
		langTag := message.MatchLanguage(lang)
		p := message.NewPrinter(langTag)

		return Error{
			Code:    code,
			Message: p.Sprintf(key, a...),
		}
	}
}

var err1 i18nFactory = factory(http.StatusInternalServerError, "Internal Server Error1")

var err2 i18nFactory = func(lang string, a ...any) Error {
	langTag := message.MatchLanguage(lang)
	p := message.NewPrinter(langTag)

	return Error{
		Code:    2,
		Message: p.Sprintf("Internal Server Error2", a...),
	}
}

I hoped that the gotext tool could assist me in extracting text, but it seems to only work for err2 and not for err1. The extracted JSON for err2 is as follows:

{
    "language": "en",
    "messages": [
        {
            "id": "Internal Server Error2",
            "message": "Internal Server Error2",
            "translation": "Internal Server Error2",
            "translatorComment": "Copied from source.",
            "placeholders": [
                {
                    "id": "A",
                    "string": "%[1]v",
                    "type": "[]any",
                    "underlyingType": "[]any",
                    "argNum": 1,
                    "expr": "a"
                }
            ],
            "fuzzy": true
        }
    ]
}

Feature request

It would be immensely helpful if gotext could automatically extract text from functions. Since err1 and err2 appear similar, both being of type i18nFactory, having gotext recognize and extract text from such functions would be a valuable addition.

@gopherbot gopherbot added this to the Proposal milestone Dec 15, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
Status: Incoming
Development

No branches or pull requests

2 participants